Passed
Push — 1.10.x ( aeb152...c6d0a9 )
by Yannick
176:52 queued 127:28
created

learnpath::set_encoding()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 8.6737
cc 5
eloc 15
nc 12
nop 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CLpCategory;
5
use ChamiloSession as Session;
6
7
/**
8
 * Class learnpath
9
 * This class defines the parent attributes and methods for Chamilo learnpaths
10
 * and SCORM learnpaths. It is used by the scorm class.
11
 *
12
 * @package chamilo.learnpath
13
 * @author	Yannick Warnier <[email protected]>
14
 * @author	Julio Montoya   <[email protected]> Several improvements and fixes
15
 */
16
class learnpath
17
{
18
    public $attempt = 0; // The number for the current ID view.
19
    public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
20
    public $current; // Id of the current item the user is viewing.
21
    public $current_score; // The score of the current item.
22
    public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
23
    public $current_time_stop; // The time the user closed this resource.
24
    public $default_status = 'not attempted';
25
    public $encoding = 'UTF-8';
26
    public $error = '';
27
    public $extra_information = ''; // This string can be used by proprietary SCORM contents to store data about the current learnpath.
28
    public $force_commit = false; // For SCORM only - if set to true, will send a scorm LMSCommit() request on each LMSSetValue().
29
    public $index; // The index of the active learnpath_item in $ordered_items array.
30
    public $items = array();
31
    public $last; // item_id of last item viewed in the learning path.
32
    public $last_item_seen = 0; // In case we have already come in this learnpath, reuse the last item seen if authorized.
33
    public $license; // Which license this course has been given - not used yet on 20060522.
34
    public $lp_id; // DB ID for this learnpath.
35
    public $lp_view_id; // DB ID for lp_view
36
    public $log_file; // File where to log learnpath API msg.
37
    public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
38
    public $message = '';
39
    public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
40
    public $name; // Learnpath name (they generally have one).
41
    public $ordered_items = array(); // List of the learnpath items in the order they are to be read.
42
    public $path = ''; // Path inside the scorm directory (if scorm).
43
    public $theme; // The current theme of the learning path.
44
    public $preview_image; // The current image of the learning path.
45
46
    // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
47
    public $prevent_reinit = 1;
48
49
    // Describes the mode of progress bar display.
50
    public $seriousgame_mode = 0;
51
    public $progress_bar_mode = '%';
52
53
    // Percentage progress as saved in the db.
54
    public $progress_db = '0';
55
    public $proximity; // Wether the content is distant or local or unknown.
56
    public $refs_list = array (); //list of items by ref => db_id. Used only for prerequisites match.
57
    // !!!This array (refs_list) is built differently depending on the nature of the LP.
58
    // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
59
    public $type; //type of learnpath. Could be 'dokeos', 'scorm', 'scorm2004', 'aicc', ...
60
    // TODO: Check if this type variable is useful here (instead of just in the controller script).
61
    public $user_id; //ID of the user that is viewing/using the course
62
    public $update_queue = array();
63
    public $scorm_debug = 0;
64
    public $arrMenu = array(); // Array for the menu items.
65
    public $debug = 0; // Logging level.
66
    public $lp_session_id = 0;
67
    public $lp_view_session_id = 0; // The specific view might be bound to a session.
68
    public $prerequisite = 0;
69
    public $use_max_score = 1; // 1 or 0
70
    public $subscribeUsers = 0; // Subscribe users or not
71
    public $created_on      = '';
72
    public $modified_on     = '';
73
    public $publicated_on   = '';
74
    public $expired_on      = '';
75
    public $ref = null;
76
    public $course_int_id;
77
    public $course_info = array();
78
    public $categoryId;
79
80
    /**
81
     * Constructor.
82
     * Needs a database handler, a course code and a learnpath id from the database.
83
     * Also builds the list of items into $this->items.
84
     * @param	string	$course Course code
85
     * @param	integer	$lp_id
86
     * @param	integer	$user_id
87
     * @return mixed True on success, false on error
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...
88
     */
89
    public function __construct($course, $lp_id, $user_id)
90
    {
91
        $this->encoding = api_get_system_encoding();
92 View Code Duplication
        if ($this->debug > 0) {
93
            error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0);
94
        }
95
        if (empty($course)) {
96
            $this->error = 'Course code is empty';
97
            return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
98
        } else {
99
            $course_info = api_get_course_info($course);
100
            if (!empty($course_info)) {
101
                $this->cc = $course_info['code'];
102
                $this->course_info = $course_info;
103
                $course_id = $course_info['real_id'];
104
            } else {
105
                $this->error = 'Course code does not exist in database.';
106
                return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
107
            }
108
        }
109
110
        $this->set_course_int_id($course_id);
111
112
        // Check learnpath ID.
113
        if (empty($lp_id)) {
114
            $this->error = 'Learnpath ID is empty';
115
            return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
116
        } else {
117
            // TODO: Make it flexible to use any course_code (still using env course code here).
118
            $lp_table = Database::get_course_table(TABLE_LP_MAIN);
119
            $lp_id = intval($lp_id);
120
            $sql = "SELECT * FROM $lp_table
121
                    WHERE id = '$lp_id' AND c_id = $course_id";
122
            if ($this->debug > 2) {
123
                error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
124
            }
125
            $res = Database::query($sql);
126
127
            if (Database::num_rows($res) > 0) {
128
                $this->lp_id = $lp_id;
129
                $row = Database::fetch_array($res);
130
                $this->type = $row['lp_type'];
131
                $this->name = stripslashes($row['name']);
132
                $this->proximity = $row['content_local'];
133
                $this->theme = $row['theme'];
134
                $this->maker = $row['content_maker'];
135
                $this->prevent_reinit = $row['prevent_reinit'];
136
                $this->seriousgame_mode = $row['seriousgame_mode'];
137
                $this->license = $row['content_license'];
138
                $this->scorm_debug = $row['debug'];
139
                $this->js_lib = $row['js_lib'];
140
                $this->path = $row['path'];
141
                $this->preview_image = $row['preview_image'];
142
                $this->author = $row['author'];
143
                $this->hide_toc_frame = $row['hide_toc_frame'];
144
                $this->lp_session_id = $row['session_id'];
145
                $this->use_max_score = $row['use_max_score'];
146
                $this->subscribeUsers = $row['subscribe_users'];
147
                $this->created_on = $row['created_on'];
148
                $this->modified_on = $row['modified_on'];
149
                $this->ref = $row['ref'];
150
                $this->categoryId = $row['category_id'];
151
152
                if ($row['publicated_on'] != '0000-00-00 00:00:00') {
153
                    $this->publicated_on = $row['publicated_on'];
154
                }
155
156
                if ($row['expired_on'] != '0000-00-00 00:00:00') {
157
                    $this->expired_on  = $row['expired_on'];
158
                }
159 View Code Duplication
                if ($this->type == 2) {
160
                    if ($row['force_commit'] == 1) {
161
                        $this->force_commit = true;
162
                    }
163
                }
164
                $this->mode = $row['default_view_mod'];
165
            } else {
166
                $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
167
168
                return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
169
            }
170
        }
171
172
        // Check user ID.
173
        if (empty($user_id)) {
174
            $this->error = 'User ID is empty';
175
176
            return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
177
        } else {
178
            $user_info = api_get_user_info($user_id);
179
            if (!empty($user_info)) {
180
                $this->user_id = $user_info['user_id'];
181
            } else {
182
                $this->error = 'User ID does not exist in database ('.$sql.')';
183
184
                return false;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
185
            }
186
        }
187
188
        // End of variables checking.
189
        $session_id = api_get_session_id();
190
        //  Get the session condition for learning paths of the base + session.
191
        $session = api_get_session_condition($session_id);
192
        // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
193
        $lp_table = Database::get_course_table(TABLE_LP_VIEW);
194
195
        // Selecting by view_count descending allows to get the highest view_count first.
196
        $sql = "SELECT * FROM $lp_table
197
                WHERE c_id = $course_id AND lp_id = '$lp_id' AND user_id = '$user_id' $session
198
                ORDER BY view_count DESC";
199
        $res = Database::query($sql);
200
        if ($this->debug > 2) {
201
            error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - querying lp_view: ' . $sql, 0);
202
        }
203
204
        if (Database :: num_rows($res) > 0) {
205
            if ($this->debug > 2) {
206
                error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - Found previous view', 0);
207
            }
208
            $row = Database :: fetch_array($res);
209
            $this->attempt = $row['view_count'];
210
            $this->lp_view_id = $row['id'];
211
            $this->last_item_seen = $row['last_item'];
212
            $this->progress_db = $row['progress'];
213
            $this->lp_view_session_id = $row['session_id'];
214
        } else if (!api_is_invitee()) {
215
            if ($this->debug > 2) {
216
                error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - NOT Found previous view', 0);
217
            }
218
            $this->attempt = 1;
219
            $params = [
220
                'c_id' => $course_id,
221
                'lp_id' => $lp_id,
222
                'user_id' => $user_id,
223
                'view_count' => 1,
224
                'session_id' => $session_id,
225
                'last_item' => 0
226
            ];
227
            Database::insert($lp_table, $params);
228
            $this->lp_view_id = Database::insert_id();
229
230
            if ($this->debug > 2) {
231
                error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - inserting new lp_view: ' . $sql, 0);
232
            }
233
234
            $sql = "UPDATE $lp_table SET id = iid WHERE iid = ".$this->lp_view_id;
235
            Database::query($sql);
236
        }
237
238
        // Initialise items.
239
        $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
240
        $sql = "SELECT * FROM $lp_item_table
241
                WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
242
                ORDER BY parent_item_id, display_order";
243
        $res = Database::query($sql);
244
245
        if ($this->debug > 2) {
246
            error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - query lp items: ' . $sql, 0);
247
            error_log('-- Start while--', 0);
248
        }
249
250
        $lp_item_id_list = array();
251
252
        while ($row = Database::fetch_array($res)) {
253
            $lp_item_id_list[] = $row['id'];
254
            switch ($this->type) {
255 View Code Duplication
                case 3: //aicc
256
                    $oItem = new aiccItem('db', $row['id'], $course_id);
257
                    if (is_object($oItem)) {
258
                        $my_item_id = $oItem->get_id();
259
                        $oItem->set_lp_view($this->lp_view_id, $course_id);
260
                        $oItem->set_prevent_reinit($this->prevent_reinit);
261
                        // Don't use reference here as the next loop will make the pointed object change.
262
                        $this->items[$my_item_id] = $oItem;
263
                        $this->refs_list[$oItem->ref] = $my_item_id;
264
                        if ($this->debug > 2) {
265
                            error_log(
266
                                'New LP - learnpath::__construct() - ' .
267
                                'aicc object with id ' . $my_item_id .
268
                                ' set in items[]',
269
                                0
270
                            );
271
                        }
272
                    }
273
                    break;
274 View Code Duplication
                case 2:
275
                    $oItem = new scormItem('db', $row['id'], $course_id);
276
                    if (is_object($oItem)) {
277
                        $my_item_id = $oItem->get_id();
278
                        $oItem->set_lp_view($this->lp_view_id, $course_id);
279
                        $oItem->set_prevent_reinit($this->prevent_reinit);
280
                        // Don't use reference here as the next loop will make the pointed object change.
281
282
                        $this->items[$my_item_id] = $oItem;
283
284
                        $this->refs_list[$oItem->ref] = $my_item_id;
285
                        if ($this->debug > 2) {
286
                            error_log('New LP - object with id ' . $my_item_id . ' set in items[]', 0);
287
                        }
288
                    }
289
                    break;
290
                case 1:
291
                default:
292
                    if ($this->debug > 2) {
293
                        error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - calling learnpathItem', 0);
294
                    }
295
                    $oItem = new learnpathItem($row['id'], $user_id, $course_id, $row);
296
297
                    if ($this->debug > 2) {
298
                        error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - end calling learnpathItem', 0);
299
                    }
300
                    if (is_object($oItem)) {
301
                        $my_item_id = $oItem->get_id();
302
                        //$oItem->set_lp_view($this->lp_view_id); // Moved down to when we are sure the item_view exists.
303
                        $oItem->set_prevent_reinit($this->prevent_reinit);
304
                        // Don't use reference here as the next loop will make the pointed object change.
305
                        $this->items[$my_item_id] = $oItem;
306
                        $this->refs_list[$my_item_id] = $my_item_id;
307 View Code Duplication
                        if ($this->debug > 2) {
308
                            error_log(
309
                                'New LP - learnpath::__construct() ' . __LINE__ .
310
                                ' - object with id ' . $my_item_id . ' set in items[]',
311
                                0);
312
                        }
313
                    }
314
                    break;
315
            }
316
317
            // Setting the object level with variable $this->items[$i][parent]
318
            foreach ($this->items as $itemLPObject) {
319
                $level = learnpath::get_level_for_item($this->items, $itemLPObject->db_id);
320
                $itemLPObject->level = $level;
321
            }
322
323
            // Setting the view in the item object.
324
            if (is_object($this->items[$row['id']])) {
325
                $this->items[$row['id']]->set_lp_view($this->lp_view_id, $course_id);
326
                if ($this->items[$row['id']]->get_type() == TOOL_HOTPOTATOES) {
327
                    $this->items[$row['id']]->current_start_time = 0;
328
                    $this->items[$row['id']]->current_stop_time	= 0;
329
                }
330
            }
331
        }
332
333
        if ($this->debug > 2) {
334
            error_log('New LP - learnpath::__construct() ' . __LINE__ . ' ----- end while ----', 0);
335
        }
336
337
        if (!empty($lp_item_id_list)) {
338
            $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
339
            if (!empty($lp_item_id_list_to_string)) {
340
                // Get last viewing vars.
341
                $lp_item_view_table = Database:: get_course_table(
342
                    TABLE_LP_ITEM_VIEW
343
                );
344
                // This query should only return one or zero result.
345
                $sql = "SELECT lp_item_id, status
346
                        FROM $lp_item_view_table
347
                        WHERE
348
                            c_id = $course_id AND
349
                            lp_view_id = ".$this->lp_view_id." AND
350
                            lp_item_id IN ('".$lp_item_id_list_to_string."')
351
                        ORDER BY view_count DESC ";
352
353
                if ($this->debug > 2) {
354
                    error_log(
355
                        'New LP - learnpath::__construct() - Selecting item_views: '.$sql,
356
                        0
357
                    );
358
                }
359
360
                $status_list = array();
361
                $res = Database::query($sql);
362
                while ($row = Database:: fetch_array($res)) {
363
                    $status_list[$row['lp_item_id']] = $row['status'];
364
                }
365
366
                foreach ($lp_item_id_list as $item_id) {
367
                    if (isset($status_list[$item_id])) {
368
                        $status = $status_list[$item_id];
369
                        if (is_object($this->items[$item_id])) {
370
                            $this->items[$item_id]->set_status($status);
371
                            if (empty($status)) {
372
                                $this->items[$item_id]->set_status(
373
                                    $this->default_status
374
                                );
375
                            }
376
                        }
377
                    } else {
378
                        if (!api_is_invitee()) {
379
                            if (is_object($this->items[$item_id])) {
380
                                $this->items[$item_id]->set_status(
381
                                    $this->default_status
382
                                );
383
                            }
384
385
                            // Add that row to the lp_item_view table so that we have something to show in the stats page.
386
                            $sql = "INSERT INTO $lp_item_view_table (c_id, lp_item_id, lp_view_id, view_count, status, start_time, total_time, score)
387
                                    VALUES ($course_id, ".$item_id.",".$this->lp_view_id.", 1, 'not attempted', '".time()."', 0, 0)";
388
389
                            if ($this->debug > 2) {
390
                                error_log(
391
                                    'New LP - learnpath::__construct() '.__LINE__.' - Inserting blank item_view : '.$sql,
392
                                    0
393
                                );
394
                            }
395
                            $this->items[$item_id]->set_lp_view(
396
                                $this->lp_view_id,
397
                                $course_id
398
                            );
399
400
                            Database::query($sql);
401
                            $insertId = Database::insert_id();
402
403
                            $sql = "UPDATE $lp_item_view_table SET id = iid
404
                                    WHERE iid = $insertId";
405
                            Database::query($sql);
406
                        }
407
                    }
408
                }
409
            }
410
        }
411
412
        $this->ordered_items = self::get_flat_ordered_items_list(
0 ignored issues
show
Documentation Bug introduced by
It seems like self::get_flat_ordered_i...et_id(), 0, $course_id) can also be of type false. However, the property $ordered_items is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
413
            $this->get_id(),
414
            0,
415
            $course_id
416
        );
417
        $this->max_ordered_items = 0;
418
        foreach ($this->ordered_items as $index => $dummy) {
0 ignored issues
show
Bug introduced by
The expression $this->ordered_items of type false|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
419
            if ($index > $this->max_ordered_items && !empty($dummy)) {
420
                $this->max_ordered_items = $index;
421
            }
422
        }
423
        // TODO: Define the current item better.
424
        $this->first();
425
        if ($this->debug > 2) {
426
            error_log('New LP - learnpath::__construct() ' . __LINE__ . ' - End of learnpath constructor for learnpath ' . $this->get_id(), 0);
427
        }
428
        return true;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
429
    }
430
431
    /**
432
     * @return string
433
     */
434
    public function getCourseCode()
435
    {
436
        return $this->cc;
437
    }
438
439
    /**
440
     * @return int
441
     */
442
    public function get_course_int_id()
443
    {
444
        return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
445
    }
446
447
    /**
448
     * @param $course_id
449
     * @return int
450
     */
451
    public function set_course_int_id($course_id)
452
    {
453
        return $this->course_int_id = intval($course_id);
454
    }
455
456
    /**
457
     * Get the depth level of LP item
458
     * @param $in_tab_items
459
     * @param $in_current_item_id
460
     * @return int
461
     */
462
    private static function get_level_for_item($in_tab_items, $in_current_item_id)
463
    {
464
        $parent_item_id = $in_tab_items[$in_current_item_id]->parent;
465
        if ($parent_item_id == 0) {
466
            return 0;
467
        } else {
468
            return learnpath::get_level_for_item($in_tab_items, $parent_item_id) + 1;
469
        }
470
    }
471
472
    /**
473
     * Function rewritten based on old_add_item() from Yannick Warnier.
474
     * Due the fact that users can decide where the item should come, I had to overlook this function and
475
     * I found it better to rewrite it. Old function is still available.
476
     * Added also the possibility to add a description.
477
     *
478
     * @param int $parent
479
     * @param int $previous
480
     * @param string $type
481
     * @param int  resource ID (ref)
482
     * @param string $title
483
     * @param string $description
484
     * @param int $prerequisites
485
     * @param int $max_time_allowed
486
     * @param int $userId
487
     *
488
     * @return int
489
     */
490
    public function add_item(
491
        $parent,
492
        $previous,
493
        $type = 'dokeos_chapter',
494
        $id,
495
        $title,
496
        $description,
497
        $prerequisites = 0,
498
        $max_time_allowed = 0,
499
        $userId = 0
500
    ) {
501
        $course_id = $this->course_info['real_id'];
502
        if ($this->debug > 0) {
503
            error_log('New LP - In learnpath::add_item(' . $parent . ',' . $previous . ',' . $type . ',' . $id . ',' . $title . ')', 0);
504
        }
505
        if (empty($course_id)) {
506
            // Sometimes Oogie doesn't catch the course info but sets $this->cc
507
            $this->course_info = api_get_course_info($this->cc);
508
            $course_id = $this->course_info['real_id'];
509
        }
510
        $userId = empty($userId) ? api_get_user_id() : $userId;
511
        $sessionId = api_get_session_id();
512
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
513
        $_course = $this->course_info;
514
        $parent = intval($parent);
515
        $previous = intval($previous);
516
        $id = intval($id);
517
        $max_time_allowed = htmlentities($max_time_allowed);
518
        if (empty($max_time_allowed)) {
519
            $max_time_allowed = 0;
520
        }
521
        $sql = "SELECT COUNT(id) AS num
522
                FROM $tbl_lp_item
523
                WHERE
524
                    c_id = $course_id AND
525
                    lp_id = " . $this->get_id() . " AND
526
                    parent_item_id = " . $parent;
527
528
        $res_count = Database::query($sql);
529
        $row = Database :: fetch_array($res_count);
530
        $num = $row['num'];
531
532
        if ($num > 0) {
533
            if ($previous == 0) {
534
                $sql = "SELECT id, next_item_id, display_order
535
                        FROM " . $tbl_lp_item . "
536
                        WHERE
537
                            c_id = $course_id AND
538
                            lp_id = " . $this->get_id() . " AND
539
                            parent_item_id = " . $parent . " AND
540
                            previous_item_id = 0 OR
541
                            previous_item_id=" . $parent;
542
                $result = Database::query($sql);
543
                $row = Database :: fetch_array($result);
544
545
                $tmp_previous = 0;
546
                $next = $row['id'];
547
                $display_order = 0;
548
            } else {
549
                $previous = (int) $previous;
550
                $sql = "SELECT id, previous_item_id, next_item_id, display_order
551
						FROM $tbl_lp_item
552
                        WHERE
553
                            c_id = $course_id AND
554
                            lp_id = " . $this->get_id() . " AND
555
                            id = " . $previous;
556
557
                $result = Database::query($sql);
558
                $row = Database:: fetch_array($result);
559
560
                $tmp_previous = $row['id'];
561
                $next = $row['next_item_id'];
562
                $display_order = $row['display_order'];
563
            }
564
        } else {
565
            $tmp_previous = 0;
566
            $next = 0;
567
            $display_order = 0;
568
        }
569
570
        $id = intval($id);
571
        $typeCleaned = Database::escape_string($type);
572
        if ($type == 'quiz') {
573
            $sql = 'SELECT SUM(ponderation)
574
                    FROM ' . Database :: get_course_table(TABLE_QUIZ_QUESTION) . ' as quiz_question
575
                    INNER JOIN  ' . Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION) . ' as quiz_rel_question
576
                    ON
577
                        quiz_question.id = quiz_rel_question.question_id AND
578
                        quiz_question.c_id = quiz_rel_question.c_id
579
                    WHERE
580
                        quiz_rel_question.exercice_id = '.$id." AND
581
                        quiz_question.c_id = $course_id AND
582
                        quiz_rel_question.c_id = $course_id ";
583
            $rsQuiz = Database::query($sql);
584
            $max_score = Database :: result($rsQuiz, 0, 0);
585
586
            // Disabling the exercise if we add it inside a LP
587
            $exercise = new Exercise($course_id);
588
            $exercise->read($id);
589
            $exercise->disable();
590
            $exercise->save();
591
        } else {
592
            $max_score = 100;
593
        }
594
595
        $params = array(
596
            "c_id" => $course_id,
597
            "lp_id" => $this->get_id(),
598
            "item_type" => $typeCleaned,
599
            "ref" => '',
600
            "title" => $title,
601
            "description" => $description,
602
            "path" => $id,
603
            "max_score" => $max_score,
604
            "parent_item_id" => $parent,
605
            "previous_item_id" => $previous,
606
            "next_item_id" => intval($next),
607
            "display_order" => $display_order + 1,
608
            "prerequisite" => $prerequisites,
609
            "max_time_allowed" => $max_time_allowed,
610
            'min_score' => 0,
611
            'launch_data' => '',
612
        );
613
614
        if ($prerequisites != 0) {
615
            $params['prerequisite'] = $prerequisites;
616
        }
617
618
        $new_item_id = Database::insert($tbl_lp_item, $params);
619
620
        if ($this->debug > 2) {
621
            error_log('New LP - Inserting chapter: ' . $new_item_id, 0);
622
        }
623
624
        if ($new_item_id) {
625
626
            $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
627
            Database::query($sql);
628
629
            // Update the item that should come after the new item.
630
            $sql = " UPDATE $tbl_lp_item SET
631
                        previous_item_id =  $new_item_id,
632
                        next_item_id = $new_item_id,
633
                        id = $new_item_id
634
                     WHERE iid = $new_item_id";
635
            Database::query($sql);
636
637
            // Update all the items after the new item.
638
            $sql = "UPDATE " . $tbl_lp_item . "
639
                        SET display_order = display_order + 1
640
                    WHERE
641
                        c_id = $course_id AND
642
                        lp_id = " . $this->get_id() . " AND
643
                        id <> " . $new_item_id . " AND
644
                        parent_item_id = " . $parent . " AND
645
                        display_order > " . $display_order;
646
            Database::query($sql);
647
648
            // Update the item that should come after the new item.
649
            $sql = "UPDATE " . $tbl_lp_item . "
650
                    SET ref = " . $new_item_id . "
651
                    WHERE c_id = $course_id AND id = " . $new_item_id;
652
            Database::query($sql);
653
654
            // Upload audio.
655
            if (!empty($_FILES['mp3']['name'])) {
656
                // Create the audio folder if it does not exist yet.
657
                $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
658
                if (!is_dir($filepath . 'audio')) {
659
                    mkdir($filepath . 'audio', api_get_permissions_for_new_directories());
660
                    $audio_id = add_document(
661
                        $_course,
662
                        '/audio',
663
                        'folder',
664
                        0,
665
                        'audio',
666
                        '',
667
                        0,
668
                        true,
669
                        null,
670
                        $sessionId,
671
                        $userId
672
                    );
673
                    api_item_property_update(
674
                        $_course,
675
                        TOOL_DOCUMENT,
676
                        $audio_id,
677
                        'FolderCreated',
678
                        $userId,
679
                        null,
680
                        null,
681
                        null,
682
                        null,
683
                        $sessionId
684
                    );
685
                    api_item_property_update(
686
                        $_course,
687
                        TOOL_DOCUMENT,
688
                        $audio_id,
689
                        'invisible',
690
                        $userId,
691
                        null,
692
                        null,
693
                        null,
694
                        null,
695
                        $sessionId
696
                    );
697
                }
698
699
                $file_path = handle_uploaded_document(
700
                    $_course,
701
                    $_FILES['mp3'],
702
                    api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document',
703
                    '/audio',
704
                    $userId,
705
                    '',
706
                    '',
707
                    '',
708
                    '',
709
                    false
710
                );
711
712
                // Getting the filename only.
713
                $file_components = explode('/', $file_path);
714
                $file = $file_components[count($file_components) - 1];
715
716
                // Store the mp3 file in the lp_item table.
717
                $sql = "UPDATE $tbl_lp_item SET
718
                            audio = '" . Database::escape_string($file) . "'
719
                        WHERE id = '" . intval($new_item_id) . "'";
720
                Database::query($sql);
721
            }
722
        }
723
724
        return $new_item_id;
725
    }
726
727
    /**
728
     * Static admin function allowing addition of a learnpath to a course.
729
     * @param	string	Course code
730
     * @param	string	Learnpath name
731
     * @param	string	Learnpath description string, if provided
732
     * @param	string	Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
733
     * @param	string	Type of files origin (default = 'zip', others = 'dir','web_dir',...)
734
     * @param	string	Zip file containing the learnpath or directory containing the learnpath
735
     * @return	integer	The new learnpath ID on success, 0 on failure
736
     */
737
    public static function add_lp(
738
        $courseCode,
739
        $name,
740
        $description = '',
741
        $learnpath = 'guess',
742
        $origin = 'zip',
743
        $zipname = '',
744
        $publicated_on = '',
745
        $expired_on = '',
746
        $categoryId = 0,
747
        $userId = 0
748
    ) {
749
        global $charset;
750
751
        if (!empty($courseCode)) {
752
            $courseInfo = api_get_course_info($courseCode);
753
            $course_id = $courseInfo['real_id'];
754
        } else {
755
            $course_id = api_get_course_int_id();
756
            $courseInfo = api_get_course_info();
757
        }
758
759
        $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
760
        // Check course code exists.
761
        // Check lp_name doesn't exist, otherwise append something.
762
        $i = 0;
763
        $name = Database::escape_string($name);
764
        $categoryId = intval($categoryId);
765
766
        // Session id.
767
        $session_id = api_get_session_id();
768
769
        $userId = empty($userId) ? api_get_user_id() : $userId;
770
771
        $check_name = "SELECT * FROM $tbl_lp
772
                       WHERE c_id = $course_id AND name = '$name'";
773
774
        $res_name = Database::query($check_name);
775
776
        if ($publicated_on == '0000-00-00 00:00:00' || empty($publicated_on)) {
777
            //by default the publication date is the same that the creation date
778
            //The behaviour above was changed due BT#2800
779
            global $_custom;
780
            if (isset($_custom['lps_hidden_when_no_start_date']) && $_custom['lps_hidden_when_no_start_date']) {
781
                $publicated_on = '';
782
            } else {
783
                $publicated_on = api_get_utc_datetime();
784
            }
785
        } else {
786
            $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
787
        }
788
789
        if ($expired_on == '0000-00-00 00:00:00' || empty($expired_on)) {
790
            $expired_on = '';
791
        } else {
792
            $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
793
        }
794
795
        while (Database :: num_rows($res_name)) {
0 ignored issues
show
Bug introduced by
It seems like $res_name can be null; however, num_rows() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
796
            // There is already one such name, update the current one a bit.
797
            $i++;
798
            $name = $name . ' - ' . $i;
799
            $check_name = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND name = '$name'";
800
            $res_name = Database::query($check_name);
801
        }
802
        // New name does not exist yet; keep it.
803
        // Escape description.
804
        // Kevin: added htmlentities().
805
        $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
806
        $type = 1;
807
        switch ($learnpath) {
808
            case 'guess':
809
                break;
810
            case 'dokeos':
811
            case 'chamilo':
812
                $type = 1;
813
                break;
814
            case 'aicc':
815
                break;
816
        }
817
818
        switch ($origin) {
819
            case 'zip':
820
                // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
821
                break;
822
            case 'manual':
823
            default:
824
                $get_max = "SELECT MAX(display_order) FROM $tbl_lp WHERE c_id = $course_id";
825
                $res_max = Database::query($get_max);
826
                if (Database :: num_rows($res_max) < 1) {
827
                    $dsp = 1;
828
                } else {
829
                    $row = Database :: fetch_array($res_max);
830
                    $dsp = $row[0] + 1;
831
                }
832
833
                $params = [
834
                    'c_id' => $course_id,
835
                    'lp_type' => $type,
836
                    'name' => $name,
837
                    'description' => $description,
838
                    'path' => '',
839
                    'default_view_mod' => 'embedded',
840
                    'default_encoding' => 'UTF-8',
841
                    'display_order' => $dsp,
842
                    'content_maker' => 'Chamilo',
843
                    'content_local' => 'local',
844
                    'js_lib' => '',
845
                    'session_id' => $session_id,
846
                    'created_on' => api_get_utc_datetime(),
847
                    'modified_on'  => api_get_utc_datetime(),
848
                    'publicated_on' => $publicated_on,
849
                    'expired_on' => $expired_on,
850
                    'category_id' => $categoryId,
851
                    'force_commit' => 0,
852
                    'content_license' => '',
853
                    'debug' => 0,
854
                    'theme' => '',
855
                    'preview_image' => '',
856
                    'author' => '',
857
                    'prerequisite' => 0,
858
                    'hide_toc_frame' => 0,
859
                    'seriousgame_mode' => 0,
860
                    'autolaunch' => 0,
861
                    'max_attempts' => 0,
862
                    'subscribe_users' => 0
863
                ];
864
865
                $id = Database::insert($tbl_lp, $params);
866
867 View Code Duplication
                if ($id > 0) {
868
                    $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
869
                    Database::query($sql);
870
871
                    // Insert into item_property.
872
                    api_item_property_update(
873
                        $courseInfo,
874
                        TOOL_LEARNPATH,
875
                        $id,
876
                        'LearnpathAdded',
877
                        $userId
878
                    );
879
                    api_set_default_visibility($id, TOOL_LEARNPATH, 0, $courseInfo, $session_id, $userId);
880
                    return $id;
881
                }
882
                break;
883
        }
884
    }
885
886
    /**
887
     * Auto completes the parents of an item in case it's been completed or passed
888
     * @param	integer	$item Optional ID of the item from which to look for parents
889
     */
890
    public function autocomplete_parents($item)
891
    {
892
        $debug = $this->debug;
893
894
        if ($debug) {
895
            error_log('Learnpath::autocomplete_parents()', 0);
896
        }
897
898
        if (empty($item)) {
899
            $item = $this->current;
900
        }
901
902
        $currentItem = $this->getItem($item);
903
        if ($currentItem) {
904
            $parent_id = $currentItem->get_parent();
905
            $parent = $this->getItem($parent_id);
906
            if ($parent) {
907
                // if $item points to an object and there is a parent.
908
                if ($debug) {
909
                    error_log(
910
                        'Autocompleting parent of item ' . $item . ' "'.$currentItem->get_title().'" (item ' . $parent_id . ' "'.$parent->get_title().'") ',
911
                        0
912
                    );
913
                }
914
915
                // New experiment including failed and browsed in completed status.
916
                //$current_status = $currentItem->get_status();
917
                //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
918
                // Fixes chapter auto complete
919
                if (true) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
920
                    // If the current item is completed or passes or succeeded.
921
                    $updateParentStatus = true;
922
                    if ($debug) {
923
                        error_log('Status of current item is alright', 0);
924
                    }
925
926
                    foreach ($parent->get_children() as $childItemId) {
927
                        $childItem = $this->getItem($childItemId);
928
929
                        // If children was not set try to get the info
930
                        if (empty($childItem->db_item_view_id)) {
931
                            $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
932
                        }
933
934
                        // Check all his brothers (parent's children) for completion status.
935
                        if ($childItemId != $item) {
936
                            if ($debug) {
937
                                error_log(
938
                                    'Looking at brother #'.$childItemId . ' "' . $childItem->get_title() . '", status is ' . $childItem->get_status(),
939
                                    0
940
                                );
941
                            }
942
                            // Trying completing parents of failed and browsed items as well.
943
                            if ($childItem->status_is(
944
                                array(
945
                                    'completed',
946
                                    'passed',
947
                                    'succeeded',
948
                                    'browsed',
949
                                    'failed'
950
                                )
951
                            )
952
                            ) {
953
                                // Keep completion status to true.
954
                                continue;
955
                            } else {
956
                                if ($debug > 2) {
957
                                    error_log(
958
                                        'Found one incomplete child of parent #' . $parent_id . ': child #'.$childItemId . ' "' . $childItem->get_title() . '", is ' . $childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
959
                                        0
960
                                    );
961
                                }
962
                                $updateParentStatus = false;
963
                                break;
964
                            }
965
                        }
966
                    }
967
968
                    if ($updateParentStatus) {
969
                        // If all the children were completed:
970
                        $parent->set_status('completed');
971
                        $parent->save(false, $this->prerequisites_match($parent->get_id()));
972
                        // Force the status to "completed"
973
                        //$this->update_queue[$parent->get_id()] = $parent->get_status();
974
                        $this->update_queue[$parent->get_id()] = 'completed';
975
                        if ($debug) {
976
                            error_log(
977
                                'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
978
                                print_r($this->update_queue, 1),
979
                                0
980
                            );
981
                        }
982
                        // Recursive call.
983
                        $this->autocomplete_parents($parent->get_id());
984
                    }
985
                }
986
            } else {
987
                if ($debug) {
988
                    error_log("Parent #$parent_id does not exists");
989
                }
990
            }
991
        } else {
992
            if ($debug) {
993
                error_log("#$item is an item that doesn't have parents");
994
            }
995
        }
996
    }
997
998
    /**
999
     * Auto saves the current results into the database for the whole learnpath
1000
     */
1001
    public function autosave()
1002
    {
1003
        if ($this->debug > 0) {
1004
            error_log('New LP - In learnpath::autosave()', 0);
1005
        }
1006
        // TODO: Add save operations for the learnpath itself.
1007
    }
1008
1009
    /**
1010
     * Closes the current resource
1011
     *
1012
     * Stops the timer
1013
     * Saves into the database if required
1014
     * Clears the current resource data from this object
1015
     * @return	boolean	True on success, false on failure
1016
     */
1017
    public function close()
1018
    {
1019
        if ($this->debug > 0) {
1020
            error_log('New LP - In learnpath::close()', 0);
1021
        }
1022
        if (empty ($this->lp_id)) {
1023
            $this->error = 'Trying to close this learnpath but no ID is set';
1024
            return false;
1025
        }
1026
        $this->current_time_stop = time();
1027
        $this->ordered_items = array();
1028
        $this->index = 0;
1029
        unset ($this->lp_id);
1030
        //unset other stuff
1031
        return true;
1032
    }
1033
1034
    /**
1035
     * Static admin function allowing removal of a learnpath
1036
     * @param	array $courseInfo
1037
     * @param	integer	Learnpath ID
1038
     * @param	string	Whether to delete data or keep it (default: 'keep', others: 'remove')
1039
     * @return	boolean	True on success, false on failure (might change that to return number of elements deleted)
1040
     */
1041
    public function delete($courseInfo = null, $id = null, $delete = 'keep')
1042
    {
1043
        $course_id = api_get_course_int_id();
1044
        if (!empty($courseInfo)) {
1045
            $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
1046
        }
1047
1048
        // TODO: Implement a way of getting this to work when the current object is not set.
1049
        // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
1050
        // If an ID is specifically given and the current LP is not the same, prevent delete.
1051
        if (!empty ($id) && ($id != $this->lp_id)) {
1052
            return false;
1053
        }
1054
1055
        $lp = Database:: get_course_table(TABLE_LP_MAIN);
1056
        $lp_item = Database:: get_course_table(TABLE_LP_ITEM);
1057
        $lp_view = Database:: get_course_table(TABLE_LP_VIEW);
1058
        $lp_item_view = Database:: get_course_table(TABLE_LP_ITEM_VIEW);
1059
1060
        // Delete lp item id.
1061
        foreach ($this->items as $id => $dummy) {
1062
            $sql = "DELETE FROM $lp_item_view
1063
                    WHERE c_id = $course_id AND lp_item_id = '" . $id . "'";
1064
            Database::query($sql);
1065
        }
1066
1067
        // Proposed by Christophe (nickname: clefevre)
1068
        $sql = "DELETE FROM $lp_item WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
1069
        Database::query($sql);
1070
1071
        $sql = "DELETE FROM $lp_view WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
1072
        Database::query($sql);
1073
1074
        self::toggle_publish($this->lp_id, 'i');
1075
1076
        if ($this->type == 2 || $this->type == 3) {
1077
            // This is a scorm learning path, delete the files as well.
1078
            $sql = "SELECT path FROM $lp
1079
                    WHERE c_id = ".$course_id." AND id = " . $this->lp_id;
1080
            $res = Database::query($sql);
1081
            if (Database :: num_rows($res) > 0) {
1082
                $row = Database :: fetch_array($res);
1083
                $path = $row['path'];
1084
                $sql = "SELECT id FROM $lp
1085
                        WHERE c_id = ".$course_id." AND path = '$path' AND id != " . $this->lp_id;
1086
                $res = Database::query($sql);
1087
                if (Database :: num_rows($res) > 0) { // Another learning path uses this directory, so don't delete it.
1088
                    if ($this->debug > 2) {
1089
                        error_log('New LP - In learnpath::delete(), found other LP using path ' . $path . ', keeping directory', 0);
1090
                    }
1091
                } else {
1092
                    // No other LP uses that directory, delete it.
1093
                    $course_rel_dir = api_get_course_path() . '/scorm/'; // scorm dir web path starting from /courses
1094
                    $course_scorm_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir; // The absolute system path for this course.
1095
                    if ($delete == 'remove' && is_dir($course_scorm_dir . $path) and !empty ($course_scorm_dir)) {
1096
                        if ($this->debug > 2) {
1097
                            error_log('New LP - In learnpath::delete(), found SCORM, deleting directory: ' . $course_scorm_dir . $path, 0);
1098
                        }
1099
                        // Proposed by Christophe (clefevre).
1100
                        if (strcmp(substr($path, -2), "/.") == 0) {
1101
                            $path = substr($path, 0, -1); // Remove "." at the end.
1102
                        }
1103
                        //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
1104
                        rmdirr($course_scorm_dir . $path);
1105
                    }
1106
                }
1107
            }
1108
        }
1109
1110
        $tbl_tool = Database :: get_course_table(TABLE_TOOL_LIST);
1111
        $link = 'newscorm/lp_controller.php?action=view&lp_id='.$this->lp_id;
1112
        // Delete tools
1113
        $sql = "DELETE FROM $tbl_tool
1114
                WHERE c_id = ".$course_id." AND (link LIKE '$link%' AND image='scormbuilder.gif')";
1115
        Database::query($sql);
1116
1117
        $sql = "DELETE FROM $lp WHERE c_id = ".$course_id." AND id = " . $this->lp_id;
1118
        Database::query($sql);
1119
        // Updates the display order of all lps.
1120
        $this->update_display_order();
1121
1122
        api_item_property_update(
1123
            api_get_course_info(),
1124
            TOOL_LEARNPATH,
1125
            $this->lp_id,
1126
            'delete',
1127
            api_get_user_id()
1128
        );
1129
1130
        $link_info = GradebookUtils::is_resource_in_course_gradebook(api_get_course_id(), 4 , $id, api_get_session_id());
1131
        if ($link_info !== false) {
1132
            GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
1133
        }
1134
1135
        if (api_get_setting('search_enabled') == 'true') {
1136
            require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
1137
            delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
1138
        }
1139
    }
1140
1141
    /**
1142
     * Removes all the children of one item - dangerous!
1143
     * @param	integer	$id Element ID of which children have to be removed
1144
     * @return	integer	Total number of children removed
1145
     */
1146
    public function delete_children_items($id)
1147
    {
1148
        $course_id = $this->course_info['real_id'];
1149
        if ($this->debug > 0) {
1150
            error_log('New LP - In learnpath::delete_children_items(' . $id . ')', 0);
1151
        }
1152
        $num = 0;
1153
        if (empty ($id) || $id != strval(intval($id))) {
1154
            return false;
1155
        }
1156
        $lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1157
        $sql = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND parent_item_id = $id";
1158
        $res = Database::query($sql);
1159
        while ($row = Database :: fetch_array($res)) {
1160
            $num += $this->delete_children_items($row['id']);
1161
            $sql_del = "DELETE FROM $lp_item WHERE c_id = ".$course_id." AND id = " . $row['id'];
1162
            Database::query($sql_del);
1163
            $num++;
1164
        }
1165
        return $num;
1166
    }
1167
1168
    /**
1169
     * Removes an item from the current learnpath
1170
     * @param	integer	$id Elem ID (0 if first)
1171
     * @param	integer	$remove Whether to remove the resource/data from the
1172
     * system or leave it (default: 'keep', others 'remove')
1173
     * @return	integer	Number of elements moved
1174
     * @todo implement resource removal
1175
     */
1176
    public function delete_item($id, $remove = 'keep')
1177
    {
1178
        $course_id = api_get_course_int_id();
1179
        if ($this->debug > 0) {
1180
            error_log('New LP - In learnpath::delete_item()', 0);
1181
        }
1182
        // TODO: Implement the resource removal.
1183
        if (empty ($id) || $id != strval(intval($id))) {
1184
            return false;
1185
        }
1186
        // First select item to get previous, next, and display order.
1187
        $lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1188
        $sql_sel = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND id = $id";
1189
        $res_sel = Database::query($sql_sel);
1190
        if (Database :: num_rows($res_sel) < 1) {
1191
            return false;
1192
        }
1193
        $row = Database :: fetch_array($res_sel);
1194
        $previous = $row['previous_item_id'];
1195
        $next = $row['next_item_id'];
1196
        $display = $row['display_order'];
1197
        $parent = $row['parent_item_id'];
1198
        $lp = $row['lp_id'];
1199
        // Delete children items.
1200
        $num = $this->delete_children_items($id);
1201
        if ($this->debug > 2) {
1202
            error_log('New LP - learnpath::delete_item() - deleted ' . $num . ' children of element ' . $id, 0);
1203
        }
1204
        // Now delete the item.
1205
        $sql_del = "DELETE FROM $lp_item WHERE c_id = $course_id AND id = $id";
1206
        if ($this->debug > 2) {
1207
            error_log('New LP - Deleting item: ' . $sql_del, 0);
1208
        }
1209
        Database::query($sql_del);
1210
        // Now update surrounding items.
1211
        $sql_upd = "UPDATE $lp_item SET next_item_id = $next
1212
                    WHERE c_id = ".$course_id." AND id = $previous";
1213
        Database::query($sql_upd);
1214
        $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
1215
                    WHERE c_id = ".$course_id." AND id = $next";
1216
        Database::query($sql_upd);
1217
        // Now update all following items with new display order.
1218
        $sql_all = "UPDATE $lp_item SET display_order = display_order-1
1219
                    WHERE c_id = ".$course_id." AND lp_id = $lp AND parent_item_id = $parent AND display_order > $display";
1220
        Database::query($sql_all);
1221
1222
        //Removing prerequisites since the item will not longer exist
1223
        $sql_all = "UPDATE $lp_item SET prerequisite = '' WHERE c_id = ".$course_id." AND prerequisite = $id";
1224
        Database::query($sql_all);
1225
1226
        // Remove from search engine if enabled.
1227
        if (api_get_setting('search_enabled') == 'true') {
1228
            $tbl_se_ref = Database :: get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
1229
            $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
1230
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
1231
            $res = Database::query($sql);
1232
            if (Database :: num_rows($res) > 0) {
1233
                $row2 = Database :: fetch_array($res);
1234
                require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
1235
                $di = new ChamiloIndexer();
1236
                $di->remove_document((int) $row2['search_did']);
1237
            }
1238
            $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
1239
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
1240
            Database::query($sql);
1241
        }
1242
    }
1243
1244
    /**
1245
     * Updates an item's content in place
1246
     * @param   integer $id Element ID
1247
     * @param   integer $parent Parent item ID
1248
     * @param   integer $previous Previous item ID
1249
     * @param   string  $title Item title
1250
     * @param   string  $description Item description
1251
     * @param   string  $prerequisites Prerequisites (optional)
1252
     * @param   array   $audio The array resulting of the $_FILES[mp3] element
1253
     * @param   int     $max_time_allowed
1254
     * @param   string  $url
1255
     * @return  boolean True on success, false on error
1256
     */
1257
    public function edit_item(
1258
        $id,
1259
        $parent,
1260
        $previous,
1261
        $title,
1262
        $description,
1263
        $prerequisites = '0',
1264
        $audio = array(),
1265
        $max_time_allowed = 0,
1266
        $url = ''
1267
    ) {
1268
        $course_id = api_get_course_int_id();
1269
        $_course = api_get_course_info();
1270
1271
        if ($this->debug > 0) {
1272
            error_log('New LP - In learnpath::edit_item()', 0);
1273
        }
1274
        if (empty ($max_time_allowed)) {
1275
            $max_time_allowed = 0;
1276
        }
1277
        if (empty ($id) || ($id != strval(intval($id))) || empty ($title)) {
1278
            return false;
1279
        }
1280
1281
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1282
        $sql_select = "SELECT * FROM " . $tbl_lp_item . " WHERE c_id = ".$course_id." AND id = " . $id;
1283
        $res_select = Database::query($sql_select);
1284
        $row_select = Database :: fetch_array($res_select);
1285
        $audio_update_sql = '';
1286
        if (is_array($audio) && !empty ($audio['tmp_name']) && $audio['error'] === 0) {
1287
            // Create the audio folder if it does not exist yet.
1288
            $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
1289 View Code Duplication
            if (!is_dir($filepath . 'audio')) {
1290
                mkdir($filepath . 'audio', api_get_permissions_for_new_directories());
1291
                $audio_id = add_document(
1292
                    $_course,
1293
                    '/audio',
1294
                    'folder',
1295
                    0,
1296
                    'audio'
1297
                );
1298
                api_item_property_update(
1299
                    $_course,
1300
                    TOOL_DOCUMENT,
1301
                    $audio_id,
1302
                    'FolderCreated',
1303
                    api_get_user_id(),
1304
                    null,
1305
                    null,
1306
                    null,
1307
                    null,
1308
                    api_get_session_id()
1309
                );
1310
                api_item_property_update(
1311
                    $_course,
1312
                    TOOL_DOCUMENT,
1313
                    $audio_id,
1314
                    'invisible',
1315
                    api_get_user_id(),
1316
                    null,
1317
                    null,
1318
                    null,
1319
                    null,
1320
                    api_get_session_id()
1321
                );
1322
            }
1323
1324
            // Upload file in documents.
1325
            $pi = pathinfo($audio['name']);
1326
            if ($pi['extension'] == 'mp3') {
1327
                $c_det = api_get_course_info($this->cc);
1328
                $bp = api_get_path(SYS_COURSE_PATH) . $c_det['path'] . '/document';
1329
                $path = handle_uploaded_document($c_det, $audio, $bp, '/audio', api_get_user_id(), 0, null, 0, 'rename', false, 0);
1330
                $path = substr($path, 7);
1331
                // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
1332
                $audio_update_sql = ", audio = '" . Database::escape_string($path) . "' ";
1333
            }
1334
        }
1335
1336
        $same_parent = ($row_select['parent_item_id'] == $parent) ? true : false;
1337
        $same_previous = ($row_select['previous_item_id'] == $previous) ? true : false;
1338
1339
        // TODO: htmlspecialchars to be checked for encoding related problems.
1340
        if ($same_parent && $same_previous) {
1341
            // Only update title and description.
1342
            $sql = "UPDATE " . $tbl_lp_item . "
1343
                    SET title = '" . Database::escape_string($title) . "',
1344
                        prerequisite = '" . $prerequisites . "',
1345
                        description = '" . Database::escape_string($description) . "'
1346
                        " . $audio_update_sql . ",
1347
                        max_time_allowed = '" . Database::escape_string($max_time_allowed) . "'
1348
                    WHERE c_id = ".$course_id." AND id = " . $id;
1349
            Database::query($sql);
1350
        } else {
1351
            $old_parent = $row_select['parent_item_id'];
1352
            $old_previous = $row_select['previous_item_id'];
1353
            $old_next = $row_select['next_item_id'];
1354
            $old_order = $row_select['display_order'];
1355
            $old_prerequisite = $row_select['prerequisite'];
1356
            $old_max_time_allowed = $row_select['max_time_allowed'];
1357
1358
            /* BEGIN -- virtually remove the current item id */
1359
            /* for the next and previous item it is like the current item doesn't exist anymore */
1360
1361
            if ($old_previous != 0) {
1362
                // Next
1363
                $sql = "UPDATE " . $tbl_lp_item . "
1364
                        SET next_item_id = " . $old_next . "
1365
                        WHERE c_id = ".$course_id." AND id = " . $old_previous;
1366
                Database::query($sql);
1367
            }
1368
1369
            if ($old_next != 0) {
1370
                // Previous
1371
                $sql = "UPDATE " . $tbl_lp_item . "
1372
                        SET previous_item_id = " . $old_previous . "
1373
                        WHERE c_id = ".$course_id." AND id = " . $old_next;
1374
                Database::query($sql);
1375
            }
1376
1377
            // display_order - 1 for every item with a display_order bigger then the display_order of the current item.
1378
            $sql = "UPDATE " . $tbl_lp_item . "
1379
                    SET display_order = display_order - 1
1380
                    WHERE
1381
                        c_id = ".$course_id." AND
1382
                        display_order > " . $old_order . " AND
1383
                        lp_id = " . $this->lp_id . " AND
1384
                        parent_item_id = " . $old_parent;
1385
            Database::query($sql);
1386
            /* END -- virtually remove the current item id */
1387
1388
            /* BEGIN -- update the current item id to his new location */
1389
1390
            if ($previous == 0) {
1391
                // Select the data of the item that should come after the current item.
1392
                $sql = "SELECT id, display_order
1393
                        FROM " . $tbl_lp_item . "
1394
                        WHERE
1395
                            c_id = ".$course_id." AND
1396
                            lp_id = " . $this->lp_id . " AND
1397
                            parent_item_id = " . $parent . " AND
1398
                            previous_item_id = " . $previous;
1399
                $res_select_old = Database::query($sql);
1400
                $row_select_old = Database::fetch_array($res_select_old);
1401
1402
                // If the new parent didn't have children before.
1403
                if (Database :: num_rows($res_select_old) == 0) {
1404
                    $new_next = 0;
1405
                    $new_order = 1;
1406
                } else {
1407
                    $new_next = $row_select_old['id'];
1408
                    $new_order = $row_select_old['display_order'];
1409
                }
1410
            } else {
1411
                // Select the data of the item that should come before the current item.
1412
                $sql = "SELECT next_item_id, display_order
1413
                        FROM " . $tbl_lp_item . "
1414
                        WHERE c_id = ".$course_id." AND id = " . $previous;
1415
                $res_select_old = Database::query($sql);
1416
                $row_select_old = Database :: fetch_array($res_select_old);
1417
                $new_next = $row_select_old['next_item_id'];
1418
                $new_order = $row_select_old['display_order'] + 1;
1419
            }
1420
1421
            // TODO: htmlspecialchars to be checked for encoding related problems.
1422
            // Update the current item with the new data.
1423
            $sql = "UPDATE " . $tbl_lp_item . "
1424
                    SET
1425
                        title = '" . Database::escape_string($title) . "',
1426
                        description = '" . Database::escape_string($description) . "',
1427
                        parent_item_id = " . $parent . ",
1428
                        previous_item_id = " . $previous . ",
1429
                        next_item_id = " . $new_next . ",
1430
                        display_order = " . $new_order . "
1431
                        " . $audio_update_sql . "
1432
                    WHERE c_id = ".$course_id." AND id = " . $id;
1433
            Database::query($sql);
1434
1435
            if ($previous != 0) {
1436
                // Update the previous item's next_item_id.
1437
                $sql = "UPDATE " . $tbl_lp_item . "
1438
                        SET next_item_id = " . $id . "
1439
                        WHERE c_id = ".$course_id." AND id = " . $previous;
1440
                Database::query($sql);
1441
            }
1442
1443
            if ($new_next != 0) {
1444
                // Update the next item's previous_item_id.
1445
                $sql = "UPDATE " . $tbl_lp_item . "
1446
                        SET previous_item_id = " . $id . "
1447
                        WHERE c_id = ".$course_id." AND id = " . $new_next;
1448
                Database::query($sql);
1449
            }
1450
1451
            if ($old_prerequisite != $prerequisites) {
1452
                $sql = "UPDATE " . $tbl_lp_item . "
1453
                        SET prerequisite = '" . $prerequisites . "'
1454
                        WHERE c_id = ".$course_id." AND id = " . $id;
1455
                Database::query($sql);
1456
            }
1457
1458
            if ($old_max_time_allowed != $max_time_allowed) {
1459
                // update max time allowed
1460
                $sql = "UPDATE " . $tbl_lp_item . "
1461
                        SET max_time_allowed = " . $max_time_allowed . "
1462
                        WHERE c_id = ".$course_id." AND id = " . $id;
1463
                Database::query($sql);
1464
            }
1465
1466
            // Update all the items with the same or a bigger display_order than the current item.
1467
            $sql = "UPDATE " . $tbl_lp_item . "
1468
                    SET display_order = display_order + 1
1469
                    WHERE
1470
                       c_id = ".$course_id." AND
1471
                       lp_id = " . $this->get_id() . " AND
1472
                       id <> " . $id . " AND
1473
                       parent_item_id = " . $parent . " AND
1474
                       display_order >= " . $new_order;
1475
1476
            Database::query($sql);
1477
        }
1478
1479
        if ($row_select['item_type'] == 'link') {
1480
            $link = new Link();
0 ignored issues
show
Bug introduced by
The call to Link::__construct() misses some required arguments starting with $id.
Loading history...
1481
            $linkId = $row_select['path'];
1482
            $link->updateLink($linkId, $url);
1483
        }
1484
    }
1485
1486
    /**
1487
     * Updates an item's prereq in place
1488
     * @param	integer	$id Element ID
1489
     * @param	string	$prerequisite_id Prerequisite Element ID
1490
     * @param	int 	$mastery_score Prerequisite min score
1491
     * @param	int 	$max_score Prerequisite max score
1492
     *
1493
     * @return	boolean	True on success, false on error
1494
     */
1495
    public function edit_item_prereq($id, $prerequisite_id, $mastery_score = 0, $max_score = 100)
1496
    {
1497
        $course_id = api_get_course_int_id();
1498
        if ($this->debug > 0) {
1499
            error_log('New LP - In learnpath::edit_item_prereq(' . $id . ',' . $prerequisite_id . ',' . $mastery_score . ',' . $max_score . ')', 0);
1500
        }
1501
1502
        if (empty($id) || ($id != strval(intval($id))) || empty ($prerequisite_id)) {
1503
            return false;
1504
        }
1505
1506
        $prerequisite_id = intval($prerequisite_id);
1507
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1508
1509
        if (!is_numeric($mastery_score) || $mastery_score < 0) {
1510
            $mastery_score = 0;
1511
        }
1512
1513
        if (!is_numeric($max_score) || $max_score < 0) {
1514
            $max_score = 100;
1515
        }
1516
1517
        /*if ($mastery_score > $max_score) {
1518
            $max_score = $mastery_score;
1519
        }*/
1520
1521
        if (!is_numeric($prerequisite_id)) {
1522
            $prerequisite_id = 'NULL';
1523
        }
1524
1525
        $mastery_score = floatval($mastery_score);
1526
        $max_score = floatval($max_score);
1527
1528
        $sql = " UPDATE $tbl_lp_item
1529
                 SET
1530
                    prerequisite = $prerequisite_id ,
1531
                    prerequisite_min_score = $mastery_score ,
1532
                    prerequisite_max_score = $max_score
1533
                 WHERE c_id = $course_id AND id = $id";
1534
        Database::query($sql);
1535
1536
        if ($prerequisite_id != 'NULL' && $prerequisite_id != '') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1537
            // Will this be enough to ensure unicity?
1538
            /*$sql = " UPDATE $tbl_lp_item
1539
                     SET mastery_score = $mastery_score
1540
                     WHERE c_id = $course_id AND ref = '$prerequisite_id'";
1541
1542
            Database::query($sql);*/
1543
        }
1544
        // TODO: Update the item object (can be ignored for now because refreshed).
1545
        return true;
1546
    }
1547
1548
    /**
1549
     * Escapes a string with the available database escape function
1550
     * @param	string	String to escape
1551
     * @return	string	String escaped
1552
     * @deprecated use  Database::escape_string
1553
     */
1554
    public function escape_string($string)
1555
    {
1556
        return Database::escape_string($string);
1557
    }
1558
1559
    /**
1560
     * Static admin function exporting a learnpath into a zip file
1561
     * @param	string	Export type (scorm, zip, cd)
1562
     * @param	string	Course code
1563
     * @param	integer Learnpath ID
1564
     * @param	string	Zip file name
1565
     * @return	string	Zip file path (or false on error)
1566
     */
1567
    public function export_lp($type, $course, $id, $zipname)
1568
    {
1569
        if (empty($type) || empty($course) || empty($id) || empty($zipname)) {
1570
            return false;
1571
        }
1572
        $url = '';
1573
        switch ($type) {
1574
            case 'scorm':
1575
                break;
1576
            case 'zip':
1577
                break;
1578
            case 'cdrom':
1579
                break;
1580
        }
1581
        return $url;
1582
    }
1583
1584
    /**
1585
     * Gets all the chapters belonging to the same parent as the item/chapter given
1586
     * Can also be called as abstract method
1587
     * @param	integer	Item ID
1588
     * @return	array	A list of all the "brother items" (or an empty array on failure)
1589
     */
1590 View Code Duplication
    public function get_brother_chapters($id)
1591
    {
1592
        $course_id = api_get_course_int_id();
1593
        if ($this->debug > 0) {
1594
            error_log('New LP - In learnpath::get_brother_chapters()', 0);
1595
        }
1596
1597
        if (empty($id)|| $id != strval(intval($id))) {
1598
            return array ();
1599
        }
1600
1601
        $lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1602
        $sql_parent = "SELECT * FROM $lp_item
1603
                       WHERE c_id = ".$course_id." AND id = $id AND item_type='dokeos_chapter'";
1604
        $res_parent = Database::query($sql_parent);
1605
        if (Database :: num_rows($res_parent) > 0) {
1606
            $row_parent = Database :: fetch_array($res_parent);
1607
            $parent = $row_parent['parent_item_id'];
1608
            $sql_bros = "SELECT * FROM $lp_item
1609
                        WHERE
1610
                            c_id = ".$course_id." AND
1611
                            parent_item_id = $parent AND
1612
                            id = $id AND
1613
                            item_type='dokeos_chapter'
1614
                        ORDER BY display_order";
1615
            $res_bros = Database::query($sql_bros);
1616
            $list = array ();
1617
            while ($row_bro = Database :: fetch_array($res_bros)) {
1618
                $list[] = $row_bro;
1619
            }
1620
            return $list;
1621
        }
1622
        return array ();
1623
    }
1624
1625
    /**
1626
     * Gets all the items belonging to the same parent as the item given
1627
     * Can also be called as abstract method
1628
     * @param	integer	Item ID
1629
     * @return	array	A list of all the "brother items" (or an empty array on failure)
1630
     */
1631 View Code Duplication
    public function get_brother_items($id)
1632
    {
1633
        $course_id = api_get_course_int_id();
1634
        if ($this->debug > 0) {
1635
            error_log('New LP - In learnpath::get_brother_items(' . $id . ')', 0);
1636
        }
1637
1638
        if (empty ($id) || $id != strval(intval($id))) {
1639
            return array ();
1640
        }
1641
1642
        $lp_item = Database :: get_course_table(TABLE_LP_ITEM);
1643
        $sql_parent = "SELECT * FROM $lp_item WHERE c_id = $course_id AND id = $id";
1644
        $res_parent = Database::query($sql_parent);
1645
        if (Database :: num_rows($res_parent) > 0) {
1646
            $row_parent = Database :: fetch_array($res_parent);
1647
            $parent = $row_parent['parent_item_id'];
1648
            $sql_bros = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND parent_item_id = $parent
1649
                         ORDER BY display_order";
1650
            $res_bros = Database::query($sql_bros);
1651
            $list = array ();
1652
            while ($row_bro = Database :: fetch_array($res_bros)) {
1653
                $list[] = $row_bro;
1654
            }
1655
            return $list;
1656
        }
1657
        return array ();
1658
    }
1659
1660
    /**
1661
     * Get the specific prefix index terms of this learning path
1662
     * @param string $prefix
1663
     * @return  array Array of terms
1664
     */
1665
    public function get_common_index_terms_by_prefix($prefix)
1666
    {
1667
        require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
1668
        $terms = get_specific_field_values_list_by_prefix(
1669
            $prefix,
1670
            $this->cc,
1671
            TOOL_LEARNPATH,
1672
            $this->lp_id
1673
        );
1674
        $prefix_terms = array();
1675
        if (!empty($terms)) {
1676
            foreach ($terms as $term) {
1677
                $prefix_terms[] = $term['value'];
1678
            }
1679
        }
1680
        return $prefix_terms;
1681
    }
1682
1683
    /**
1684
     * Gets the number of items currently completed
1685
     * @return integer The number of items currently completed
1686
     */
1687
    public function get_complete_items_count()
1688
    {
1689
        if ($this->debug > 0) {
1690
            error_log('New LP - In learnpath::get_complete_items_count()', 0);
1691
        }
1692
        $i = 0;
1693
        $completedStatusList = array(
1694
            'completed',
1695
            'passed',
1696
            'succeeded',
1697
            'browsed',
1698
            'failed'
1699
        );
1700
1701
        foreach ($this->items as $id => $dummy) {
1702
            // Trying failed and browsed considered "progressed" as well.
1703
            if ($this->items[$id]->status_is($completedStatusList) &&
1704
                $this->items[$id]->get_type() != 'dokeos_chapter' &&
1705
                $this->items[$id]->get_type() != 'dir'
1706
            ) {
1707
                $i++;
1708
            }
1709
        }
1710
        return $i;
1711
    }
1712
1713
    /**
1714
     * Gets the current item ID
1715
     * @return	integer	The current learnpath item id
1716
     */
1717
    public function get_current_item_id()
1718
    {
1719
        $current = 0;
1720
        if ($this->debug > 0) {
1721
            error_log('New LP - In learnpath::get_current_item_id()', 0);
1722
        }
1723
        if (!empty($this->current)) {
1724
            $current = $this->current;
1725
        }
1726
        if ($this->debug > 2) {
1727
            error_log('New LP - In learnpath::get_current_item_id() - Returning ' . $current, 0);
1728
        }
1729
        return $current;
1730
    }
1731
1732
    /**
1733
     * Force to get the first learnpath item id
1734
     * @return	integer	The current learnpath item id
1735
     */
1736
    public function get_first_item_id()
1737
    {
1738
        $current = 0;
1739
        if (is_array($this->ordered_items)) {
1740
            $current = $this->ordered_items[0];
1741
        }
1742
        return $current;
1743
    }
1744
1745
    /**
1746
     * Gets the total number of items available for viewing in this SCORM
1747
     * @return	integer	The total number of items
1748
     */
1749
    public function get_total_items_count()
1750
    {
1751
        if ($this->debug > 0) {
1752
            error_log('New LP - In learnpath::get_total_items_count()', 0);
1753
        }
1754
        return count($this->items);
1755
    }
1756
1757
    /**
1758
     * Gets the total number of items available for viewing in this SCORM but without chapters
1759
     * @return	integer	The total no-chapters number of items
1760
     */
1761
    public function get_total_items_count_without_chapters()
1762
    {
1763
        if ($this->debug > 0) {
1764
            error_log('New LP - In learnpath::get_total_items_count_without_chapters()', 0);
1765
        }
1766
        $total = 0;
1767
        $typeListNotToCount = self::getChapterTypes();
1768
        foreach ($this->items as $temp2) {
1769
            if (!in_array($temp2->get_type(), $typeListNotToCount)) {
1770
                $total++;
1771
            }
1772
        }
1773
        return $total;
1774
    }
1775
1776
    /**
1777
     * Gets the first element URL.
1778
     * @return	string	URL to load into the viewer
1779
     */
1780
    public function first()
1781
    {
1782
        if ($this->debug > 0) {
1783
            error_log('New LP - In learnpath::first()', 0);
1784
            error_log('$this->last_item_seen '.$this->last_item_seen);
1785
        }
1786
1787
        // Test if the last_item_seen exists and is not a dir.
1788
        if (count($this->ordered_items) == 0) {
1789
            $this->index = 0;
1790
        }
1791
1792
        if ($this->debug > 0) {
1793
            if (isset($this->items[$this->last_item_seen])) {
1794
                $status = $this->items[$this->last_item_seen]->get_status();
1795
            }
1796
            error_log('status '.$status);
1797
        }
1798
1799
        if (!empty($this->last_item_seen) &&
1800
            !empty($this->items[$this->last_item_seen]) &&
1801
            $this->items[$this->last_item_seen]->get_type() != 'dir' &&
1802
            $this->items[$this->last_item_seen]->get_type() != 'dokeos_chapter'
1803
            //with this change (below) the LP will NOT go to the next item, it will take lp item we left
1804
            //&& !$this->items[$this->last_item_seen]->is_done()
1805
        ) {
1806
1807
            if ($this->debug > 2) {
1808
                error_log('New LP - In learnpath::first() - Last item seen is ' . $this->last_item_seen.' of type '.$this->items[$this->last_item_seen]->get_type(), 0);
1809
            }
1810
            $index = -1;
1811
            foreach ($this->ordered_items as $myindex => $item_id) {
1812
                if ($item_id == $this->last_item_seen) {
1813
                    $index = $myindex;
1814
                    break;
1815
                }
1816
            }
1817
            if ($index == -1) {
1818
                // Index hasn't changed, so item not found - panic (this shouldn't happen).
1819
                if ($this->debug > 2) {
1820
                    error_log('New LP - Last item (' . $this->last_item_seen . ') was found in items but not in ordered_items, panic!', 0);
1821
                }
1822
                return false;
1823
            } else {
1824
                $this->last     = $this->last_item_seen;
1825
                $this->current  = $this->last_item_seen;
1826
                $this->index    = $index;
1827
            }
1828
        } else {
1829
            if ($this->debug > 2) {
1830
                error_log('New LP - In learnpath::first() - No last item seen', 0);
1831
            }
1832
            $index = 0;
1833
            // Loop through all ordered items and stop at the first item that is
1834
            // not a directory *and* that has not been completed yet.
1835
            while ( !empty($this->ordered_items[$index]) AND
1836
                is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') AND
1837
                (
1838
                    $this->items[$this->ordered_items[$index]]->get_type() == 'dir' OR
1839
                    $this->items[$this->ordered_items[$index]]->get_type() == 'dokeos_chapter' OR
1840
                    $this->items[$this->ordered_items[$index]]->is_done() === true
1841
                ) AND $index < $this->max_ordered_items) {
1842
                $index++;
1843
            }
1844
            $this->last     = $this->current;
1845
            // current is
1846
            $this->current  = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
1847
            $this->index    = $index;
1848
            if ($this->debug > 2) {
1849
                error_log('$index ' . $index);
1850
            }
1851 View Code Duplication
            if ($this->debug > 2) {
1852
                error_log('New LP - In learnpath::first() - No last item seen. New last = ' . $this->last . '(' . $this->ordered_items[$index] . ')', 0);
1853
            }
1854
        }
1855
        if ($this->debug > 2) {
1856
            error_log('New LP - In learnpath::first() - First item is ' . $this->get_current_item_id());
1857
        }
1858
    }
1859
1860
    /**
1861
     * Gets the information about an item in a format usable as JavaScript to update
1862
     * the JS API by just printing this content into the <head> section of the message frame
1863
     * @param	int $item_id
1864
     * @return	string
1865
     */
1866
    public function get_js_info($item_id = '')
1867
    {
1868
        if ($this->debug > 0) {
1869
            error_log('New LP - In learnpath::get_js_info(' . $item_id . ')', 0);
1870
        }
1871
1872
        $info = '';
1873
        $item_id = intval($item_id);
1874
1875
        if (!empty($item_id) && is_object($this->items[$item_id])) {
1876
            //if item is defined, return values from DB
1877
            $oItem = $this->items[$item_id];
1878
            $info .= '<script language="javascript">';
1879
            $info .= "top.set_score(" . $oItem->get_score() . ");\n";
1880
            $info .= "top.set_max(" . $oItem->get_max() . ");\n";
1881
            $info .= "top.set_min(" . $oItem->get_min() . ");\n";
1882
            $info .= "top.set_lesson_status('" . $oItem->get_status() . "');";
1883
            $info .= "top.set_session_time('" . $oItem->get_scorm_time('js') . "');";
1884
            $info .= "top.set_suspend_data('" . $oItem->get_suspend_data() . "');";
1885
            $info .= "top.set_saved_lesson_status('" . $oItem->get_status() . "');";
1886
            $info .= "top.set_flag_synchronized();";
1887
            $info .= '</script>';
1888
            if ($this->debug > 2) {
1889
                error_log('New LP - in learnpath::get_js_info(' . $item_id . ') - returning: ' . $info, 0);
1890
            }
1891
            return $info;
1892
1893
        } else {
1894
1895
            // If item_id is empty, just update to default SCORM data.
1896
            $info .= '<script language="javascript">';
1897
            $info .= "top.set_score(" . learnpathItem :: get_score() . ");\n";
1898
            $info .= "top.set_max(" . learnpathItem :: get_max() . ");\n";
1899
            $info .= "top.set_min(" . learnpathItem :: get_min() . ");\n";
1900
            $info .= "top.set_lesson_status('" . learnpathItem :: get_status() . "');";
1901
            $info .= "top.set_session_time('" . learnpathItem :: getScormTimeFromParameter('js') . "');";
1902
            $info .= "top.set_suspend_data('" . learnpathItem :: get_suspend_data() . "');";
1903
            $info .= "top.set_saved_lesson_status('" . learnpathItem :: get_status() . "');";
1904
            $info .= "top.set_flag_synchronized();";
1905
            $info .= '</script>';
1906
            if ($this->debug > 2) {
1907
                error_log('New LP - in learnpath::get_js_info(' . $item_id . ') - returning: ' . $info, 0);
1908
            }
1909
            return $info;
1910
        }
1911
    }
1912
1913
    /**
1914
     * Gets the js library from the database
1915
     * @return	string	The name of the javascript library to be used
1916
     */
1917
    public function get_js_lib()
1918
    {
1919
        $lib = '';
1920
        if (!empty ($this->js_lib)) {
1921
            $lib = $this->js_lib;
1922
        }
1923
        return $lib;
1924
    }
1925
1926
    /**
1927
     * Gets the learnpath database ID
1928
     * @return	integer	Learnpath ID in the lp table
1929
     */
1930
    public function get_id()
1931
    {
1932
        if (!empty ($this->lp_id)) {
1933
            return $this->lp_id;
1934
        } else {
1935
            return 0;
1936
        }
1937
    }
1938
1939
    /**
1940
     * Gets the last element URL.
1941
     * @return string URL to load into the viewer
1942
     */
1943
    public function get_last()
1944
    {
1945
        if ($this->debug > 0) {
1946
            error_log('New LP - In learnpath::get_last()', 0);
1947
        }
1948
        //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
1949
        if (count($this->ordered_items) > 0) {
1950
            $this->index = count($this->ordered_items) - 1;
1951
            return $this->ordered_items[$this->index];
1952
        }
1953
1954
        return false;
1955
    }
1956
1957
    /**
1958
     * Gets the navigation bar for the learnpath display screen
1959
     * @return	string	The HTML string to use as a navigation bar
1960
     */
1961
    public function get_navigation_bar($idBar = null, $display=null) {
1962
        if ($this->debug > 0) {
1963
            error_log('New LP - In learnpath::get_navigation_bar()', 0);
1964
        }
1965
        if(empty($idBar)){
1966
            $idBar='control-top';
1967
        }
1968
        /* if(empty($display)){
1969
            $display='display:block';
1970
        } */
1971
        $navbar = null;
1972
        $lp_id = $this->lp_id;
1973
        $mycurrentitemid = $this->get_current_item_id();
1974
1975
        if ($this->mode == 'fullscreen') {
1976
            $navbar = '
1977
                  <span id="'.$idBar.'" class="buttons">
1978
                    <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="stats" id="stats_link">
1979
                        <span class="fa fa-info"></span><span class="sr-only">' . get_lang('Reporting') . '</span>
1980
                    </a>
1981
                    <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid . ',\'previous\');return false;" title="previous">
1982
                        <span class="fa fa-chevron-left"></span><span class="sr-only">' . get_lang('ScormPrevious') . '</span>
1983
                    </a>
1984
                    <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid . ',\'next\');return false;" title="next">
1985
                        <span class="fa fa-chevron-right"></span><span class="sr-only">' . get_lang('ScormNext') . '</span>
1986
                    </a>
1987
                    <a class="icon-toolbar" id="view-embedded" href="lp_controller.php?action=mode&mode=embedded" target="_top" title="embedded mode">
1988
                        <span class="fa fa-columns"></span><span class="sr-only">' . get_lang('ScormExitFullScreen') . '</span>
1989
                    </a>
1990
                  </span>';
1991
1992
        } else {
1993
            $navbar = '
1994
                <span id="'.$idBar.'" class="buttons text-right">
1995
                    <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="stats" id="stats_link">
1996
                        <span class="fa fa-info"></span><span class="sr-only">' . get_lang('Reporting') . '</span>
1997
                    </a>
1998
                    <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid . ',\'previous\');return false;" title="previous">
1999
                        <span class="fa fa-chevron-left"></span><span class="sr-only">' . get_lang('ScormPrevious') . '</span>
2000
                    </a>
2001
                    <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid . ',\'next\');return false;" title="next">
2002
                        <span class="fa fa-chevron-right"></span><span class="sr-only">' . get_lang('ScormNext') . '</span>
2003
                    </a>
2004
                </span>';
2005
        }
2006
2007
        return $navbar;
2008
    }
2009
2010
    /**
2011
     * Gets the next resource in queue (url).
2012
     * @return	string	URL to load into the viewer
2013
     */
2014
    public function get_next_index()
2015
    {
2016
        if ($this->debug > 0) {
2017
            error_log('New LP - In learnpath::get_next_index()', 0);
2018
        }
2019
        // TODO
2020
        $index = $this->index;
2021
        $index++;
2022 View Code Duplication
        if ($this->debug > 2) {
2023
            error_log('New LP - Now looking at ordered_items[' . ($index) . '] - type is ' . $this->items[$this->ordered_items[$index]]->type, 0);
2024
        }
2025
        while (!empty ($this->ordered_items[$index]) AND ($this->items[$this->ordered_items[$index]]->get_type() == 'dir' || $this->items[$this->ordered_items[$index]]->get_type() == 'dokeos_chapter') AND $index < $this->max_ordered_items) {
2026
            $index++;
2027
            if ($index == $this->max_ordered_items){
2028
                if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir' || $this->items[$this->ordered_items[$index]]->get_type() == 'dokeos_chapter') {
2029
                    return $this->index;
2030
                } else {
2031
                    return $index;
2032
                }
2033
            }
2034
        }
2035
        if (empty ($this->ordered_items[$index])) {
2036
            return $this->index;
2037
        }
2038
        if ($this->debug > 2) {
2039
            error_log('New LP - index is now ' . $index, 0);
2040
        }
2041
        return $index;
2042
    }
2043
2044
    /**
2045
     * Gets item_id for the next element
2046
     * @return	integer	Next item (DB) ID
2047
     */
2048
    public function get_next_item_id()
2049
    {
2050
        if ($this->debug > 0) {
2051
            error_log('New LP - In learnpath::get_next_item_id()', 0);
2052
        }
2053
        $new_index = $this->get_next_index();
2054
        if (!empty ($new_index)) {
2055
            if (isset ($this->ordered_items[$new_index])) {
2056
                if ($this->debug > 2) {
2057
                    error_log('New LP - In learnpath::get_next_index() - Returning ' . $this->ordered_items[$new_index], 0);
2058
                }
2059
                return $this->ordered_items[$new_index];
2060
            }
2061
        }
2062
        if ($this->debug > 2) {
2063
            error_log('New LP - In learnpath::get_next_index() - Problem - Returning 0', 0);
2064
        }
2065
        return 0;
2066
    }
2067
2068
    /**
2069
     * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...)
2070
     *
2071
     * Generally, the package provided is in the form of a zip file, so the function
2072
     * has been written to test a zip file. If not a zip, the function will return the
2073
     * default return value: ''
2074
     * @param	string	the path to the file
2075
     * @param	string 	the original name of the file
2076
     * @return	string	'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
2077
     */
2078
    public static function get_package_type($file_path, $file_name)
2079
    {
2080
        // Get name of the zip file without the extension.
2081
        $file_info = pathinfo($file_name);
2082
        $filename = $file_info['basename']; // Name including extension.
2083
        $extension = $file_info['extension']; // Extension only.
2084
2085
        if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), array(
2086
                'dll',
2087
                'exe'
2088
            ))) {
2089
            return 'oogie';
2090
        }
2091
        if (!empty($_POST['woogie']) && !in_array(strtolower($extension), array(
2092
                'dll',
2093
                'exe'
2094
            ))) {
2095
            return 'woogie';
2096
        }
2097
2098
        // Filename without its extension.
2099
        $file_base_name = str_replace('.' . $extension, '', $filename);
2100
2101
        $zipFile = new PclZip($file_path);
2102
        // Check the zip content (real size and file extension).
2103
        $zipContentArray = $zipFile->listContent();
2104
        $package_type = '';
2105
        $at_root = false;
2106
        $manifest = '';
2107
        $aicc_match_crs = 0;
2108
        $aicc_match_au = 0;
2109
        $aicc_match_des = 0;
2110
        $aicc_match_cst = 0;
2111
2112
        // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
2113
        if (is_array($zipContentArray) && count($zipContentArray) > 0) {
2114
            foreach ($zipContentArray as $thisContent) {
2115
                if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
2116
                    // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
2117
                } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
2118
                    $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
2119
                    $package_type = 'scorm';
2120
                    break; // Exit the foreach loop.
2121
                } elseif (
2122
                    preg_match('/aicc\//i', $thisContent['filename']) ||
2123
                    in_array(strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)), array( 'crs','au','des','cst'))
2124
                ) {
2125
                    $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
2126
                    switch ($ext) {
2127
                        case 'crs':
2128
                            $aicc_match_crs = 1;
2129
                            break;
2130
                        case 'au':
2131
                            $aicc_match_au = 1;
2132
                            break;
2133
                        case 'des':
2134
                            $aicc_match_des = 1;
2135
                            break;
2136
                        case 'cst':
2137
                            $aicc_match_cst = 1;
2138
                            break;
2139
                        default:
2140
                            break;
2141
                    }
2142
                    //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
2143
                } else {
2144
                    $package_type = '';
2145
                }
2146
            }
2147
        }
2148
        if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
2149
            // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
2150
            $package_type = 'aicc';
2151
        }
2152
        return $package_type;
2153
    }
2154
2155
    /**
2156
     * Gets the previous resource in queue (url). Also initialises time values for this viewing
2157
     * @return string URL to load into the viewer
2158
     */
2159
    public function get_previous_index()
2160
    {
2161
        if ($this->debug > 0) {
2162
            error_log('New LP - In learnpath::get_previous_index()', 0);
2163
        }
2164
        $index = $this->index;
2165
        if (isset ($this->ordered_items[$index -1])) {
2166
            $index--;
2167
            while (isset($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir' || $this->items[$this->ordered_items[$index]]->get_type() == 'dokeos_chapter')) {
2168
                $index--;
2169
                if ($index < 0) {
2170
                    return $this->index;
2171
                }
2172
            }
2173
        } else {
2174
            if ($this->debug > 2) {
2175
                error_log('New LP - get_previous_index() - there was no previous index available, reusing ' . $index, 0);
2176
            }
2177
            // There is no previous item.
2178
        }
2179
        return $index;
2180
    }
2181
2182
    /**
2183
     * Gets item_id for the next element
2184
     * @return	integer	Previous item (DB) ID
2185
     */
2186
    public function get_previous_item_id()
2187
    {
2188
        if ($this->debug > 0) {
2189
            error_log('New LP - In learnpath::get_previous_item_id()', 0);
2190
        }
2191
        $new_index = $this->get_previous_index();
2192
        return $this->ordered_items[$new_index];
2193
    }
2194
2195
    /**
2196
     * Gets the progress value from the progress_db attribute
2197
     * @return	integer	Current progress value
2198
     */
2199
    public function get_progress()
2200
    {
2201
        if ($this->debug > 0) {
2202
            error_log('New LP - In learnpath::get_progress()', 0);
2203
        }
2204
        if (!empty ($this->progress_db)) {
2205
            return $this->progress_db;
2206
        }
2207
        return 0;
2208
    }
2209
2210
    /**
2211
     * Returns the HTML necessary to print a mediaplayer block inside a page
2212
     * @return string	The mediaplayer HTML
2213
     */
2214
    public function get_mediaplayer($autostart = 'true')
2215
    {
2216
        $course_id = api_get_course_int_id();
2217
        $_course = api_get_course_info();
2218
        $tbl_lp_item 		= Database :: get_course_table(TABLE_LP_ITEM);
2219
        $tbl_lp_item_view 	= Database :: get_course_table(TABLE_LP_ITEM_VIEW);
2220
2221
        // Getting all the information about the item.
2222
        $sql = "SELECT * FROM ".$tbl_lp_item." as lp
2223
                INNER JOIN ".$tbl_lp_item_view." as lp_view
2224
                ON lp.id = lp_view.lp_item_id
2225
                WHERE
2226
                    lp.id = '".$_SESSION['oLP']->current."' AND
2227
                    lp.c_id = $course_id AND
2228
                    lp_view.c_id = $course_id";
2229
        $result = Database::query($sql);
2230
        $row 	= Database::fetch_assoc($result);
2231
        $output = '';
2232
2233
        if (!empty ($row['audio'])) {
2234
2235
            $list = $_SESSION['oLP']->get_toc();
2236
            $type_quiz = false;
2237
2238
            foreach($list as $toc) {
2239
                if ($toc['id'] == $_SESSION['oLP']->current && ($toc['type']=='quiz') ) {
2240
                    $type_quiz = true;
2241
                }
2242
            }
2243
2244
            if ($type_quiz) {
2245
                if ($_SESSION['oLP']->prevent_reinit == 1) {
2246
                    $row['status'] === 'completed' ? $autostart_audio = 'false' : $autostart_audio = 'true';
2247
                } else {
2248
                    $autostart_audio = $autostart;
2249
                }
2250
            } else {
2251
                $autostart_audio = 'true';
2252
            }
2253
2254
            $courseInfo = api_get_course_info();
2255
2256
            $audio = $row['audio'];
2257
2258
            $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
2259
            $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
2260
2261
            if (!file_exists($file)) {
2262
                $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
2263
                $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
2264
                $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
2265
            }
2266
2267
            $player = Display::getMediaPlayer(
2268
                $file,
2269
                array(
2270
                    'id' => 'lp_audio_media_player',
2271
                    'url' => $url,
2272
                    'autoplay' => $autostart_audio,
2273
                    'width' => '100%'
2274
                )
2275
            );
2276
2277
            // The mp3 player.
2278
            $output  = '<div id="container">';
2279
            $output .= $player;
2280
            $output .= '</div>';
2281
        }
2282
2283
        return $output;
2284
    }
2285
2286
    /**
2287
     * Checks if the learning path is visible for student after the progress
2288
     * of its prerequisite is completed, considering the time availability and
2289
     * the LP visibility.
2290
     * @param int $lp_id
2291
     * @param int $student_id
2292
     * @param string Course code (optional)
2293
     * @param int $sessionId
2294
     * @return	bool
2295
     */
2296
    public static function is_lp_visible_for_student(
2297
        $lp_id,
2298
        $student_id,
2299
        $courseCode = null,
2300
        $sessionId = null
2301
    ) {
2302
        $lp_id = (int)$lp_id;
2303
        $courseInfo = api_get_course_info($courseCode);
2304
        $sessionId = intval($sessionId);
2305
2306
        if (empty($sessionId)) {
2307
            $sessionId = api_get_session_id();
2308
        }
2309
2310
        $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
2311
        // Get current prerequisite
2312
        $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
2313
                FROM $tbl_learnpath
2314
                WHERE c_id = ".$courseInfo['real_id']." AND id = $lp_id";
2315
2316
        $itemInfo = api_get_item_property_info(
2317
            $courseInfo['real_id'],
2318
            TOOL_LEARNPATH,
2319
            $lp_id,
2320
            $sessionId
2321
        );
2322
2323
        // If the item was deleted.
2324
        if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
2325
            return false;
2326
        }
2327
2328
        $rs  = Database::query($sql);
2329
        $now = time();
2330
        if (Database::num_rows($rs) > 0) {
2331
            $row = Database::fetch_array($rs, 'ASSOC');
2332
2333
            $prerequisite = $row['prerequisite'];
2334
            $is_visible = true;
2335
2336
            if (!empty($prerequisite)) {
2337
                $progress = self::getProgress(
2338
                    $prerequisite,
2339
                    $student_id,
2340
                    $courseInfo['real_id'],
2341
                    $sessionId
2342
                );
2343
                $progress = intval($progress);
2344
                if ($progress < 100) {
2345
                    $is_visible = false;
2346
                }
2347
            }
2348
2349
            // Also check the time availability of the LP
2350
            if ($is_visible) {
2351
                // Adding visibility restrictions
2352 View Code Duplication
                if (!empty($row['publicated_on']) &&
2353
                    $row['publicated_on'] != '0000-00-00 00:00:00'
2354
                ) {
2355
                    if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
2356
                        //api_not_allowed();
2357
                        $is_visible = false;
2358
                    }
2359
                }
2360
2361
                // Blocking empty start times see BT#2800
2362
                global $_custom;
2363
                if (isset($_custom['lps_hidden_when_no_start_date']) &&
2364
                    $_custom['lps_hidden_when_no_start_date']
2365
                ) {
2366
                    if (empty($row['publicated_on']) || $row['publicated_on'] == '0000-00-00 00:00:00') {
2367
                        //api_not_allowed();
2368
                        $is_visible = false;
2369
                    }
2370
                }
2371
2372 View Code Duplication
                if (!empty($row['expired_on']) && $row['expired_on'] != '0000-00-00 00:00:00') {
2373
                    if ($now > api_strtotime($row['expired_on'], 'UTC')) {
2374
                        //api_not_allowed();
2375
                        $is_visible = false;
2376
                    }
2377
                }
2378
            }
2379
2380
            // Check if the subscription users/group to a LP is ON
2381
            if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1) {
2382
                // Try group
2383
                $is_visible = false;
2384
2385
                // Checking only the user visibility
2386
                $userVisibility = api_get_item_visibility(
2387
                    $courseInfo,
2388
                    'learnpath',
2389
                    $row['id'],
2390
                    $sessionId,
2391
                    $student_id,
2392
                    'LearnpathSubscription'
2393
                );
2394
2395
                if ($userVisibility == 1) {
2396
                    $is_visible = true;
2397
                } else {
2398
                    $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
2399
                    if (!empty($userGroups)) {
2400
                        foreach ($userGroups as $groupInfo) {
2401
                            $groupId = $groupInfo['iid'];
2402
2403
                            $userVisibility = api_get_item_visibility(
2404
                                $courseInfo,
2405
                                'learnpath',
2406
                                $row['id'],
2407
                                $sessionId,
2408
                                null,
2409
                                'LearnpathSubscription',
2410
                                $groupId
2411
                            );
2412
2413
                            if ($userVisibility == 1) {
2414
                                $is_visible = true;
2415
                                break;
2416
                            }
2417
                        }
2418
                    }
2419
                }
2420
            }
2421
2422
            return $is_visible;
2423
        }
2424
2425
        return false;
2426
    }
2427
2428
    /**
2429
     * @param int $lpId
2430
     * @param int $userId
2431
     * @param int $courseId
2432
     * @param int $sessionId
2433
     * @return int
2434
     */
2435
    public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
2436
    {
2437
        $lpId = intval($lpId);
2438
        $userId = intval($userId);
2439
        $courseId = intval($courseId);
2440
        $sessionId = intval($sessionId);
2441
        $progress = 0;
2442
2443
        $sessionCondition = api_get_session_condition($sessionId);
2444
        $table = Database :: get_course_table(TABLE_LP_VIEW);
2445
        $sql = "SELECT * FROM $table
2446
                WHERE
2447
                    c_id = ".$courseId." AND
2448
                    lp_id = $lpId AND
2449
                    user_id = $userId $sessionCondition";
2450
        $res = Database::query($sql);
2451
        if (Database :: num_rows($res) > 0) {
2452
            $row = Database:: fetch_array($res);
2453
            $progress = $row['progress'];
2454
        }
2455
        return $progress;
2456
2457
    }
2458
2459
    /**
2460
     * Displays a progress bar
2461
     * completed so far.
2462
     * @param	integer	$percentage Progress value to display
2463
     * @param	string	$text_add Text to display near the progress value
2464
     * @return	string	HTML string containing the progress bar
2465
     */
2466
    public static function get_progress_bar($percentage = -1, $text_add = '')
2467
    {
2468
        $text = $percentage . $text_add;
2469
        $output = '<div class="progress">
2470
                        <div id="progress_bar_value" class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="' .$percentage. '" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
2471
                        '. $text .'
2472
                        </div>
2473
                    </div>';
2474
2475
        return $output;
2476
    }
2477
2478
    /**
2479
     * @param string $mode can be '%' or 'abs'
2480
     * otherwise this value will be used $this->progress_bar_mode
2481
     * @return string
2482
     */
2483
    public function getProgressBar($mode = null)
2484
    {
2485
        list($percentage, $text_add) = $this->get_progress_bar_text($mode);
2486
        return self::get_progress_bar($percentage, $text_add);
2487
    }
2488
2489
    /**
2490
     * Gets the progress bar info to display inside the progress bar.
2491
     * Also used by scorm_api.php
2492
     * @param	string	$mode Mode of display (can be '%' or 'abs').abs means
2493
     * we display a number of completed elements per total elements
2494
     * @param	integer	$add Additional steps to fake as completed
2495
     * @return	list array Percentage or number and symbol (% or /xx)
2496
     */
2497
    public function get_progress_bar_text($mode = '', $add = 0)
2498
    {
2499
        if ($this->debug > 0) {
2500
            error_log('New LP - In learnpath::get_progress_bar_text()', 0);
2501
        }
2502
        if (empty($mode)) {
2503
            $mode = $this->progress_bar_mode;
2504
        }
2505
        $total_items = $this->get_total_items_count_without_chapters();
2506
        if ($this->debug > 2) {
2507
            error_log('New LP - Total items available in this learnpath: ' . $total_items, 0);
2508
        }
2509
        $completeItems = $this->get_complete_items_count();
2510
        if ($this->debug > 2) {
2511
            error_log('New LP - Items completed so far: ' . $completeItems, 0);
2512
        }
2513
        if ($add != 0) {
2514
            $completeItems += $add;
2515
            if ($this->debug > 2) {
2516
                error_log('New LP - Items completed so far (+modifier): ' . $completeItems, 0);
2517
            }
2518
        }
2519
        $text = '';
2520
        if ($completeItems > $total_items) {
2521
            $completeItems = $total_items;
2522
        }
2523
        $percentage = 0;
2524
        if ($mode == '%') {
2525
            if ($total_items > 0) {
2526
                $percentage = ((float) $completeItems / (float) $total_items) * 100;
2527
            } else {
2528
                $percentage = 0;
2529
            }
2530
            $percentage = number_format($percentage, 0);
2531
            $text = '%';
2532
        } elseif ($mode == 'abs') {
2533
            $percentage = $completeItems;
2534
            $text = '/' . $total_items;
2535
        }
2536
2537
        return array(
2538
            $percentage,
2539
            $text
2540
        );
2541
    }
2542
2543
    /**
2544
     * Gets the progress bar mode
2545
     * @return	string	The progress bar mode attribute
2546
     */
2547
    public function get_progress_bar_mode()
2548
    {
2549
        if ($this->debug > 0) {
2550
            error_log('New LP - In learnpath::get_progress_bar_mode()', 0);
2551
        }
2552
        if (!empty ($this->progress_bar_mode)) {
2553
            return $this->progress_bar_mode;
2554
        } else {
2555
            return '%';
2556
        }
2557
    }
2558
2559
    /**
2560
     * Gets the learnpath proximity (remote or local)
2561
     * @return	string	Learnpath proximity
2562
     */
2563
    public function get_proximity()
2564
    {
2565
        if ($this->debug > 0) {
2566
            error_log('New LP - In learnpath::get_proximity()', 0);
2567
        }
2568
        if (!empty ($this->proximity)) {
2569
            return $this->proximity;
2570
        } else {
2571
            return '';
2572
        }
2573
    }
2574
2575
    /**
2576
     * Gets the learnpath theme (remote or local)
2577
     * @return	string	Learnpath theme
2578
     */
2579
    public function get_theme()
2580
    {
2581
        if ($this->debug > 0) {
2582
            error_log('New LP - In learnpath::get_theme()', 0);
2583
        }
2584
        if (!empty ($this->theme)) {
2585
            return $this->theme;
2586
        } else {
2587
            return '';
2588
        }
2589
    }
2590
2591
    /**
2592
     * Gets the learnpath session id
2593
     * @return	string	Learnpath theme
2594
     */
2595
    public function get_lp_session_id()
2596
    {
2597
        if ($this->debug > 0) {
2598
            error_log('New LP - In learnpath::get_lp_session_id()', 0);
2599
        }
2600
        if (!empty ($this->lp_session_id)) {
2601
            return $this->lp_session_id;
2602
        } else {
2603
            return 0;
2604
        }
2605
    }
2606
2607
    /**
2608
     * Gets the learnpath image
2609
     * @return	string	Web URL of the LP image
2610
     */
2611
    public function get_preview_image()
2612
    {
2613
        if ($this->debug > 0) {
2614
            error_log('New LP - In learnpath::get_preview_image()', 0);
2615
        }
2616
        if (!empty($this->preview_image)) {
2617
            return $this->preview_image;
2618
        } else {
2619
            return '';
2620
        }
2621
    }
2622
2623
    /**
2624
     * @param string $size
2625
     * @param string $path_type
2626
     * @return bool|string
2627
     */
2628
    public function get_preview_image_path($size = null, $path_type = 'web')
2629
    {
2630
        $preview_image = $this->get_preview_image();
2631
        if (isset($preview_image) && !empty($preview_image)) {
2632
            $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
2633
            $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
2634
2635
            if (isset($size)) {
2636
                $info = pathinfo($preview_image);
2637
                $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
2638
                if (file_exists($image_sys_path.$image_custom_size)) {
2639
                    if ($path_type == 'web') {
2640
                        return $image_path.$image_custom_size;
2641
                    } else {
2642
                        return $image_sys_path.$image_custom_size;
2643
                    }
2644
                }
2645
            } else {
2646
                if ($path_type == 'web') {
2647
                    return $image_path.$preview_image;
2648
                } else {
2649
                    return $image_sys_path.$preview_image;
2650
                }
2651
            }
2652
        }
2653
2654
        return false;
2655
    }
2656
2657
    /**
2658
     * Gets the learnpath author
2659
     * @return string	LP's author
2660
     */
2661
    public function get_author()
2662
    {
2663
        if ($this->debug > 0) {
2664
            error_log('New LP - In learnpath::get_author()', 0);
2665
        }
2666
        if (!empty ($this->author)) {
2667
            return $this->author;
2668
        } else {
2669
            return '';
2670
        }
2671
    }
2672
2673
    /**
2674
     * Gets the learnpath author
2675
     * @return	string	LP's author
2676
     */
2677
    public function get_hide_toc_frame()
2678
    {
2679
        if ($this->debug > 0) {
2680
            error_log('New LP - In learnpath::get_author()', 0);
2681
        }
2682
        if (!empty ($this->hide_toc_frame)) {
2683
            return $this->hide_toc_frame;
2684
        } else {
2685
            return '';
2686
        }
2687
    }
2688
2689
    /**
2690
     * Generate a new prerequisites string for a given item. If this item was a sco and
2691
     * its prerequisites were strings (instead of IDs), then transform those strings into
2692
     * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
2693
     * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
2694
     * same rule as the scorm_export() method
2695
     * @param	integer		Item ID
2696
     * @return	string		Prerequisites string ready for the export as SCORM
2697
     */
2698
    public function get_scorm_prereq_string($item_id)
2699
    {
2700
        if ($this->debug > 0) {
2701
            error_log('New LP - In learnpath::get_scorm_prereq_string()', 0);
2702
        }
2703
        if (!is_object($this->items[$item_id])) {
2704
            return false;
2705
        }
2706
        /** @var learnpathItem $oItem */
2707
        $oItem = $this->items[$item_id];
2708
        $prereq = $oItem->get_prereq_string();
2709
2710
        if (empty($prereq)) {
2711
            return '';
2712
        }
2713
        if (preg_match('/^\d+$/', $prereq) && is_object($this->items[$prereq])) {
2714
            // If the prerequisite is a simple integer ID and this ID exists as an item ID,
2715
            // then simply return it (with the ITEM_ prefix).
2716
            //return 'ITEM_' . $prereq;
2717
            return $this->items[$prereq]->ref;
2718
        } else {
2719
            if (isset($this->refs_list[$prereq])) {
2720
                // It's a simple string item from which the ID can be found in the refs list,
2721
                // so we can transform it directly to an ID for export.
2722
                return $this->items[$this->refs_list[$prereq]]->ref;
2723
            } else if (isset($this->refs_list['ITEM_'.$prereq])) {
2724
                return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
2725
            } else {
2726
                // The last case, if it's a complex form, then find all the IDs (SCORM strings)
2727
                // and replace them, one by one, by the internal IDs (chamilo db)
2728
                // TODO: Modify the '*' replacement to replace the multiplier in front of it
2729
                // by a space as well.
2730
                $find = array (
2731
                    '&',
2732
                    '|',
2733
                    '~',
2734
                    '=',
2735
                    '<>',
2736
                    '{',
2737
                    '}',
2738
                    '*',
2739
                    '(',
2740
                    ')'
2741
                );
2742
                $replace = array (
2743
                    ' ',
2744
                    ' ',
2745
                    ' ',
2746
                    ' ',
2747
                    ' ',
2748
                    ' ',
2749
                    ' ',
2750
                    ' ',
2751
                    ' ',
2752
                    ' '
2753
                );
2754
                $prereq_mod = str_replace($find, $replace, $prereq);
2755
                $ids = explode(' ', $prereq_mod);
2756
                foreach ($ids as $id) {
2757
                    $id = trim($id);
2758
                    if (isset ($this->refs_list[$id])) {
2759
                        $prereq = preg_replace('/[^a-zA-Z_0-9](' . $id . ')[^a-zA-Z_0-9]/', 'ITEM_' . $this->refs_list[$id], $prereq);
2760
                    }
2761
                }
2762
2763
                return $prereq;
2764
            }
2765
        }
2766
    }
2767
2768
    /**
2769
     * Returns the XML DOM document's node
2770
     * @param	resource	Reference to a list of objects to search for the given ITEM_*
2771
     * @param	string		The identifier to look for
2772
     * @return	mixed		The reference to the element found with that identifier. False if not found
2773
     */
2774
    public function get_scorm_xml_node(& $children, $id)
2775
    {
2776
        for ($i = 0; $i < $children->length; $i++) {
2777
            $item_temp = $children->item($i);
2778
            if ($item_temp->nodeName == 'item') {
2779
                if ($item_temp->getAttribute('identifier') == $id) {
2780
                    return $item_temp;
2781
                }
2782
            }
2783
            $subchildren = $item_temp->childNodes;
2784
            if ($subchildren->length > 0) {
2785
                $val = $this->get_scorm_xml_node($subchildren, $id);
2786
                if (is_object($val)) {
2787
2788
                    return $val;
2789
                }
2790
            }
2791
        }
2792
2793
        return false;
2794
    }
2795
2796
    /**
2797
     * Returns a usable array of stats related to the current learnpath and user
2798
     * @return array	Well-formatted array containing status for the current learnpath
2799
     */
2800
    public function get_stats()
2801
    {
2802
        if ($this->debug > 0) {
2803
            error_log('New LP - In learnpath::get_stats()', 0);
2804
        }
2805
    }
2806
2807
    /**
2808
     * Static method. Can be re-implemented by children. Gives an array of statistics for
2809
     * the given course (for all learnpaths and all users)
2810
     * @param	string	Course code
2811
     * @return array	Well-formatted array containing status for the course's learnpaths
2812
     */
2813
    public function get_stats_course($course)
2814
    {
2815
        //if ($this->debug > 0) { error_log('New LP - In learnpath::get_stats_course()', 0); }
2816
        // TODO
2817
    }
2818
2819
    /**
2820
     * Static method. Can be re-implemented by children. Gives an array of statistics for
2821
     * the given course and learnpath (for all users)
2822
     * @param	string	Course code
2823
     * @param	integer	Learnpath ID
2824
     * @return array	Well-formatted array containing status for the specified learnpath
2825
     */
2826
    public function get_stats_lp($course, $lp)
2827
    {
2828
        //if ($this->debug > 0) { error_log('New LP - In learnpath::get_stats_lp()', 0); }
2829
        // TODO
2830
    }
2831
2832
    /**
2833
     * Static method. Can be re-implemented by children. Gives an array of statistics for
2834
     * the given course, learnpath and user.
2835
     * @param	string	Course code
2836
     * @param	integer	Learnpath ID
2837
     * @param	integer	User ID
2838
     * @return array	Well-formatted array containing status for the specified learnpath and user
2839
     */
2840
    public function get_stats_lp_user($course, $lp, $user)
2841
    {
2842
        //if ($this->debug > 0) { error_log('New LP - In learnpath::get_stats_lp_user()', 0); }
2843
        // TODO
2844
    }
2845
2846
    /**
2847
     * Static method. Can be re-implemented by children. Gives an array of statistics for
2848
     * the given course and learnpath (for all users)
2849
     * @param	string	Course code
2850
     * @param	integer	User ID
2851
     * @return array	Well-formatted array containing status for the user's learnpaths
2852
     */
2853
    public function get_stats_user($course, $user) {
2854
        //if ($this->debug > 0) { error_log('New LP - In learnpath::get_stats_user()', 0); }
2855
        // TODO
2856
    }
2857
2858
    /**
2859
     * Gets the status list for all LP's items
2860
     * @return	array	Array of [index] => [item ID => current status]
2861
     */
2862
    public function get_items_status_list()
2863
    {
2864
        if ($this->debug > 0) {
2865
            error_log('New LP - In learnpath::get_items_status_list()', 0);
2866
        }
2867
        $list = array ();
2868
        foreach ($this->ordered_items as $item_id) {
2869
            $list[] = array (
2870
                $item_id => $this->items[$item_id]->get_status()
2871
            );
2872
        }
2873
        return $list;
2874
    }
2875
2876
    /**
2877
     * Return the number of interactions for the given learnpath Item View ID.
2878
     * This method can be used as static.
2879
     * @param	integer	Item View ID
2880
     * @param   integer course id
2881
     * @return	integer	Number of interactions
2882
     */
2883 View Code Duplication
    public static function get_interactions_count_from_db($lp_iv_id, $course_id)
2884
    {
2885
        $table = Database :: get_course_table(TABLE_LP_IV_INTERACTION);
2886
        $lp_iv_id = intval($lp_iv_id);
2887
        $course_id = intval($course_id);
2888
2889
        $sql = "SELECT count(*) FROM $table
2890
                WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
2891
        $res = Database::query($sql);
2892
        $num = 0;
2893
        if (Database::num_rows($res)) {
2894
            $row = Database::fetch_array($res);
2895
            $num = $row[0];
2896
        }
2897
        return $num;
2898
    }
2899
2900
    /**
2901
     * Return the interactions as an array for the given lp_iv_id.
2902
     * This method can be used as static.
2903
     * @param	integer	Learnpath Item View ID
2904
     * @return	array
2905
     * @todo 	Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
2906
     */
2907
    public static function get_iv_interactions_array($lp_iv_id)
2908
    {
2909
        $course_id = api_get_course_int_id();
2910
        $list = array();
2911
        $table = Database :: get_course_table(TABLE_LP_IV_INTERACTION);
2912
2913
        if (empty($lp_iv_id)) {
2914
            return array();
2915
        }
2916
2917
        $sql = "SELECT * FROM $table
2918
                WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
2919
                ORDER BY order_id ASC";
2920
        $res = Database::query($sql);
2921
        $num = Database :: num_rows($res);
2922
        if ($num > 0) {
2923
            $list[] = array (
2924
                'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
2925
                'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
2926
                'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
2927
                'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
2928
                'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
2929
                'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
2930
                'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
2931
                'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES)
2932
            );
2933
            while ($row = Database :: fetch_array($res)) {
2934
                $list[] = array (
2935
                    'order_id' => ($row['order_id'] + 1),
2936
                    'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
2937
                    'type' => $row['interaction_type'],
2938
                    'time' => $row['completion_time'],
2939
                    //'correct_responses' => $row['correct_responses'],
2940
                    'correct_responses' => '', // Hide correct responses from students.
2941
                    'student_response' => $row['student_response'],
2942
                    'result' => $row['result'],
2943
                    'latency' => $row['latency']
2944
                );
2945
            }
2946
        }
2947
2948
        return $list;
2949
    }
2950
2951
    /**
2952
     * Return the number of objectives for the given learnpath Item View ID.
2953
     * This method can be used as static.
2954
     * @param	integer	Item View ID
2955
     * @return	integer	Number of objectives
2956
     */
2957 View Code Duplication
    public static function get_objectives_count_from_db($lp_iv_id, $course_id)
2958
    {
2959
        $table = Database :: get_course_table(TABLE_LP_IV_OBJECTIVE);
2960
        $course_id = intval($course_id);
2961
        $lp_iv_id = intval($lp_iv_id);
2962
        $sql = "SELECT count(*) FROM $table
2963
                WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
2964
        //@todo seems that this always returns 0
2965
        $res = Database::query($sql);
2966
        $num = 0;
2967
        if (Database::num_rows($res)) {
2968
            $row = Database :: fetch_array($res);
2969
            $num = $row[0];
2970
        }
2971
2972
        return $num;
2973
    }
2974
2975
    /**
2976
     * Return the objectives as an array for the given lp_iv_id.
2977
     * This method can be used as static.
2978
     * @param	integer	Learnpath Item View ID
2979
     * @return	array
2980
     * @todo 	Translate labels
2981
     */
2982
    public static function get_iv_objectives_array($lp_iv_id = 0)
2983
    {
2984
        $course_id = api_get_course_int_id();
2985
        $table = Database :: get_course_table(TABLE_LP_IV_OBJECTIVE);
2986
        $sql = "SELECT * FROM $table
2987
                WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id
2988
                ORDER BY order_id ASC";
2989
        $res = Database::query($sql);
2990
        $num = Database :: num_rows($res);
2991
        $list = array();
2992
        if ($num > 0) {
2993
            $list[] = array(
2994
                'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
2995
                'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
2996
                'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
2997
                'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
2998
                'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
2999
                'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES)
3000
            );
3001
            while ($row = Database :: fetch_array($res)) {
3002
                $list[] = array (
3003
                    'order_id' => ($row['order_id'] + 1),
3004
                    'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F or stuff like that.
3005
                    'score_raw' => $row['score_raw'],
3006
                    'score_max' => $row['score_max'],
3007
                    'score_min' => $row['score_min'],
3008
                    'status' => $row['status']
3009
                );
3010
            }
3011
        }
3012
3013
        return $list;
3014
    }
3015
3016
    /**
3017
     * Generate and return the table of contents for this learnpath. The (flat) table returned can be
3018
     * used by get_html_toc() to be ready to display
3019
     * @return	array	TOC as a table with 4 elements per row: title, link, status and level
3020
     */
3021
    public function get_toc()
3022
    {
3023
        if ($this->debug > 0) {
3024
            error_log('learnpath::get_toc()', 0);
3025
        }
3026
        $toc = array();
3027
        foreach ($this->ordered_items as $item_id) {
3028
            if ($this->debug > 2) {
3029
                error_log('learnpath::get_toc(): getting info for item ' . $item_id, 0);
3030
            }
3031
            // TODO: Change this link generation and use new function instead.
3032
            $toc[] = array (
3033
                'id'            => $item_id,
3034
                'title'         => $this->items[$item_id]->get_title(),
3035
                'status'        => $this->items[$item_id]->get_status(),
3036
                'level'         => $this->items[$item_id]->get_level(),
3037
                'type'          => $this->items[$item_id]->get_type(),
3038
                'description'   => $this->items[$item_id]->get_description(),
3039
                'path'          => $this->items[$item_id]->get_path(),
3040
            );
3041
        }
3042
        if ($this->debug > 2) {
3043
            error_log('New LP - In learnpath::get_toc() - TOC array: ' . print_r($toc, true), 0);
3044
        }
3045
        return $toc;
3046
    }
3047
3048
    /**
3049
     * Generate and return the table of contents for this learnpath. The JS
3050
     * table returned is used inside of scorm_api.php
3051
     * @return  string  A JS array vairiable construction
3052
     */
3053
    public function get_items_details_as_js($varname = 'olms.lms_item_types')
3054
    {
3055
        if ($this->debug > 0) {
3056
            error_log('New LP - In learnpath::get_items_details_as_js()', 0);
3057
        }
3058
        $toc = $varname.' = new Array();';
3059
        foreach ($this->ordered_items as $item_id) {
3060
            $toc.= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
3061
        }
3062
        if ($this->debug > 2) {
3063
            error_log('New LP - In learnpath::get_items_details_as_js() - TOC array: ' . print_r($toc, true), 0);
3064
        }
3065
        return $toc;
3066
    }
3067
3068
    /**
3069
     * Gets the learning path type
3070
     * @param	boolean		Return the name? If false, return the ID. Default is false.
3071
     * @return	mixed		Type ID or name, depending on the parameter
3072
     */
3073
    public function get_type($get_name = false)
3074
    {
3075
        $res = false;
3076
        if ($this->debug > 0) {
3077
            error_log('New LP - In learnpath::get_type()', 0);
3078
        }
3079
        if (!empty ($this->type)) {
3080
            if ($get_name) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
3081
                // Get it from the lp_type table in main db.
3082
            } else {
3083
                $res = $this->type;
3084
            }
3085
        }
3086
        if ($this->debug > 2) {
3087
            error_log('New LP - In learnpath::get_type() - Returning ' . ($res ? $res : 'false'), 0);
3088
        }
3089
        return $res;
3090
    }
3091
3092
    /**
3093
     * Gets the learning path type as static method
3094
     * @param	boolean		Return the name? If false, return the ID. Default is false.
3095
     * @return	mixed		Type ID or name, depending on the parameter
3096
     */
3097
    public static function get_type_static($lp_id = 0)
3098
    {
3099
        $course_id = api_get_course_int_id();
3100
        $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
3101
        $lp_id = intval($lp_id);
3102
        $sql = "SELECT lp_type FROM $tbl_lp
3103
                WHERE c_id = $course_id AND id = '" . $lp_id . "'";
3104
        $res = Database::query($sql);
3105
        if ($res === false) {
3106
            return null;
3107
        }
3108
        if (Database :: num_rows($res) <= 0) {
3109
            return null;
3110
        }
3111
        $row = Database :: fetch_array($res);
3112
        return $row['lp_type'];
3113
    }
3114
3115
    /**
3116
     * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
3117
     * This method can be used as abstract and is recursive
3118
     * @param	integer	Learnpath ID
3119
     * @param	integer	Parent ID of the items to look for
3120
     * @return	mixed	Ordered list of item IDs or false on error
3121
     */
3122
    public static function get_flat_ordered_items_list($lp, $parent = 0, $course_id = null)
3123
    {
3124
        if (empty($course_id)) {
3125
            $course_id = api_get_course_int_id();
3126
        } else {
3127
            $course_id = intval($course_id);
3128
        }
3129
        $list = array();
3130
3131
        if (empty($lp)) {
3132
            return false;
3133
        }
3134
3135
        $lp = intval($lp);
3136
        $parent = intval($parent);
3137
3138
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
3139
        $sql = "SELECT id FROM $tbl_lp_item
3140
                WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
3141
                ORDER BY display_order";
3142
3143
        $res = Database::query($sql);
3144
        while ($row = Database :: fetch_array($res)) {
3145
            $sublist = learnpath :: get_flat_ordered_items_list($lp, $row['id'], $course_id);
3146
            $list[] = $row['id'];
3147
            foreach ($sublist as $item) {
3148
                $list[] = $item;
3149
            }
3150
        }
3151
        return $list;
3152
    }
3153
3154
    /**
3155
     * @return array
3156
     */
3157
    public static function getChapterTypes()
3158
    {
3159
        return array(
3160
            'dokeos_chapter',
3161
            'dokeos_module',
3162
            'chapter',
3163
            'dir'
3164
        );
3165
    }
3166
3167
    /**
3168
     * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display
3169
     * @return	string	HTML TOC ready to display
3170
     */
3171
    public function get_html_toc($toc_list = null)
3172
    {
3173
        $is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
3174
3175
        if ($this->debug > 0) {
3176
            error_log('In learnpath::get_html_toc()', 0);
3177
        }
3178
        if (empty($toc_list)) {
3179
            $toc_list = $this->get_toc();
3180
        }
3181
        //$html = '<div id="scorm_title" class="scorm-heading">'.Security::remove_XSS($this->get_name()) . '</div>';
3182
        $html = '<div class="scorm-body">';
3183
3184
3185
        $html .= '<div id="inner_lp_toc" class="inner_lp_toc scrollbar-light">';
3186
        require_once 'resourcelinker.inc.php';
3187
3188
        // Temporary variables.
3189
        $mycurrentitemid = $this->get_current_item_id();
3190
        $color_counter = 0;
3191
        $i = 0;
3192
3193
        foreach ($toc_list as $item) {
3194
3195
            // Style Status
3196
            $class_name = [
3197
                'not attempted' => 'scorm_not_attempted',
3198
                'incomplete' => 'scorm_not_attempted',
3199
                'failed' => 'scorm_failed',
3200
                'completed' => 'scorm_completed',
3201
                'passed' => 'scorm_completed',
3202
                'succeeded' => 'scorm_completed',
3203
                'browsed' => 'scorm_completed',
3204
            ];
3205
3206
            $scorm_color_background = 'row_odd';
3207
            $style_item = '';
3208
3209
            if ($color_counter % 2 == 0) {
3210
                $scorm_color_background = 'row_even';
3211
            }
3212
3213
            $dirTypes = self::getChapterTypes();
3214
3215
            if (in_array($item['type'], $dirTypes)) {
3216
                $scorm_color_background ='scorm_item_section ';
3217
                $style_item = '';
3218
            }
3219
            if ($item['id'] == $this->current) {
3220
                $scorm_color_background = 'scorm_item_normal '.$scorm_color_background.' scorm_highlight';
3221
            } elseif (!in_array($item['type'], $dirTypes)) {
3222
                $scorm_color_background = 'scorm_item_normal '.$scorm_color_background.' ';
3223
            }
3224
3225
            $html .= '<div id="toc_' . $item['id'] . '" class="' . $scorm_color_background . ' '.$class_name[$item['status']].' ">';
3226
3227
            // Learning path title
3228
            $title = $item['title'];
3229
            if (empty ($title)) {
3230
                $title = rl_get_resource_name(api_get_course_id(), $this->get_id(), $item['id']);
3231
            }
3232
            $title = Security::remove_XSS($title);
3233
3234
            // Learning path personalization
3235
            // build the LP tree
3236
            // The anchor atoc_ will let us center the TOC on the currently viewed item &^D
3237
            $description = $item['description'];
3238
            if (empty($description)) {
3239
                $description = $title;
3240
            }
3241
            if (in_array($item['type'], $dirTypes)) {
3242
                // Chapters
3243
                $html .= '<div class="'.$style_item.' scorm_section_level_'.$item['level'].'" title="'.$description.'" >';
3244
            } else {
3245
                $html .= '<div class="'.$style_item.' scorm_item_level_'.$item['level'].' scorm_type_'.learnpath::format_scorm_type_item($item['type']).'" title="'.$description.'" >';
3246
                $html .= '<a name="atoc_'.$item['id'].'"></a>';
3247
            }
3248
3249
            if (in_array($item['type'], $dirTypes)) {
3250
                // Chapter
3251
                // if you want to put an image before, you should use css
3252
                $html .= stripslashes($title);
3253
            } else {
3254
                $this->get_link('http', $item['id'], $toc_list);
3255
                $html .= '<a class="items-list" href="#" onclick="switch_item(' .$mycurrentitemid . ',' .$item['id'] . ');' .'return false;" >' . stripslashes($title) . '</a>';
3256
            }
3257
            $html .= "</div>";
3258
3259
            if ($scorm_color_background != '') {
3260
                $html .= '</div>';
3261
            }
3262
3263
            $color_counter++;
3264
        }
3265
        $html .= "</div>";
3266
        $html .= "</div>";
3267
        return $html;
3268
    }
3269
3270
    /**
3271
     * Returns an HTML-formatted string ready to display with teacher buttons
3272
     * in LP view menu
3273
     * @return	string	HTML TOC ready to display
3274
     */
3275
    public function get_teacher_toc_buttons()
3276
    {
3277
        $is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
3278
        $hide_teacher_icons_lp = api_get_configuration_value('hide_teacher_icons_lp');
3279
        $html = '';
3280
3281
        if ($is_allowed_to_edit && $hide_teacher_icons_lp == false) {
3282
            $gradebook = '';
3283
            if (!empty($_GET['gradebook'])) {
3284
                $gradebook = Security:: remove_XSS($_GET['gradebook']);
3285
            }
3286
            if ($this->get_lp_session_id() == api_get_session_id()) {
3287
                $html .= '<div id="actions_lp" class="actions_lp"><hr>';
3288
                $html .= '<div class="btn-group">';
3289
                $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?" . api_get_cidreq()."&gradebook=$gradebook&action=build&lp_id=" . $this->lp_id . "&isStudentView=false' target='_parent'>" .
3290
                    Display::returnFontAwesomeIcon('street-view') . get_lang('Overview') . "</a>";
3291
                $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?" . api_get_cidreq()."&action=add_item&type=step&lp_id=" . $this->lp_id . "&isStudentView=false' target='_parent'>" .
3292
                    Display::returnFontAwesomeIcon('pencil') . get_lang('Edit') . "</a>";
3293
                $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&gradebook=$gradebook&action=edit&lp_id=" . $this->lp_id.'&isStudentView=false">' .
3294
                    Display::returnFontAwesomeIcon('cog') . get_lang('Settings').'</a>';
3295
                $html .= '</div>';
3296
                $html .= '</div>';
3297
            }
3298
        }
3299
        return $html;
3300
3301
    }
3302
    /**
3303
     * Gets the learnpath maker name - generally the editor's name
3304
     * @return	string	Learnpath maker name
3305
     */
3306
    public function get_maker()
3307
    {
3308
        if ($this->debug > 0) {
3309
            error_log('New LP - In learnpath::get_maker()', 0);
3310
        }
3311
        if (!empty ($this->maker)) {
3312
            return $this->maker;
3313
        } else {
3314
            return '';
3315
        }
3316
    }
3317
3318
    /**
3319
     * Gets the learnpath name/title
3320
     * @return	string	Learnpath name/title
3321
     */
3322 View Code Duplication
    public function get_name()
3323
    {
3324
        if ($this->debug > 0) {
3325
            error_log('New LP - In learnpath::get_name()', 0);
3326
        }
3327
        if (!empty ($this->name)) {
3328
            return $this->name;
3329
        } else {
3330
            return 'N/A';
3331
        }
3332
    }
3333
3334
    /**
3335
     * Gets a link to the resource from the present location, depending on item ID.
3336
     * @param	string	$type Type of link expected
3337
     * @param	integer	$item_id Learnpath item ID
3338
     * @return	string	$provided_toc Link to the lp_item resource
3339
     */
3340
    public function get_link($type = 'http', $item_id = null, $provided_toc = false)
3341
    {
3342
        $course_id = $this->get_course_int_id();
3343
3344 View Code Duplication
        if ($this->debug > 0) {
3345
            error_log('New LP - In learnpath::get_link(' . $type . ',' . $item_id . ')', 0);
3346
        }
3347 View Code Duplication
        if (empty($item_id)) {
3348
            if ($this->debug > 2) {
3349
                error_log('New LP - In learnpath::get_link() - no item id given in learnpath::get_link(), using current: ' . $this->get_current_item_id(), 0);
3350
            }
3351
            $item_id = $this->get_current_item_id();
3352
        }
3353
3354 View Code Duplication
        if (empty($item_id)) {
3355
            if ($this->debug > 2) {
3356
                error_log('New LP - In learnpath::get_link() - no current item id found in learnpath object', 0);
3357
            }
3358
            //still empty, this means there was no item_id given and we are not in an object context or
3359
            //the object property is empty, return empty link
3360
            $item_id = $this->first();
3361
            return '';
3362
        }
3363
3364
        $file = '';
3365
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
3366
        $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
3367
        $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
3368
        $item_id = intval($item_id);
3369
3370
        $sql = "SELECT
3371
                    l.lp_type as ltype,
3372
                    l.path as lpath,
3373
                    li.item_type as litype,
3374
                    li.path as lipath,
3375
                    li.parameters as liparams
3376
        		FROM $lp_table l
3377
                INNER JOIN $lp_item_table li
3378
                    ON (li.lp_id = l.id AND l.c_id = $course_id AND li.c_id = $course_id )
3379
        		WHERE li.id = $item_id ";
3380
        if ($this->debug > 2) {
3381
            error_log('New LP - In learnpath::get_link() - selecting item ' . $sql, 0);
3382
        }
3383
        $res = Database::query($sql);
3384
        if (Database :: num_rows($res) > 0) {
3385
            $row = Database :: fetch_array($res);
3386
            $lp_type = $row['ltype'];
3387
            $lp_path = $row['lpath'];
3388
            $lp_item_type = $row['litype'];
3389
            $lp_item_path = $row['lipath'];
3390
            $lp_item_params = $row['liparams'];
3391
3392
            if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
3393
                list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
3394
            }
3395
            $sys_course_path = api_get_path(SYS_COURSE_PATH) . api_get_course_path();
3396
            if ($type == 'http') {
3397
                $course_path = api_get_path(WEB_COURSE_PATH) . api_get_course_path(); //web path
3398
            } else {
3399
                $course_path = $sys_course_path; //system path
3400
            }
3401
3402
            // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc), then change the lp type to thread it as a normal Chamilo LP not a SCO.
3403
            if (in_array($lp_item_type, array('quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication'))) {
3404
                $lp_type = 1;
3405
            }
3406
3407
            if ($this->debug > 2) {
3408
                error_log('New LP - In learnpath::get_link() - $lp_type ' . $lp_type, 0);
3409
                error_log('New LP - In learnpath::get_link() - $lp_item_type ' . $lp_item_type, 0);
3410
            }
3411
3412
            // Now go through the specific cases to get the end of the path
3413
            // @todo Use constants instead of int values.
3414
            switch ($lp_type) {
3415
                case 1 :
3416
                    if ($lp_item_type == 'dokeos_chapter') {
3417
                        $file = 'lp_content.php?type=dir';
3418
                    } else {
3419
                        require_once 'resourcelinker.inc.php';
3420
                        $file = rl_get_resource_link_for_learnpath(
3421
                            $course_id,
3422
                            $this->get_id(),
3423
                            $item_id,
3424
                            $this->get_view_id()
3425
                        );
3426
3427
                        if ($this->debug > 0) {
3428
                            error_log('rl_get_resource_link_for_learnpath - file: ' . $file, 0);
3429
                        }
3430
3431
                        if ($lp_item_type == 'link') {
3432
                            if (Link::is_youtube_link($file)) {
3433
                                $src  = Link::get_youtube_video_id($file);
3434
                                $file = api_get_path(WEB_CODE_PATH).'newscorm/embed.php?type=youtube&source='.$src;
3435
                            } elseif (Link::isVimeoLink($file)) {
3436
                                $src  = Link::getVimeoLinkId($file);
3437
                                $file = api_get_path(WEB_CODE_PATH).'newscorm/embed.php?type=vimeo&source='.$src;
3438
                            } else {
3439
                                // If the current site is HTTPS and the link is
3440
                                // HTTP, browsers will refuse opening the link
3441
                                $urlId = api_get_current_access_url_id();
3442
                                $url = api_get_access_url($urlId, false);
3443
                                $protocol = substr($url['url'], 0, 5);
3444
                                if ($protocol === 'https') {
3445
                                    $linkProtocol = substr($file, 0, 5);
3446
                                    if ($linkProtocol === 'http:') {
3447
                                        //this is the special intervention case
3448
                                        $file = api_get_path(WEB_CODE_PATH).'newscorm/embed.php?type=nonhttps&source=' .  urlencode($file);
3449
                                    }
3450
                                }
3451
                            }
3452
                        } else {
3453
                            // Check how much attempts of a exercise exits in lp
3454
                            $lp_item_id = $this->get_current_item_id();
3455
                            $lp_view_id = $this->get_view_id();
3456
3457
                            $prevent_reinit = null;
3458
                            if (isset($this->items[$this->current])) {
3459
                                $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
3460
                            }
3461
3462
                            if (empty($provided_toc)) {
3463
                                if ($this->debug > 0) {
3464
                                    error_log('In learnpath::get_link() Loading get_toc ', 0);
3465
                                }
3466
                                $list = $this->get_toc();
3467
                            } else {
3468
                                if ($this->debug > 0) {
3469
                                    error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
3470
                                }
3471
                                $list = $provided_toc;
3472
                            }
3473
3474
                            $type_quiz = false;
3475
3476 View Code Duplication
                            foreach ($list as $toc) {
0 ignored issues
show
Bug introduced by
The expression $list of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3477
                                if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
3478
                                    $type_quiz = true;
3479
                                }
3480
                            }
3481
3482
                            if ($type_quiz) {
3483
                                $lp_item_id = intval($lp_item_id);
3484
                                $lp_view_id = intval($lp_view_id);
3485
                                $sql = "SELECT count(*) FROM $lp_item_view_table
3486
                                        WHERE
3487
                                            c_id = $course_id AND
3488
                                            lp_item_id='" . $lp_item_id . "' AND
3489
                                            lp_view_id ='" . $lp_view_id . "' AND
3490
                                            status='completed'";
3491
                                $result = Database::query($sql);
3492
                                $row_count = Database :: fetch_row($result);
3493
                                $count_item_view = (int) $row_count[0];
3494
                                $not_multiple_attempt = 0;
3495
                                if ($prevent_reinit === 1 && $count_item_view > 0) {
3496
                                    $not_multiple_attempt = 1;
3497
                                }
3498
                                $file .= '&not_multiple_attempt=' . $not_multiple_attempt;
3499
                            }
3500
3501
                            $tmp_array = explode('/', $file);
3502
                            $document_name = $tmp_array[count($tmp_array) - 1];
3503
                            if (strpos($document_name, '_DELETED_')) {
3504
                                $file = 'blank.php?error=document_deleted';
3505
                            }
3506
                        }
3507
                    }
3508
                    break;
3509
                case 2 :
3510
                    if ($this->debug > 2) {
3511
                        error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - Item type: ' . $lp_item_type, 0);
3512
                    }
3513
3514
                    if ($lp_item_type != 'dir') {
3515
                        // Quite complex here:
3516
                        // We want to make sure 'http://' (and similar) links can
3517
                        // be loaded as is (withouth the Chamilo path in front) but
3518
                        // some contents use this form: resource.htm?resource=http://blablabla
3519
                        // which means we have to find a protocol at the path's start, otherwise
3520
                        // it should not be considered as an external URL.
3521
3522
                        //if ($this->prerequisites_match($item_id)) {
3523
                        if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
3524
                            if ($this->debug > 2) {
3525
                                error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - Found match for protocol in ' . $lp_item_path, 0);
3526
                            }
3527
                            // Distant url, return as is.
3528
                            $file = $lp_item_path;
3529
                        } else {
3530
                            if ($this->debug > 2) {
3531
                                error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - No starting protocol in ' . $lp_item_path, 0);
3532
                            }
3533
                            // Prevent getting untranslatable urls.
3534
                            $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
3535
                            $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
3536
                            // Prepare the path.
3537
                            $file = $course_path . '/scorm/' . $lp_path . '/' . $lp_item_path;
3538
                            // TODO: Fix this for urls with protocol header.
3539
                            $file = str_replace('//', '/', $file);
3540
                            $file = str_replace(':/', '://', $file);
3541
                            if (substr($lp_path, -1) == '/') {
3542
                                $lp_path = substr($lp_path, 0, -1);
3543
                            }
3544
3545
                            if (!is_file(realpath($sys_course_path . '/scorm/' . $lp_path . '/' . $lp_item_path))) {
3546
                                // if file not found.
3547
                                $decoded = html_entity_decode($lp_item_path);
3548
                                list ($decoded) = explode('?', $decoded);
3549
                                if (!is_file(realpath($sys_course_path . '/scorm/' . $lp_path . '/' . $decoded))) {
3550
                                    require_once 'resourcelinker.inc.php';
3551
                                    $file = rl_get_resource_link_for_learnpath(
3552
                                        $course_id,
3553
                                        $this->get_id(),
3554
                                        $item_id,
3555
                                        $this->get_view_id()
3556
                                    );
3557
                                    if (empty($file)) {
3558
                                        $file = 'blank.php?error=document_not_found';
3559
                                    } else {
3560
                                        $tmp_array = explode('/', $file);
3561
                                        $document_name = $tmp_array[count($tmp_array) - 1];
3562
                                        if (strpos($document_name, '_DELETED_')) {
3563
                                            $file = 'blank.php?error=document_deleted';
3564
                                        } else {
3565
                                            $file = 'blank.php?error=document_not_found';
3566
                                        }
3567
                                    }
3568
                                } else {
3569
                                    $file = $course_path . '/scorm/' . $lp_path . '/' . $decoded;
3570
                                }
3571
                            }
3572
                        }
3573
3574
                        // We want to use parameters if they were defined in the imsmanifest
3575
                        if (strpos($file, 'blank.php') === false) {
3576
                            $file .= (strstr($file, '?') === false ? '?' : '') . $lp_item_params;
3577
                        }
3578
                    } else {
3579
                        $file = 'lp_content.php?type=dir';
3580
                    }
3581
                    break;
3582
                case 3 :
3583
                    if ($this->debug > 2) {
3584
                        error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - Item type: ' . $lp_item_type, 0);
3585
                    }
3586
                    // Formatting AICC HACP append URL.
3587
                    $aicc_append = '?aicc_sid=' . urlencode(session_id()) . '&aicc_url=' . urlencode(api_get_path(WEB_CODE_PATH) . 'newscorm/aicc_hacp.php') . '&';
3588
                    if (!empty($lp_item_params)) {
3589
                        $aicc_append .= $lp_item_params . '&';
3590
                    }
3591
                    if ($lp_item_type != 'dir') {
3592
                        // Quite complex here:
3593
                        // We want to make sure 'http://' (and similar) links can
3594
                        // be loaded as is (withouth the Chamilo path in front) but
3595
                        // some contents use this form: resource.htm?resource=http://blablabla
3596
                        // which means we have to find a protocol at the path's start, otherwise
3597
                        // it should not be considered as an external URL.
3598
3599
                        if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
3600
                            if ($this->debug > 2) {
3601
                                error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - Found match for protocol in ' . $lp_item_path, 0);
3602
                            }
3603
                            // Distant url, return as is.
3604
                            $file = $lp_item_path;
3605
                            // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
3606
                            /*
3607
                            if (stristr($file,'<servername>') !== false) {
3608
                                $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
3609
                            }
3610
                            */
3611
                            if (stripos($file, '<servername>') !== false) {
3612
                                //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
3613
                                $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
3614
                                $file = str_replace('<servername>', $web_course_path . '/scorm/' . $lp_path, $lp_item_path);
3615
                            }
3616
                            //
3617
                            $file .= $aicc_append;
3618
                        } else {
3619
                            if ($this->debug > 2) {
3620
                                error_log('New LP - In learnpath::get_link() ' . __LINE__ . ' - No starting protocol in ' . $lp_item_path, 0);
3621
                            }
3622
                            // Prevent getting untranslatable urls.
3623
                            $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
3624
                            $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
3625
                            // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
3626
                            $file = $course_path . '/scorm/' . $lp_path . '/' . $lp_item_path;
3627
                            // TODO: Fix this for urls with protocol header.
3628
                            $file = str_replace('//', '/', $file);
3629
                            $file = str_replace(':/', '://', $file);
3630
                            $file .= $aicc_append;
3631
                        }
3632
                    } else {
3633
                        $file = 'lp_content.php?type=dir';
3634
                    }
3635
                    break;
3636
                case 4 :
3637
                    break;
3638
                default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
3639
                    break;
3640
            }
3641
            // Replace &amp; by & because &amp; will break URL with params
3642
            $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
3643
        }
3644
        if ($this->debug > 2) {
3645
            error_log('New LP - In learnpath::get_link() - returning "' . $file . '" from get_link', 0);
3646
        }
3647
        return $file;
3648
    }
3649
3650
    /**
3651
     * Gets the latest usable view or generate a new one
3652
     * @param	integer	Optional attempt number. If none given, takes the highest from the lp_view table
3653
     * @return	integer	DB lp_view id
3654
     */
3655
    public function get_view($attempt_num = 0)
3656
    {
3657
        if ($this->debug > 0) {
3658
            error_log('New LP - In learnpath::get_view()', 0);
3659
        }
3660
        $search = '';
3661
        // Use $attempt_num to enable multi-views management (disabled so far).
3662
        if ($attempt_num != 0 AND intval(strval($attempt_num)) == $attempt_num) {
3663
            $search = 'AND view_count = ' . $attempt_num;
3664
        }
3665
        // When missing $attempt_num, search for a unique lp_view record for this lp and user.
3666
        $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW);
3667
3668
        $course_id = api_get_course_int_id();
3669
        $sessionId = api_get_session_id();
3670
3671
        $sql = "SELECT id, view_count FROM $lp_view_table
3672
        		WHERE
3673
        		    c_id = " . $course_id . " AND
3674
        		    lp_id = " . $this->get_id() . " AND
3675
        		    user_id = " . $this->get_user_id() . " AND
3676
        		    session_id = $sessionId
3677
        		    $search
3678
                ORDER BY view_count DESC";
3679
        $res = Database::query($sql);
3680
        if (Database :: num_rows($res) > 0) {
3681
            $row = Database :: fetch_array($res);
3682
            $this->lp_view_id = $row['id'];
3683
        } else if (!api_is_invitee()) {
3684
            // There is no database record, create one.
3685
            $sql = "INSERT INTO $lp_view_table (c_id, lp_id,user_id, view_count, session_id) VALUES
3686
            		($course_id, " . $this->get_id() . "," . $this->get_user_id() . ", 1, $sessionId)";
3687
            Database::query($sql);
3688
            $id = Database :: insert_id();
3689
            $this->lp_view_id = $id;
3690
3691
            $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
3692
            Database::query($sql);
3693
        }
3694
3695
        return $this->lp_view_id;
3696
    }
3697
3698
    /**
3699
     * Gets the current view id
3700
     * @return	integer	View ID (from lp_view)
3701
     */
3702
    public function get_view_id()
3703
    {
3704
        if ($this->debug > 0) {
3705
            error_log('New LP - In learnpath::get_view_id()', 0);
3706
        }
3707
        if (!empty ($this->lp_view_id)) {
3708
            return $this->lp_view_id;
3709
        } else {
3710
            return 0;
3711
        }
3712
    }
3713
3714
    /**
3715
     * Gets the update queue
3716
     * @return	array	Array containing IDs of items to be updated by JavaScript
3717
     */
3718
    public function get_update_queue()
3719
    {
3720
        if ($this->debug > 0) {
3721
            error_log('New LP - In learnpath::get_update_queue()', 0);
3722
        }
3723
        return $this->update_queue;
3724
    }
3725
3726
    /**
3727
     * Gets the user ID
3728
     * @return	integer	User ID
3729
     */
3730 View Code Duplication
    public function get_user_id()
3731
    {
3732
        if ($this->debug > 0) {
3733
            error_log('New LP - In learnpath::get_user_id()', 0);
3734
        }
3735
        if (!empty ($this->user_id)) {
3736
            return $this->user_id;
3737
        } else {
3738
            return false;
3739
        }
3740
    }
3741
3742
    /**
3743
     * Checks if any of the items has an audio element attached
3744
     * @return  bool    True or false
3745
     */
3746
    public function has_audio()
3747
    {
3748
        if ($this->debug > 1) {
3749
            error_log('New LP - In learnpath::has_audio()', 0);
3750
        }
3751
        $has = false;
3752
        foreach ($this->items as $i => $item) {
3753
            if (!empty ($this->items[$i]->audio)) {
3754
                $has = true;
3755
                break;
3756
            }
3757
        }
3758
        return $has;
3759
    }
3760
3761
    /**
3762
     * Logs a message into a file
3763
     * @param	string 	Message to log
3764
     * @return	boolean	True on success, false on error or if msg empty
3765
     */
3766
    public function log($msg)
3767
    {
3768
        if ($this->debug > 0) {
3769
            error_log('New LP - In learnpath::log()', 0);
3770
        }
3771
        // TODO
3772
        $this->error .= $msg;
3773
        return true;
3774
    }
3775
3776
    /**
3777
     * Moves an item up and down at its level
3778
     * @param	integer	Item to move up and down
3779
     * @param	string	Direction 'up' or 'down'
3780
     * @return	integer	New display order, or false on error
3781
     */
3782
    public function move_item($id, $direction)
3783
    {
3784
        $course_id = api_get_course_int_id();
3785
        if ($this->debug > 0) {
3786
            error_log('New LP - In learnpath::move_item(' . $id . ',' . $direction . ')', 0);
3787
        }
3788
        if (empty($id) || empty($direction)) {
3789
            return false;
3790
        }
3791
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
3792
        $sql_sel = "SELECT *
3793
                    FROM " . $tbl_lp_item . "
3794
                    WHERE c_id = ".$course_id." AND id = " . $id;
3795
        $res_sel = Database::query($sql_sel);
3796
        // Check if elem exists.
3797
        if (Database :: num_rows($res_sel) < 1) {
3798
            return false;
3799
        }
3800
        // Gather data.
3801
        $row = Database :: fetch_array($res_sel);
3802
        $previous = $row['previous_item_id'];
3803
        $next = $row['next_item_id'];
3804
        $display = $row['display_order'];
3805
        $parent = $row['parent_item_id'];
3806
        $lp = $row['lp_id'];
3807
        // Update the item (switch with previous/next one).
3808
        switch ($direction) {
3809
            case 'up':
3810
                if ($this->debug > 2) {
3811
                    error_log('Movement up detected', 0);
3812
                }
3813
                if ($display <= 1) { /*do nothing*/
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
3814
                } else {
3815
                    $sql_sel2 = "SELECT * FROM $tbl_lp_item
3816
                                 WHERE c_id = ".$course_id." AND id = $previous";
3817
3818
                    if ($this->debug > 2) {
3819
                        error_log('Selecting previous: ' . $sql_sel2, 0);
3820
                    }
3821
                    $res_sel2 = Database::query($sql_sel2);
3822
                    if (Database :: num_rows($res_sel2) < 1) {
3823
                        $previous_previous = 0;
3824
                    }
3825
                    // Gather data.
3826
                    $row2 = Database :: fetch_array($res_sel2);
3827
                    $previous_previous = $row2['previous_item_id'];
3828
                    // Update previous_previous item (switch "next" with current).
3829 View Code Duplication
                    if ($previous_previous != 0) {
3830
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3831
                                        next_item_id = $id
3832
                                    WHERE c_id = ".$course_id." AND id = $previous_previous";
3833
                        if ($this->debug > 2) {
3834
                            error_log($sql_upd2, 0);
3835
                        }
3836
                        Database::query($sql_upd2);
3837
                    }
3838
                    // Update previous item (switch with current).
3839 View Code Duplication
                    if ($previous != 0) {
3840
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3841
                                    next_item_id = $next,
3842
                                    previous_item_id = $id,
3843
                                    display_order = display_order +1
3844
                                    WHERE c_id = ".$course_id." AND id = $previous";
3845
                        if ($this->debug > 2) {
3846
                            error_log($sql_upd2, 0);
3847
                        }
3848
                        Database::query($sql_upd2);
3849
                    }
3850
3851
                    // Update current item (switch with previous).
3852 View Code Duplication
                    if ($id != 0) {
3853
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3854
                                        next_item_id = $previous,
3855
                                        previous_item_id = $previous_previous,
3856
                                        display_order = display_order-1
3857
                                    WHERE c_id = ".$course_id." AND id = $id";
3858
                        if ($this->debug > 2) {
3859
                            error_log($sql_upd2, 0);
3860
                        }
3861
                        Database::query($sql_upd2);
3862
                    }
3863
                    // Update next item (new previous item).
3864 View Code Duplication
                    if ($next != 0) {
3865
                        $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
3866
                                     WHERE c_id = ".$course_id." AND id = $next";
3867
                        if ($this->debug > 2) {
3868
                            error_log($sql_upd2, 0);
3869
                        }
3870
                        Database::query($sql_upd2);
3871
                    }
3872
                    $display = $display -1;
3873
                }
3874
                break;
3875
            case 'down':
3876
                if ($this->debug > 2) {
3877
                    error_log('Movement down detected', 0);
3878
                }
3879
                if ($next == 0) { /* Do nothing. */
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
3880
                } else {
3881
                    $sql_sel2 = "SELECT * FROM $tbl_lp_item WHERE c_id = ".$course_id." AND id = $next";
3882
                    if ($this->debug > 2) {
3883
                        error_log('Selecting next: ' . $sql_sel2, 0);
3884
                    }
3885
                    $res_sel2 = Database::query($sql_sel2);
3886
                    if (Database :: num_rows($res_sel2) < 1) {
3887
                        $next_next = 0;
3888
                    }
3889
                    // Gather data.
3890
                    $row2 = Database :: fetch_array($res_sel2);
3891
                    $next_next = $row2['next_item_id'];
3892
                    // Update previous item (switch with current).
3893 View Code Duplication
                    if ($previous != 0) {
3894
                        $sql_upd2 = "UPDATE $tbl_lp_item SET next_item_id = $next
3895
                                     WHERE c_id = ".$course_id." AND id = $previous";
3896
                        Database::query($sql_upd2);
3897
                    }
3898
                    // Update current item (switch with previous).
3899 View Code Duplication
                    if ($id != 0) {
3900
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3901
                                     previous_item_id = $next, next_item_id = $next_next, display_order = display_order+1
3902
                                     WHERE c_id = ".$course_id." AND id = $id";
3903
                        Database::query($sql_upd2);
3904
                    }
3905
3906
                    // Update next item (new previous item).
3907 View Code Duplication
                    if ($next != 0) {
3908
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3909
                                     previous_item_id = $previous, next_item_id = $id, display_order = display_order-1
3910
                                     WHERE c_id = ".$course_id." AND id = $next";
3911
                        Database::query($sql_upd2);
3912
                    }
3913
3914
                    // Update next_next item (switch "previous" with current).
3915 View Code Duplication
                    if ($next_next != 0) {
3916
                        $sql_upd2 = "UPDATE $tbl_lp_item SET
3917
                                     previous_item_id = $id
3918
                                     WHERE c_id = ".$course_id." AND id = $next_next";
3919
                        Database::query($sql_upd2);
3920
                    }
3921
                    $display = $display +1;
3922
                }
3923
                break;
3924
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
3925
                return false;
3926
        }
3927
        return $display;
3928
    }
3929
3930
    /**
3931
     * Move a learnpath up (display_order)
3932
     * @param	integer	$lp_id Learnpath ID
3933
     */
3934
    public static function move_up($lp_id)
3935
    {
3936
        $course_id = api_get_course_int_id();
3937
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
3938
        $sql = "SELECT * FROM $lp_table
3939
                WHERE c_id = ".$course_id."
3940
                ORDER BY display_order";
3941
        $res = Database::query($sql);
3942
        if ($res === false)
3943
            return false;
3944
        $lps = array ();
3945
        $lp_order = array ();
3946
        $num = Database :: num_rows($res);
3947
        // First check the order is correct, globally (might be wrong because
3948
        // of versions < 1.8.4)
3949 View Code Duplication
        if ($num > 0) {
3950
            $i = 1;
3951
            while ($row = Database :: fetch_array($res)) {
3952
                if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
3953
                    $need_fix = true;
3954
                    $sql_u = "UPDATE $lp_table SET display_order = $i
3955
                              WHERE c_id = ".$course_id." AND id = " . $row['id'];
3956
                    Database::query($sql_u);
3957
                }
3958
                $row['display_order'] = $i;
3959
                $lps[$row['id']] = $row;
3960
                $lp_order[$i] = $row['id'];
3961
                $i++;
3962
            }
3963
        }
3964
        if ($num > 1) { // If there's only one element, no need to sort.
3965
            $order = $lps[$lp_id]['display_order'];
3966
            if ($order > 1) { // If it's the first element, no need to move up.
3967
                $sql_u1 = "UPDATE $lp_table SET display_order = $order
3968
                           WHERE c_id = ".$course_id." AND id = " . $lp_order[$order - 1];
3969
                Database::query($sql_u1);
3970
                $sql_u2 = "UPDATE $lp_table SET display_order = " . ($order - 1) . "
3971
                           WHERE c_id = ".$course_id." AND id = " . $lp_id;
3972
                Database::query($sql_u2);
3973
            }
3974
        }
3975
    }
3976
3977
    /**
3978
     * Move a learnpath down (display_order)
3979
     * @param	integer	$lp_id Learnpath ID
3980
     */
3981
    public static function move_down($lp_id)
3982
    {
3983
        $course_id = api_get_course_int_id();
3984
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
3985
        $sql = "SELECT * FROM $lp_table
3986
                WHERE c_id = ".$course_id."
3987
                ORDER BY display_order";
3988
        $res = Database::query($sql);
3989
        if ($res === false) {
3990
            return false;
3991
        }
3992
        $lps = array ();
3993
        $lp_order = array ();
3994
        $num = Database :: num_rows($res);
3995
        $max = 0;
3996
        // First check the order is correct, globally (might be wrong because
3997
        // of versions < 1.8.4).
3998 View Code Duplication
        if ($num > 0) {
3999
            $i = 1;
4000
            while ($row = Database :: fetch_array($res)) {
4001
                $max = $i;
4002
                if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
4003
                    $need_fix = true;
4004
                    $sql_u = "UPDATE $lp_table SET display_order = $i
4005
                              WHERE c_id = ".$course_id." AND id = " . $row['id'];
4006
                    Database::query($sql_u);
4007
                }
4008
                $row['display_order'] = $i;
4009
                $lps[$row['id']] = $row;
4010
                $lp_order[$i] = $row['id'];
4011
                $i++;
4012
            }
4013
        }
4014
        if ($num > 1) { // If there's only one element, no need to sort.
4015
            $order = $lps[$lp_id]['display_order'];
4016
            if ($order < $max) { // If it's the first element, no need to move up.
4017
                $sql_u1 = "UPDATE $lp_table SET display_order = $order
4018
                           WHERE c_id = ".$course_id." AND id = " . $lp_order[$order + 1];
4019
                Database::query($sql_u1);
4020
                $sql_u2 = "UPDATE $lp_table SET display_order = " . ($order + 1) . "
4021
                           WHERE c_id = ".$course_id." AND id = " . $lp_id;
4022
                Database::query($sql_u2);
4023
            }
4024
        }
4025
    }
4026
4027
    /**
4028
     * Updates learnpath attributes to point to the next element
4029
     * The last part is similar to set_current_item but processing the other way around
4030
     */
4031
    public function next()
4032
    {
4033
        if ($this->debug > 0) {
4034
            error_log('New LP - In learnpath::next()', 0);
4035
        }
4036
        $this->last = $this->get_current_item_id();
4037
        $this->items[$this->last]->save(false, $this->prerequisites_match($this->last));
4038
        $this->autocomplete_parents($this->last);
4039
        $new_index = $this->get_next_index();
4040
        if ($this->debug > 2) {
4041
            error_log('New LP - New index: ' . $new_index, 0);
4042
        }
4043
        $this->index = $new_index;
4044
        if ($this->debug > 2) {
4045
            error_log('New LP - Now having orderedlist[' . $new_index . '] = ' . $this->ordered_items[$new_index], 0);
4046
        }
4047
        $this->current = $this->ordered_items[$new_index];
4048
        if ($this->debug > 2) {
4049
            error_log('New LP - new item id is ' . $this->current . '-' . $this->get_current_item_id(), 0);
4050
        }
4051
    }
4052
4053
    /**
4054
     * Open a resource = initialise all local variables relative to this resource. Depending on the child
4055
     * class, this might be redefined to allow several behaviours depending on the document type.
4056
     * @param integer Resource ID
4057
     * @return boolean True on success, false otherwise
4058
     */
4059
    public function open($id)
4060
    {
4061
        if ($this->debug > 0) {
4062
            error_log('New LP - In learnpath::open()', 0);
4063
        }
4064
        // TODO:
4065
        // set the current resource attribute to this resource
4066
        // switch on element type (redefine in child class?)
4067
        // set status for this item to "opened"
4068
        // start timer
4069
        // initialise score
4070
        $this->index = 0; //or = the last item seen (see $this->last)
4071
    }
4072
4073
    /**
4074
     * Check that all prerequisites are fulfilled. Returns true and an
4075
     * empty string on succes, returns false
4076
     * and the prerequisite string on error.
4077
     * This function is based on the rules for aicc_script language as
4078
     * described in the SCORM 1.2 CAM documentation page 108.
4079
     * @param	integer	$itemId Optional item ID. If none given, uses the current open item.
4080
     * @return	boolean	True if prerequisites are matched, false otherwise -
4081
     * Empty string if true returned, prerequisites string otherwise.
4082
     */
4083
    public function prerequisites_match($itemId = null)
4084
    {
4085
        $debug = $this->debug;
4086
        if ($debug > 0) {
4087
            error_log('In learnpath::prerequisites_match()', 0);
4088
        }
4089
4090
        if (empty($itemId)) {
4091
            $itemId = $this->current;
4092
        }
4093
4094
        $currentItem = $this->getItem($itemId);
4095
4096
        if ($currentItem) {
4097
            if ($this->type == 2) {
4098
                // Getting prereq from scorm
4099
                $prereq_string = $this->get_scorm_prereq_string($itemId);
4100
            } else {
4101
                $prereq_string = $currentItem->get_prereq_string();
4102
            }
4103
4104
            if (empty($prereq_string)) {
4105
                if ($debug > 0) {
4106
                    error_log('Found prereq_string is empty return true');
4107
                }
4108
                return true;
4109
            }
4110
            // Clean spaces.
4111
            $prereq_string = str_replace(' ', '', $prereq_string);
4112
            if ($debug > 0) {
4113
                error_log('Found prereq_string: ' . $prereq_string, 0);
4114
            }
4115
            // Now send to the parse_prereq() function that will check this component's prerequisites.
4116
            $result = $currentItem->parse_prereq(
4117
                $prereq_string,
4118
                $this->items,
4119
                $this->refs_list,
4120
                $this->get_user_id()
4121
            );
4122
4123
            if ($result === false) {
4124
                $this->set_error_msg($currentItem->prereq_alert);
4125
            }
4126
        } else {
4127
            $result = true;
4128
            if ($debug > 1) {
4129
                error_log('$this->items[' . $itemId . '] was not an object', 0);
4130
            }
4131
        }
4132
4133
        if ($debug > 1) {
4134
            error_log('End of prerequisites_match(). Error message is now ' . $this->error, 0);
4135
        }
4136
        return $result;
4137
    }
4138
4139
    /**
4140
     * Updates learnpath attributes to point to the previous element
4141
     * The last part is similar to set_current_item but processing the other way around
4142
     */
4143
    public function previous()
4144
    {
4145
        if ($this->debug > 0) {
4146
            error_log('New LP - In learnpath::previous()', 0);
4147
        }
4148
        $this->last = $this->get_current_item_id();
4149
        $this->items[$this->last]->save(false, $this->prerequisites_match($this->last));
4150
        $this->autocomplete_parents($this->last);
4151
        $new_index = $this->get_previous_index();
4152
        $this->index = $new_index;
4153
        $this->current = $this->ordered_items[$new_index];
4154
    }
4155
4156
    /**
4157
     * Publishes a learnpath. This basically means show or hide the learnpath
4158
     * to normal users.
4159
     * Can be used as abstract
4160
     * @param	integer	Learnpath ID
4161
     * @param	string	New visibility
4162
     */
4163
    public static function toggle_visibility($lp_id, $set_visibility = 1)
4164
    {
4165
        $action = 'visible';
4166
        if ($set_visibility != 1) {
4167
            $action = 'invisible';
4168
            self::toggle_publish($lp_id, 'i');
4169
        }
4170
4171
        return api_item_property_update(
4172
            api_get_course_info(),
4173
            TOOL_LEARNPATH,
4174
            $lp_id,
4175
            $action,
4176
            api_get_user_id()
4177
        );
4178
    }
4179
4180
    /**
4181
     * Publishes a learnpath. This basically means show or hide the learnpath
4182
     * on the course homepage
4183
     * Can be used as abstract
4184
     * @param	integer	$lp_id Learnpath id
4185
     * @param	string	$set_visibility New visibility (v/i - visible/invisible)
4186
     * @return bool
4187
     */
4188
    public static function toggle_publish($lp_id, $set_visibility = 'v')
4189
    {
4190
        $course_id = api_get_course_int_id();
4191
        $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
4192
        $lp_id = intval($lp_id);
4193
        $sql = "SELECT * FROM $tbl_lp
4194
                WHERE c_id = ".$course_id." AND id = $lp_id";
4195
        $result = Database::query($sql);
4196
        if (Database::num_rows($result)) {
4197
            $row = Database :: fetch_array($result);
4198
            $name = domesticate($row['name']);
4199
            if ($set_visibility == 'i') {
4200
                $s = $name . " " . get_lang('LearnpathNotPublished');
4201
                $dialogBox = $s;
4202
                $v = 0;
4203
            }
4204
            if ($set_visibility == 'v') {
4205
                $s = $name . " " . get_lang('LearnpathPublished');
4206
                $dialogBox = $s;
4207
                $v = 1;
4208
            }
4209
        } else {
4210
            return false;
4211
        }
4212
4213
        $session_id = api_get_session_id();
4214
        $session_condition = api_get_session_condition($session_id);
4215
4216
        $tbl_tool = Database :: get_course_table(TABLE_TOOL_LIST);
4217
        $link = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
4218
        $sql = "SELECT * FROM $tbl_tool
4219
                WHERE
4220
                    c_id = ".$course_id." AND
4221
                    link='$link' and
4222
                    image='scormbuilder.gif' and
4223
                    link LIKE '$link%'
4224
                    $session_condition
4225
                ";
4226
        $result = Database::query($sql);
4227
        $num = Database :: num_rows($result);
4228
        if ($set_visibility == 'i' && $num > 0) {
4229
            $sql = "DELETE FROM $tbl_tool
4230
                    WHERE c_id = ".$course_id." AND (link='$link' and image='scormbuilder.gif' $session_condition)";
4231
            Database::query($sql);
4232
4233
        } elseif ($set_visibility == 'v' && $num == 0) {
4234
            $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
4235
            	    ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
4236
            Database::query($sql);
4237
4238
            $insertId = Database::insert_id();
4239
            if ($insertId) {
4240
                $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
4241
                Database::query($sql);
4242
            }
4243
        } elseif ($set_visibility == 'v' && $num > 0) {
4244
            $sql = "UPDATE $tbl_tool SET
4245
                        c_id = $course_id,
4246
                        name = '$name',
4247
                        link = '$link',
4248
                        image = 'scormbuilder.gif',
4249
                        visibility = '$v',
4250
                        admin = '0',
4251
                        address = 'pastillegris.gif',
4252
                        added_tool = 0,
4253
                        session_id = $session_id
4254
            	    WHERE
4255
            	        c_id = ".$course_id." AND
4256
            	        (link='$link' and image='scormbuilder.gif' $session_condition)
4257
                    ";
4258
            Database::query($sql);
4259
        } else {
4260
            // Parameter and database incompatible, do nothing, exit.
4261
            return false;
4262
        }
4263
4264
    }
4265
4266
    /**
4267
     * Restart the whole learnpath. Return the URL of the first element.
4268
     * Make sure the results are saved with anoter method. This method should probably be
4269
     * redefined in children classes.
4270
     * To use a similar method  statically, use the create_new_attempt() method
4271
     * @return string URL to load in the viewer
4272
     */
4273
    public function restart()
4274
    {
4275
        if ($this->debug > 0) {
4276
            error_log('New LP - In learnpath::restart()', 0);
4277
        }
4278
        // TODO
4279
        // Call autosave method to save the current progress.
4280
        //$this->index = 0;
4281
        if (api_is_invitee()) {
4282
            return false;
4283
        }
4284
        $session_id = api_get_session_id();
4285
        $course_id = api_get_course_int_id();
4286
        $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW);
4287
        $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
4288
                VALUES ($course_id, " . $this->lp_id . "," . $this->get_user_id() . "," . ($this->attempt + 1) . ", $session_id)";
4289
        if ($this->debug > 2) {
4290
            error_log('New LP - Inserting new lp_view for restart: ' . $sql, 0);
4291
        }
4292
        $res = Database::query($sql);
4293
        $view_id = Database::insert_id();
4294
4295
        if ($view_id) {
4296
4297
            $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
4298
            Database::query($sql);
4299
4300
            $this->lp_view_id = $view_id;
4301
            $this->attempt = $this->attempt + 1;
4302
        } else {
4303
            $this->error = 'Could not insert into item_view table...';
4304
            return false;
4305
        }
4306
        $this->autocomplete_parents($this->current);
4307
        foreach ($this->items as $index => $dummy) {
4308
            $this->items[$index]->restart();
4309
            $this->items[$index]->set_lp_view($this->lp_view_id);
4310
        }
4311
        $this->first();
4312
4313
        return true;
4314
    }
4315
4316
    /**
4317
     * Saves the current item
4318
     * @return	boolean
4319
     */
4320
    public function save_current()
4321
    {
4322
        if ($this->debug > 0) {
4323
            error_log('learnpath::save_current()', 0);
4324
        }
4325
        // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
4326
        // on $ordered_items[] but not sure it's always safe to use with $items[]).
4327
        if ($this->debug > 2) {
4328
            error_log('New LP - save_current() saving item ' . $this->current, 0);
4329
        }
4330
        if ($this->debug > 2) {
4331
            error_log('' . print_r($this->items, true), 0);
4332
        }
4333
        if (isset($this->items[$this->current]) &&
4334
            is_object($this->items[$this->current])
4335
        ) {
4336
            $res = $this->items[$this->current]->save(false, $this->prerequisites_match($this->current));
4337
            $this->autocomplete_parents($this->current);
4338
            $status = $this->items[$this->current]->get_status();
4339
            $this->update_queue[$this->current] = $status;
4340
            return $res;
4341
        }
4342
        return false;
4343
    }
4344
4345
    /**
4346
     * Saves the given item
4347
     * @param	integer	$item_id. Optional (will take from $_REQUEST if null)
0 ignored issues
show
Documentation introduced by
There is no parameter named $item_id.. Did you maybe mean $item_id?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
4348
     * @param	boolean	$from_outside Save from url params (true) or from current attributes (false). Optional. Defaults to true
4349
     * @return	boolean
4350
     */
4351
    public function save_item($item_id = null, $from_outside = true)
4352
    {
4353
        $debug = $this->debug;
4354
        if ($debug) {
4355
            error_log('In learnpath::save_item(' . $item_id . ',' . intval($from_outside). ')', 0);
4356
        }
4357
        // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
4358
        // on $ordered_items[] but not sure it's always safe to use with $items[]).
4359
        if (empty($item_id)) {
4360
            $item_id = intval($_REQUEST['id']);
4361
        }
4362
        if (empty($item_id)) {
4363
            $item_id = $this->get_current_item_id();
4364
        }
4365
        if (isset($this->items[$item_id]) && is_object($this->items[$item_id])) {
4366
            if ($debug) {
4367
                error_log('Object exists');
4368
            }
4369
4370
            // Saving the item.
4371
            $res = $this->items[$item_id]->save(
4372
                $from_outside,
4373
                $this->prerequisites_match($item_id)
4374
            );
4375
4376
            if ($debug) {
4377
                error_log('update_queue before:');
4378
                error_log(print_r($this->update_queue,1));
4379
            }
4380
            $this->autocomplete_parents($item_id);
4381
4382
            $status = $this->items[$item_id]->get_status();
4383
            $this->update_queue[$item_id] = $status;
4384
4385
            if ($debug) {
4386
                error_log('get_status(): ' . $status);
4387
                error_log('update_queue after:');
4388
                error_log(print_r($this->update_queue,1));
4389
            }
4390
            return $res;
4391
        }
4392
        return false;
4393
    }
4394
4395
    /**
4396
     * Saves the last item seen's ID only in case
4397
     */
4398
    public function save_last()
4399
    {
4400
        $course_id = api_get_course_int_id();
4401
        if ($this->debug > 0) {
4402
            error_log('New LP - In learnpath::save_last()', 0);
4403
        }
4404
        $session_condition = api_get_session_condition(api_get_session_id(), true, false);
4405
        $table = Database :: get_course_table(TABLE_LP_VIEW);
4406
4407
        if (isset($this->current) && !api_is_invitee()) {
4408
            if ($this->debug > 2) {
4409
                error_log('New LP - Saving current item (' . $this->current . ') for later review', 0);
4410
            }
4411
            $sql = "UPDATE $table SET
4412
                        last_item = " . intval($this->get_current_item_id()). "
4413
                    WHERE
4414
                        c_id = $course_id AND
4415
                        lp_id = " . $this->get_id() . " AND
4416
                        user_id = " . $this->get_user_id()." ".$session_condition;
4417
4418
            if ($this->debug > 2) {
4419
                error_log('New LP - Saving last item seen : ' . $sql, 0);
4420
            }
4421
            Database::query($sql);
4422
        }
4423
4424
        if (!api_is_invitee()) {
4425
            // Save progress.
4426
            list($progress, $text) = $this->get_progress_bar_text('%');
0 ignored issues
show
Unused Code introduced by
The assignment to $text 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...
4427
            if ($progress >= 0 && $progress <= 100) {
4428
                $progress = (int) $progress;
4429
                $sql = "UPDATE $table SET
4430
                            progress = $progress
4431
                        WHERE
4432
                            c_id = ".$course_id." AND
4433
                            lp_id = " . $this->get_id() . " AND
4434
                            user_id = " . $this->get_user_id()." ".$session_condition;
4435
                // Ignore errors as some tables might not have the progress field just yet.
4436
                Database::query($sql);
4437
                $this->progress_db = $progress;
0 ignored issues
show
Documentation Bug introduced by
The property $progress_db was declared of type string, but $progress is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
4438
            }
4439
        }
4440
    }
4441
4442
    /**
4443
     * Sets the current item ID (checks if valid and authorized first)
4444
     * @param	integer	$item_id New item ID. If not given or not authorized, defaults to current
4445
     */
4446
    public function set_current_item($item_id = null)
4447
    {
4448
        if ($this->debug > 0) {
4449
            error_log('New LP - In learnpath::set_current_item(' . $item_id . ')', 0);
4450
        }
4451
        if (empty ($item_id)) {
4452
            if ($this->debug > 2) {
4453
                error_log('New LP - No new current item given, ignore...', 0);
4454
            }
4455
            // Do nothing.
4456
        } else {
4457
            if ($this->debug > 2) {
4458
                error_log('New LP - New current item given is ' . $item_id . '...', 0);
4459
            }
4460
            if (is_numeric($item_id)) {
4461
                $item_id = intval($item_id);
4462
                // TODO: Check in database here.
4463
                $this->last = $this->current;
4464
                $this->current = $item_id;
4465
                // TODO: Update $this->index as well.
4466
                foreach ($this->ordered_items as $index => $item) {
4467
                    if ($item == $this->current) {
4468
                        $this->index = $index;
4469
                        break;
4470
                    }
4471
                }
4472 View Code Duplication
                if ($this->debug > 2) {
4473
                    error_log('New LP - set_current_item(' . $item_id . ') done. Index is now : ' . $this->index, 0);
4474
                }
4475
            } else {
4476
                error_log('New LP - set_current_item(' . $item_id . ') failed. Not a numeric value: ', 0);
4477
            }
4478
        }
4479
    }
4480
4481
    /**
4482
     * Sets the encoding
4483
     * @param	string	New encoding
4484
     * TODO (as of Chamilo 1.8.8): Check in the future whether this method is needed.
4485
     */
4486
    public function set_encoding($enc = 'UTF-8')
4487
    {
4488
        if ($this->debug > 0) {
4489
            error_log('New LP - In learnpath::set_encoding()', 0);
4490
        }
4491
4492
        $course_id = api_get_course_int_id();
4493
        $enc = api_refine_encoding_id($enc);
4494
        if (empty($enc)) {
4495
            $enc = api_get_system_encoding();
4496
        }
4497
        if (api_is_encoding_supported($enc)) {
0 ignored issues
show
Bug introduced by
It seems like $enc defined by api_refine_encoding_id($enc) on line 4493 can also be of type array; however, api_is_encoding_supported() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4498
            $lp = $this->get_id();
4499
            if ($lp != 0) {
4500
                $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
4501
                $sql = "UPDATE $tbl_lp SET default_encoding = '$enc' WHERE c_id = ".$course_id." AND id = " . $lp;
4502
                $res = Database::query($sql);
4503
                return $res;
4504
            }
4505
        }
4506
        return false;
4507
    }
4508
4509
    /**
4510
     * Sets the JS lib setting in the database directly.
4511
     * This is the JavaScript library file this lp needs to load on startup
4512
     * @param	string	Proximity setting
4513
     * @return  boolean True on update success. False otherwise.
4514
     */
4515 View Code Duplication
    public function set_jslib($lib = '')
4516
    {
4517
        if ($this->debug > 0) {
4518
            error_log('New LP - In learnpath::set_jslib()', 0);
4519
        }
4520
        $lp = $this->get_id();
4521
        $course_id = api_get_course_int_id();
4522
4523
        if ($lp != 0) {
4524
            $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
4525
            $sql = "UPDATE $tbl_lp SET js_lib = '$lib' WHERE c_id = ".$course_id." AND id = " . $lp;
4526
            $res = Database::query($sql);
4527
            return $res;
4528
        } else {
4529
            return false;
4530
        }
4531
    }
4532
4533
    /**
4534
     * Sets the name of the LP maker (publisher) (and save)
4535
     * @param	string	Optional string giving the new content_maker of this learnpath
4536
     * @return  boolean True
4537
     */
4538 View Code Duplication
    public function set_maker($name = '')
4539
    {
4540
        if ($this->debug > 0) {
4541
            error_log('New LP - In learnpath::set_maker()', 0);
4542
        }
4543
        if (empty ($name))
4544
            return false;
4545
        $this->maker = $name;
4546
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4547
        $course_id = api_get_course_int_id();
4548
        $lp_id = $this->get_id();
4549
        $sql = "UPDATE $lp_table SET
4550
                content_maker = '" . Database::escape_string($this->maker) . "'
4551
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4552
        if ($this->debug > 2) {
4553
            error_log('New LP - lp updated with new content_maker : ' . $this->maker, 0);
4554
        }
4555
        Database::query($sql);
4556
        return true;
4557
    }
4558
4559
    /**
4560
     * Sets the name of the current learnpath (and save)
4561
     * @param	string	$name Optional string giving the new name of this learnpath
4562
     * @return  boolean True/False
4563
     */
4564
    public function set_name($name = null)
4565
    {
4566
        if ($this->debug > 0) {
4567
            error_log('New LP - In learnpath::set_name()', 0);
4568
        }
4569
        if (empty($name)) {
4570
            return false;
4571
        }
4572
        $this->name = Database::escape_string($name);
4573
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4574
        $lp_id = $this->get_id();
4575
        $course_id = $this->course_info['real_id'];
4576
        $sql = "UPDATE $lp_table SET
4577
                name = '" . Database::escape_string($this->name). "'
4578
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4579
        if ($this->debug > 2) {
4580
            error_log('New LP - lp updated with new name : ' . $this->name, 0);
4581
        }
4582
        $result = Database::query($sql);
4583
        // If the lp is visible on the homepage, change his name there.
4584
        if (Database::affected_rows($result)) {
4585
            $session_id = api_get_session_id();
4586
            $session_condition = api_get_session_condition($session_id);
4587
            $tbl_tool = Database :: get_course_table(TABLE_TOOL_LIST);
4588
            $link = 'newscorm/lp_controller.php?action=view&lp_id=' . $lp_id.'&id_session='.$session_id;
4589
            $sql = "UPDATE $tbl_tool SET name = '$this->name'
4590
            	    WHERE
4591
            	        c_id = $course_id AND
4592
            	        (link='$link' AND image='scormbuilder.gif' $session_condition)";
4593
            Database::query($sql);
4594
            return true;
4595
        } else {
4596
            return false;
4597
        }
4598
    }
4599
4600
    /**
4601
     * Set index specified prefix terms for all items in this path
4602
     * @param   string  Comma-separated list of terms
4603
     * @param   char Xapian term prefix
4604
     * @return  boolean False on error, true otherwise
4605
     */
4606
    public function set_terms_by_prefix($terms_string, $prefix)
4607
    {
4608
        $course_id = api_get_course_int_id();
4609
        if (api_get_setting('search_enabled') !== 'true')
4610
            return false;
4611
4612
        if (!extension_loaded('xapian')) {
4613
            return false;
4614
        }
4615
4616
        $terms_string = trim($terms_string);
4617
        $terms = explode(',', $terms_string);
4618
        array_walk($terms, 'trim_value');
4619
4620
        $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
4621
4622
        // Don't do anything if no change, verify only at DB, not the search engine.
4623 View Code Duplication
        if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0))
4624
            return false;
4625
4626
        require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
4627
        require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
4628
        require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
4629
        require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
4630
4631
        $items_table = Database :: get_course_table(TABLE_LP_ITEM);
4632
        // TODO: Make query secure agains XSS : use member attr instead of post var.
4633
        $lp_id = intval($_POST['lp_id']);
4634
        $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
4635
        $result = Database::query($sql);
4636
        $di = new ChamiloIndexer();
4637
4638
        while ($lp_item = Database :: fetch_array($result)) {
4639
            // Get search_did.
4640
            $tbl_se_ref = Database :: get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
4641
            $sql = 'SELECT * FROM %s
4642
                    WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
4643
                    LIMIT 1';
4644
            $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
4645
4646
            //echo $sql; echo '<br>';
4647
            $res = Database::query($sql);
4648
            if (Database::num_rows($res) > 0) {
4649
                $se_ref = Database :: fetch_array($res);
4650
4651
                // Compare terms.
4652
                $doc = $di->get_document($se_ref['search_did']);
4653
                $xapian_terms = xapian_get_doc_terms($doc, $prefix);
4654
                $xterms = array();
4655
                foreach ($xapian_terms as $xapian_term) {
0 ignored issues
show
Bug introduced by
The expression $xapian_terms of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
4656
                    $xterms[] = substr($xapian_term['name'], 1);
4657
                }
4658
4659
                $dterms = $terms;
4660
4661
                $missing_terms = array_diff($dterms, $xterms);
4662
                $deprecated_terms = array_diff($xterms, $dterms);
4663
4664
                // Save it to search engine.
4665
                foreach ($missing_terms as $term) {
4666
                    $doc->add_term($prefix . $term, 1);
4667
                }
4668
                foreach ($deprecated_terms as $term) {
4669
                    $doc->remove_term($prefix . $term);
4670
                }
4671
                $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
4672
                $di->getDb()->flush();
4673
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
4674
                //@todo What we should do here?
4675
            }
4676
        }
4677
        return true;
4678
    }
4679
4680
    /**
4681
     * Sets the theme of the LP (local/remote) (and save)
4682
     * @param	string	Optional string giving the new theme of this learnpath
4683
     * @return   bool    Returns true if theme name is not empty
4684
     */
4685 View Code Duplication
    public function set_theme($name = '')
4686
    {
4687
        $course_id = api_get_course_int_id();
4688
        if ($this->debug > 0) {
4689
            error_log('New LP - In learnpath::set_theme()', 0);
4690
        }
4691
        $this->theme = $name;
4692
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4693
        $lp_id = $this->get_id();
4694
        $sql = "UPDATE $lp_table SET theme = '" . Database::escape_string($this->theme). "'
4695
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4696
        if ($this->debug > 2) {
4697
            error_log('New LP - lp updated with new theme : ' . $this->theme, 0);
4698
        }
4699
        Database::query($sql);
4700
4701
        return true;
4702
    }
4703
4704
    /**
4705
     * Sets the image of an LP (and save)
4706
     * @param	 string	Optional string giving the new image of this learnpath
4707
     * @return bool   Returns true if theme name is not empty
4708
     */
4709 View Code Duplication
    public function set_preview_image($name = '')
4710
    {
4711
        $course_id = api_get_course_int_id();
4712
        if ($this->debug > 0) {
4713
            error_log('New LP - In learnpath::set_preview_image()', 0);
4714
        }
4715
4716
        $this->preview_image = $name;
4717
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4718
        $lp_id = $this->get_id();
4719
        $sql = "UPDATE $lp_table SET
4720
                preview_image = '" . Database::escape_string($this->preview_image). "'
4721
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4722
        if ($this->debug > 2) {
4723
            error_log('New LP - lp updated with new preview image : ' . $this->preview_image, 0);
4724
        }
4725
        Database::query($sql);
4726
        return true;
4727
    }
4728
4729
    /**
4730
     * Sets the author of a LP (and save)
4731
     * @param	string	Optional string giving the new author of this learnpath
4732
     * @return   bool    Returns true if author's name is not empty
4733
     */
4734 View Code Duplication
    public function set_author($name = '')
4735
    {
4736
        $course_id = api_get_course_int_id();
4737
        if ($this->debug > 0) {
4738
            error_log('New LP - In learnpath::set_author()', 0);
4739
        }
4740
        $this->author = $name;
4741
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4742
        $lp_id = $this->get_id();
4743
        $sql = "UPDATE $lp_table SET author = '" . Database::escape_string($name). "'
4744
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4745
        if ($this->debug > 2) {
4746
            error_log('New LP - lp updated with new preview author : ' . $this->author, 0);
4747
        }
4748
        Database::query($sql);
4749
4750
        return true;
4751
    }
4752
4753
    /**
4754
     * Sets the hide_toc_frame parameter of a LP (and save)
4755
     * @param	int	1 if frame is hidden 0 then else
4756
     * @return   bool    Returns true if author's name is not empty
4757
     */
4758 View Code Duplication
    public function set_hide_toc_frame($hide)
4759
    {
4760
        $course_id = api_get_course_int_id();
4761
        if ($this->debug > 0) {
4762
            error_log('New LP - In learnpath::set_hide_toc_frame()', 0);
4763
        }
4764
        if (intval($hide) == $hide){
4765
            $this->hide_toc_frame = $hide;
4766
            $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4767
            $lp_id = $this->get_id();
4768
            $sql = "UPDATE $lp_table SET
4769
                    hide_toc_frame = '" . $this->hide_toc_frame . "'
4770
                    WHERE c_id = ".$course_id." AND id = '$lp_id'";
4771
            if ($this->debug > 2) {
4772
                error_log('New LP - lp updated with new preview hide_toc_frame : ' . $this->author, 0);
4773
            }
4774
            Database::query($sql);
4775
4776
            return true;
4777
        } else {
4778
            return false;
4779
        }
4780
    }
4781
4782
    /**
4783
     * Sets the prerequisite of a LP (and save)
4784
     * @param	int		integer giving the new prerequisite of this learnpath
4785
     * @return 	bool 	returns true if prerequisite is not empty
4786
     */
4787 View Code Duplication
    public function set_prerequisite($prerequisite)
4788
    {
4789
        $course_id = api_get_course_int_id();
4790
        if ($this->debug > 0) {
4791
            error_log('New LP - In learnpath::set_prerequisite()', 0);
4792
        }
4793
        $this->prerequisite = intval($prerequisite);
4794
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4795
        $lp_id = $this->get_id();
4796
        $sql = "UPDATE $lp_table SET prerequisite = '".$this->prerequisite."'
4797
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4798
        if ($this->debug > 2) {
4799
            error_log('New LP - lp updated with new preview requisite : ' . $this->requisite, 0);
4800
        }
4801
        Database::query($sql);
4802
        return true;
4803
    }
4804
4805
    /**
4806
     * Sets the location/proximity of the LP (local/remote) (and save)
4807
     * @param	string	Optional string giving the new location of this learnpath
4808
     * @return  boolean True on success / False on error
4809
     */
4810
    public function set_proximity($name = '')
4811
    {
4812
        $course_id = api_get_course_int_id();
4813
        if ($this->debug > 0) {
4814
            error_log('New LP - In learnpath::set_proximity()', 0);
4815
        }
4816
        if (empty ($name))
4817
            return false;
4818
4819
        $this->proximity = $name;
4820
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4821
        $lp_id = $this->get_id();
4822
        $sql = "UPDATE $lp_table SET
4823
                    content_local = '" . Database::escape_string($name) . "'
4824
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4825
        if ($this->debug > 2) {
4826
            error_log('New LP - lp updated with new proximity : ' . $this->proximity, 0);
4827
        }
4828
        Database::query($sql);
4829
        return true;
4830
    }
4831
4832
    /**
4833
     * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item
4834
     * @param	integer	DB ID of the item
4835
     */
4836
    public function set_previous_item($id)
4837
    {
4838
        if ($this->debug > 0) {
4839
            error_log('New LP - In learnpath::set_previous_item()', 0);
4840
        }
4841
        $this->last = $id;
4842
    }
4843
4844
    /**
4845
     * Sets use_max_score
4846
     * @param   string  $use_max_score Optional string giving the new location of this learnpath
4847
     * @return  boolean True on success / False on error
4848
     */
4849
    public function set_use_max_score($use_max_score = 1)
4850
    {
4851
        $course_id = api_get_course_int_id();
4852
        if ($this->debug > 0) {
4853
            error_log('New LP - In learnpath::set_use_max_score()', 0);
4854
        }
4855
        $use_max_score = intval($use_max_score);
4856
        $this->use_max_score = $use_max_score;
4857
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4858
        $lp_id = $this->get_id();
4859
        $sql = "UPDATE $lp_table SET
4860
                    use_max_score = '" . $this->use_max_score . "'
4861
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4862
4863
        if ($this->debug > 2) {
4864
            error_log('New LP - lp updated with new use_max_score : ' . $this->use_max_score, 0);
4865
        }
4866
        Database::query($sql);
4867
4868
        return true;
4869
    }
4870
4871
    /**
4872
     * Sets and saves the expired_on date
4873
     * @param   string  $expired_on Optional string giving the new author of this learnpath
4874
     * @return   bool    Returns true if author's name is not empty
4875
     */
4876 View Code Duplication
    public function set_expired_on($expired_on)
4877
    {
4878
        $course_id = api_get_course_int_id();
4879
        if ($this->debug > 0) {
4880
            error_log('New LP - In learnpath::set_expired_on()', 0);
4881
        }
4882
4883
        if (!empty($expired_on)) {
4884
            $this->expired_on = api_get_utc_datetime($expired_on);
4885
        } else {
4886
            $this->expired_on = '';
4887
        }
4888
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4889
        $lp_id = $this->get_id();
4890
        $sql = "UPDATE $lp_table SET
4891
                expired_on = '" . Database::escape_string($this->expired_on) . "'
4892
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4893
        if ($this->debug > 2) {
4894
            error_log('New LP - lp updated with new expired_on : ' . $this->expired_on, 0);
4895
        }
4896
        Database::query($sql);
4897
4898
        return true;
4899
    }
4900
4901
    /**
4902
     * Sets and saves the publicated_on date
4903
     * @param   string  $publicated_on Optional string giving the new author of this learnpath
4904
     * @return   bool    Returns true if author's name is not empty
4905
     */
4906 View Code Duplication
    public function set_publicated_on($publicated_on)
4907
    {
4908
        $course_id = api_get_course_int_id();
4909
        if ($this->debug > 0) {
4910
            error_log('New LP - In learnpath::set_expired_on()', 0);
4911
        }
4912
        if (!empty($publicated_on)) {
4913
            $this->publicated_on = api_get_utc_datetime($publicated_on);
4914
        } else {
4915
            $this->publicated_on = '';
4916
        }
4917
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4918
        $lp_id = $this->get_id();
4919
        $sql = "UPDATE $lp_table SET
4920
                publicated_on = '" . Database::escape_string($this->publicated_on) . "'
4921
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4922
        if ($this->debug > 2) {
4923
            error_log('New LP - lp updated with new publicated_on : ' . $this->publicated_on, 0);
4924
        }
4925
        Database::query($sql);
4926
4927
        return true;
4928
    }
4929
4930
    /**
4931
     * Sets and saves the expired_on date
4932
     * @return   bool    Returns true if author's name is not empty
4933
     */
4934 View Code Duplication
    public function set_modified_on()
4935
    {
4936
        $course_id = api_get_course_int_id();
4937
        if ($this->debug > 0) {
4938
            error_log('New LP - In learnpath::set_expired_on()', 0);
4939
        }
4940
        $this->modified_on = api_get_utc_datetime();
4941
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
4942
        $lp_id = $this->get_id();
4943
        $sql = "UPDATE $lp_table SET modified_on = '" . $this->modified_on . "'
4944
                WHERE c_id = ".$course_id." AND id = '$lp_id'";
4945
        if ($this->debug > 2) {
4946
            error_log('New LP - lp updated with new expired_on : ' . $this->modified_on, 0);
4947
        }
4948
        Database::query($sql);
4949
        return true;
4950
    }
4951
4952
    /**
4953
     * Sets the object's error message
4954
     * @param	string	Error message. If empty, reinits the error string
4955
     * @return 	void
4956
     */
4957
    public function set_error_msg($error = '')
4958
    {
4959
        if ($this->debug > 0) {
4960
            error_log('New LP - In learnpath::set_error_msg()', 0);
4961
        }
4962
        if (empty ($error)) {
4963
            $this->error = '';
4964
        } else {
4965
            $this->error .= $error;
4966
        }
4967
    }
4968
4969
    /**
4970
     * Launches the current item if not 'sco'
4971
     * (starts timer and make sure there is a record ready in the DB)
4972
     * @param  boolean  $allow_new_attempt Whether to allow a new attempt or not
4973
     * @return boolean
4974
     */
4975
    public function start_current_item($allow_new_attempt = false)
4976
    {
4977
        if ($this->debug > 0) {
4978
            error_log('New LP - In learnpath::start_current_item()', 0);
4979
        }
4980
        if ($this->current != 0 && is_object($this->items[$this->current])) {
4981
            $type = $this->get_type();
4982
            $item_type = $this->items[$this->current]->get_type();
4983
            if (($type == 2 && $item_type != 'sco') ||
4984
                ($type == 3 && $item_type != 'au') ||
4985
                ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
4986
            ) {
4987
                $this->items[$this->current]->open($allow_new_attempt);
4988
                $this->autocomplete_parents($this->current);
4989
                $prereq_check = $this->prerequisites_match($this->current);
4990
                $this->items[$this->current]->save(false, $prereq_check);
4991
                //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
4992
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
4993
                // If sco, then it is supposed to have been updated by some other call.
4994
            }
4995
            if ($item_type == 'sco') {
4996
                $this->items[$this->current]->restart();
4997
            }
4998
        }
4999
        if ($this->debug > 0) {
5000
            error_log('New LP - End of learnpath::start_current_item()', 0);
5001
        }
5002
        return true;
5003
    }
5004
5005
    /**
5006
     * Stops the processing and counters for the old item (as held in $this->last)
5007
     * @return boolean  True/False
5008
     */
5009
    public function stop_previous_item()
5010
    {
5011
        if ($this->debug > 0) {
5012
            error_log('New LP - In learnpath::stop_previous_item()', 0);
5013
        }
5014
5015
        if ($this->last != 0 && $this->last != $this->current && is_object($this->items[$this->last])) {
5016
            if ($this->debug > 2) {
5017
                error_log('New LP - In learnpath::stop_previous_item() - ' . $this->last . ' is object', 0);
5018
            }
5019
            switch ($this->get_type()) {
5020 View Code Duplication
                case '3' :
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
5021
                    if ($this->items[$this->last]->get_type() != 'au') {
5022
                        if ($this->debug > 2) {
5023
                            error_log('New LP - In learnpath::stop_previous_item() - ' . $this->last . ' in lp_type 3 is <> au', 0);
5024
                        }
5025
                        $this->items[$this->last]->close();
5026
                        //$this->autocomplete_parents($this->last);
5027
                        //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
5028
                    } else {
5029
                        if ($this->debug > 2) {
5030
                            error_log('New LP - In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals', 0);
5031
                        }
5032
                    }
5033 View Code Duplication
                case '2' :
5034
                    if ($this->items[$this->last]->get_type() != 'sco') {
5035
                        if ($this->debug > 2) {
5036
                            error_log('New LP - In learnpath::stop_previous_item() - ' . $this->last . ' in lp_type 2 is <> sco', 0);
5037
                        }
5038
                        $this->items[$this->last]->close();
5039
                        //$this->autocomplete_parents($this->last);
5040
                        //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
5041
                    } else {
5042
                        if ($this->debug > 2) {
5043
                            error_log('New LP - In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals', 0);
5044
                        }
5045
                    }
5046
                    break;
5047
                case '1' :
5048
                default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
5049
                    if ($this->debug > 2) {
5050
                        error_log('New LP - In learnpath::stop_previous_item() - ' . $this->last . ' in lp_type 1 is asset', 0);
5051
                    }
5052
                    $this->items[$this->last]->close();
5053
                    break;
5054
            }
5055
        } else {
5056
            if ($this->debug > 2) {
5057
                error_log('New LP - In learnpath::stop_previous_item() - No previous element found, ignoring...', 0);
5058
            }
5059
            return false;
5060
        }
5061
        return true;
5062
    }
5063
5064
    /**
5065
     * Updates the default view mode from fullscreen to embedded and inversely
5066
     * @return	string The current default view mode ('fullscreen' or 'embedded')
5067
     */
5068
    public function update_default_view_mode()
5069
    {
5070
        $course_id = api_get_course_int_id();
5071
        if ($this->debug > 0) {
5072
            error_log('New LP - In learnpath::update_default_view_mode()', 0);
5073
        }
5074
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5075
        $sql = "SELECT * FROM $lp_table
5076
                WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5077
        $res = Database::query($sql);
5078
        if (Database :: num_rows($res) > 0) {
5079
            $row = Database :: fetch_array($res);
5080
            $default_view_mode = $row['default_view_mod'];
5081
            $view_mode = $default_view_mode;
5082
            switch ($default_view_mode) {
5083
                case 'fullscreen': // default with popup
5084
                    $view_mode = 'embedded';
5085
                    break;
5086
                case 'embedded': // default view with left menu
5087
                    $view_mode = 'embedframe';
5088
                    break;
5089
                case 'embedframe': //folded menu
5090
                    $view_mode = 'impress';
5091
                    break;
5092
                case 'impress':
5093
                    $view_mode = 'fullscreen';
5094
                    break;
5095
            }
5096
            $sql = "UPDATE $lp_table SET default_view_mod = '$view_mode'
5097
                    WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5098
            Database::query($sql);
5099
            $this->mode = $view_mode;
5100
5101
            return $view_mode;
5102
        } else {
5103
            if ($this->debug > 2) {
5104
                error_log('New LP - Problem in update_default_view() - could not find LP ' . $this->get_id() . ' in DB', 0);
5105
            }
5106
        }
5107
        return -1;
5108
    }
5109
5110
    /**
5111
     * Updates the default behaviour about auto-commiting SCORM updates
5112
     * @return	boolean	True if auto-commit has been set to 'on', false otherwise
5113
     */
5114
    public function update_default_scorm_commit()
5115
    {
5116
        $course_id = api_get_course_int_id();
5117
        if ($this->debug > 0) {
5118
            error_log('New LP - In learnpath::update_default_scorm_commit()', 0);
5119
        }
5120
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5121
        $sql = "SELECT * FROM $lp_table
5122
                WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5123
        $res = Database::query($sql);
5124
        if (Database :: num_rows($res) > 0) {
5125
            $row = Database :: fetch_array($res);
5126
            $force = $row['force_commit'];
5127
            if ($force == 1) {
5128
                $force = 0;
5129
                $force_return = false;
5130
            } elseif ($force == 0) {
5131
                $force = 1;
5132
                $force_return = true;
5133
            }
5134
            $sql = "UPDATE $lp_table SET force_commit = $force
5135
                    WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5136
            Database::query($sql);
5137
            $this->force_commit = $force_return;
5138
5139
            return $force_return;
5140
        } else {
5141
            if ($this->debug > 2) {
5142
                error_log('New LP - Problem in update_default_scorm_commit() - could not find LP ' . $this->get_id() . ' in DB', 0);
5143
            }
5144
        }
5145
        return -1;
5146
    }
5147
5148
    /**
5149
     * Updates the order of learning paths (goes through all of them by order and fills the gaps)
5150
     * @return	bool	True on success, false on failure
5151
     */
5152
    public function update_display_order()
5153
    {
5154
        $course_id = api_get_course_int_id();
5155
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5156
5157
        $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." ORDER BY display_order";
5158
        $res = Database::query($sql);
5159
        if ($res === false)
5160
            return false;
5161
5162
        $num = Database :: num_rows($res);
5163
        // First check the order is correct, globally (might be wrong because
5164
        // of versions < 1.8.4).
5165
        if ($num > 0) {
5166
            $i = 1;
5167
            while ($row = Database :: fetch_array($res)) {
5168
                if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
5169
                    $need_fix = true;
5170
                    $sql = "UPDATE $lp_table SET display_order = $i
5171
                            WHERE c_id = ".$course_id." AND id = " . $row['id'];
5172
                    Database::query($sql);
5173
                }
5174
                $i++;
5175
            }
5176
        }
5177
        return true;
5178
    }
5179
5180
    /**
5181
     * Updates the "prevent_reinit" value that enables control on reinitialising items on second view
5182
     * @return	boolean	True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
5183
     */
5184 View Code Duplication
    public function update_reinit()
5185
    {
5186
        $course_id = api_get_course_int_id();
5187
        if ($this->debug > 0) {
5188
            error_log('New LP - In learnpath::update_reinit()', 0);
5189
        }
5190
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5191
        $sql = "SELECT * FROM $lp_table
5192
                WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5193
        $res = Database::query($sql);
5194
        if (Database :: num_rows($res) > 0) {
5195
            $row = Database :: fetch_array($res);
5196
            $force = $row['prevent_reinit'];
5197
            if ($force == 1) {
5198
                $force = 0;
5199
            } elseif ($force == 0) {
5200
                $force = 1;
5201
            }
5202
            $sql = "UPDATE $lp_table SET prevent_reinit = $force
5203
                    WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5204
            Database::query($sql);
5205
            $this->prevent_reinit = $force;
5206
            return $force;
5207
        } else {
5208
            if ($this->debug > 2) {
5209
                error_log('New LP - Problem in update_reinit() - could not find LP ' . $this->get_id() . ' in DB', 0);
5210
            }
5211
        }
5212
        return -1;
5213
    }
5214
5215
    /**
5216
     * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag
5217
     *
5218
     * @return string 'single', 'multi' or 'seriousgame'
5219
     * @author ndiechburg <[email protected]>
5220
     **/
5221
    public function get_attempt_mode()
5222
    {
5223
        //Set default value for seriousgame_mode
5224
        if (!isset($this->seriousgame_mode)) {
5225
            $this->seriousgame_mode=0;
5226
        }
5227
        // Set default value for prevent_reinit
5228
        if (!isset($this->prevent_reinit)) {
5229
            $this->prevent_reinit =1;
5230
        }
5231
        if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
5232
            return 'seriousgame';
5233
        }
5234
        if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
5235
            return 'single';
5236
        }
5237
        if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
5238
            return 'multiple';
5239
        }
5240
        return 'single';
5241
    }
5242
5243
    /**
5244
     * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags
5245
     *
5246
     * @param string 'seriousgame', 'single' or 'multiple'
5247
     * @return boolean
5248
     * @author ndiechburg <[email protected]>
5249
     **/
5250
    public function set_attempt_mode($mode)
5251
    {
5252
        $course_id = api_get_course_int_id();
5253
        switch ($mode) {
5254
            case 'seriousgame' :
5255
                $sg_mode = 1;
5256
                $prevent_reinit = 1;
5257
                break;
5258
            case 'single' :
5259
                $sg_mode = 0;
5260
                $prevent_reinit = 1;
5261
                break;
5262
            case 'multiple' :
5263
                $sg_mode = 0;
5264
                $prevent_reinit = 0;
5265
                break;
5266
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
5267
                $sg_mode = 0;
5268
                $prevent_reinit = 0;
5269
                break;
5270
        }
5271
        $this->prevent_reinit = $prevent_reinit;
5272
        $this->seriousgame_mode = $sg_mode;
5273
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5274
        $sql = "UPDATE $lp_table SET
5275
                prevent_reinit = $prevent_reinit ,
5276
                seriousgame_mode = $sg_mode
5277
                WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5278
        $res = Database::query($sql);
5279
        if ($res) {
5280
            return true;
5281
        } else {
5282
            return false;
5283
        }
5284
    }
5285
5286
    /**
5287
     * Switch between multiple attempt, single attempt or serious_game mode (only for scorm)
5288
     *
5289
     * @return boolean
5290
     * @author ndiechburg <[email protected]>
5291
     **/
5292
    public function switch_attempt_mode()
5293
    {
5294
        if ($this->debug > 0) {
5295
            error_log('New LP - In learnpath::switch_attempt_mode()', 0);
5296
        }
5297
        $mode = $this->get_attempt_mode();
5298
        switch ($mode) {
5299
            case 'single' :
5300
                $next_mode = 'multiple';
5301
                break;
5302
            case 'multiple' :
5303
                $next_mode = 'seriousgame';
5304
                break;
5305
            case 'seriousgame' :
5306
                $next_mode = 'single';
5307
                break;
5308
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
5309
                $next_mode = 'single';
5310
                break;
5311
        }
5312
        $this->set_attempt_mode($next_mode);
5313
    }
5314
5315
    /**
5316
     * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
5317
     * but possibility to do again a completed item.
5318
     *
5319
     * @return boolean true if seriousgame_mode has been set to 1, false otherwise
5320
     * @author ndiechburg <[email protected]>
5321
     **/
5322 View Code Duplication
    public function set_seriousgame_mode()
5323
    {
5324
        $course_id = api_get_course_int_id();
5325
        if ($this->debug > 0) {
5326
            error_log('New LP - In learnpath::set_seriousgame_mode()', 0);
5327
        }
5328
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5329
        $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5330
        $res = Database::query($sql);
5331
        if (Database :: num_rows($res) > 0) {
5332
            $row = Database :: fetch_array($res);
5333
            $force = $row['seriousgame_mode'];
5334
            if ($force == 1) {
5335
                $force = 0;
5336
            } elseif ($force == 0) {
5337
                $force = 1;
5338
            }
5339
            $sql = "UPDATE $lp_table SET seriousgame_mode = $force
5340
			        WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5341
            Database::query($sql);
5342
            $this->seriousgame_mode = $force;
5343
            return $force;
5344
        } else {
5345
            if ($this->debug > 2) {
5346
                error_log('New LP - Problem in set_seriousgame_mode() - could not find LP ' . $this->get_id() . ' in DB', 0);
5347
            }
5348
        }
5349
        return -1;
5350
    }
5351
5352
    /**
5353
     * Updates the "scorm_debug" value that shows or hide the debug window
5354
     * @return	boolean	True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
5355
     */
5356 View Code Duplication
    public function update_scorm_debug()
5357
    {
5358
        $course_id = api_get_course_int_id();
5359
        if ($this->debug > 0) {
5360
            error_log('New LP - In learnpath::update_scorm_debug()', 0);
5361
        }
5362
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
5363
        $sql = "SELECT * FROM $lp_table
5364
                WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5365
        $res = Database::query($sql);
5366
        if (Database :: num_rows($res) > 0) {
5367
            $row = Database :: fetch_array($res);
5368
            $force = $row['debug'];
5369
            if ($force == 1) {
5370
                $force = 0;
5371
            } elseif ($force == 0) {
5372
                $force = 1;
5373
            }
5374
            $sql = "UPDATE $lp_table SET debug = $force
5375
                    WHERE c_id = ".$course_id." AND id = " . $this->get_id();
5376
            $res = Database::query($sql);
5377
            $this->scorm_debug = $force;
5378
            return $force;
5379
        } else {
5380
            if ($this->debug > 2) {
5381
                error_log('New LP - Problem in update_scorm_debug() - could not find LP ' . $this->get_id() . ' in DB', 0);
5382
            }
5383
        }
5384
        return -1;
5385
    }
5386
5387
    /**
5388
     * Function that makes a call to the function sort_tree_array and create_tree_array
5389
     * @author Kevin Van Den Haute
5390
     * @param  array
5391
     */
5392
    public function tree_array($array)
5393
    {
5394
        if ($this->debug > 1) {
5395
            error_log('New LP - In learnpath::tree_array()', 0);
5396
        }
5397
        $array = $this->sort_tree_array($array);
5398
        $this->create_tree_array($array);
5399
    }
5400
5401
    /**
5402
     * Creates an array with the elements of the learning path tree in it
5403
     *
5404
     * @author Kevin Van Den Haute
5405
     * @param array $array
5406
     * @param int $parent
5407
     * @param int $depth
5408
     * @param array $tmp
5409
     */
5410
    public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = array ())
5411
    {
5412
        if ($this->debug > 1) {
5413
            error_log('New LP - In learnpath::create_tree_array())', 0);
5414
        }
5415
5416
        if (is_array($array)) {
5417
            for ($i = 0; $i < count($array); $i++) {
5418
                if ($array[$i]['parent_item_id'] == $parent) {
5419
                    if (!in_array($array[$i]['parent_item_id'], $tmp)) {
5420
                        $tmp[] = $array[$i]['parent_item_id'];
5421
                        $depth++;
5422
                    }
5423
                    $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
5424
                    $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
5425
                    $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
5426
5427
                    $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
5428
                    $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
5429
                    $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
5430
                    $this->arrMenu[] = array(
5431
                        'id' => $array[$i]['id'],
5432
                        'ref' => $ref,
5433
                        'item_type' => $array[$i]['item_type'],
5434
                        'title' => $array[$i]['title'],
5435
                        'path' => $path,
5436
                        'description' => $array[$i]['description'],
5437
                        'parent_item_id' => $array[$i]['parent_item_id'],
5438
                        'previous_item_id' => $array[$i]['previous_item_id'],
5439
                        'next_item_id' => $array[$i]['next_item_id'],
5440
                        'min_score' => $array[$i]['min_score'],
5441
                        'max_score' => $array[$i]['max_score'],
5442
                        'mastery_score' => $array[$i]['mastery_score'],
5443
                        'display_order' => $array[$i]['display_order'],
5444
                        'prerequisite' => $preq,
5445
                        'depth' => $depth,
5446
                        'audio' => $audio,
5447
                        'prerequisite_min_score' => $prerequisiteMinScore,
5448
                        'prerequisite_max_score' => $prerequisiteMaxScore
5449
                    );
5450
5451
                    $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
5452
                }
5453
            }
5454
        }
5455
    }
5456
5457
    /**
5458
     * Sorts a multi dimensional array by parent id and display order
5459
     * @author Kevin Van Den Haute
5460
     *
5461
     * @param array $array (array with al the learning path items in it)
5462
     *
5463
     * @return array
5464
     */
5465
    public function sort_tree_array($array) {
5466
        foreach ($array as $key => $row) {
5467
            $parent[$key] = $row['parent_item_id'];
5468
            $position[$key] = $row['display_order'];
5469
        }
5470
5471
        if (count($array) > 0)
5472
            array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
5473
5474
        return $array;
5475
    }
5476
5477
    /**
5478
     * Function that creates a html list of learning path items so that we can add audio files to them
5479
     * @author Kevin Van Den Haute
5480
     * @param int $lp_id
0 ignored issues
show
Bug introduced by
There is no parameter named $lp_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...
5481
     * @return string
5482
     */
5483
    public function overview()
5484
    {
5485
        if ($this->debug > 0) {
5486
            error_log('New LP - In learnpath::overview()', 0);
5487
        }
5488
5489
        $_SESSION['gradebook'] = isset($_GET['gradebook']) ? Security :: remove_XSS($_GET['gradebook']) : null;
5490
        $return = '';
5491
5492
        $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
5493
5494
        // we need to start a form when we want to update all the mp3 files
5495
        if ($update_audio == 'true') {
5496
            $return .= '<form action="' . api_get_self() . '?cidReq=' . Security :: remove_XSS($_GET['cidReq']) . '&updateaudio=' . Security :: remove_XSS($_GET['updateaudio']) .'&action=' . Security :: remove_XSS($_GET['action']) . '&lp_id=' . $_SESSION['oLP']->lp_id . '" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
5497
        }
5498
        $return .= '<div id="message"></div>';
5499
        if (count($this->items) == 0) {
5500
            $return .= Display::display_normal_message(get_lang('YouShouldAddItemsBeforeAttachAudio'));
5501
        } else {
5502
            $return_audio = '<table class="data_table">';
5503
            $return_audio .= '<tr>';
5504
            $return_audio .= '<th width="40%">' . get_lang('Title') . '</th>';
5505
            $return_audio .= '<th>' . get_lang('Audio') . '</th>';
5506
            $return_audio .= '</tr>';
5507
5508
            if ($update_audio != 'true') {
5509
                $return .= '<div class="col-md-12">';
5510
                $return .= self::return_new_tree($update_audio);
5511
                $return .='</div>';
5512
                $return .= Display::div(Display::url(get_lang('Save'), '#', array('id'=>'listSubmit', 'class'=>'btn btn-primary')), array('style'=>'float:left; margin-top:15px;width:100%'));
5513
            } else {
5514
                $return_audio .= self::return_new_tree($update_audio);
5515
                $return .= $return_audio.'</table>';
5516
            }
5517
5518
            // We need to close the form when we are updating the mp3 files.
5519
            if ($update_audio == 'true') {
5520
                $return .= '<div class="footer-audio">';
5521
                $return .= Display::button('save_audio','<em class="fa fa-file-audio-o"></em> '. get_lang('SaveAudioAndOrganization'),array('class'=>'btn btn-primary','type'=>'submit'));
5522
                $return .= '</div>';
5523
                //$return .= '<div><button class="btn btn-primary" type="submit" name="save_audio" id="save_audio">' . get_lang('SaveAudioAndOrganization') . '</button></div>'; // TODO: What kind of language variable is this?
5524
            }
5525
        }
5526
5527
        // We need to close the form when we are updating the mp3 files.
5528
        if ($update_audio == 'true' && count($this->arrMenu) != 0) {
5529
            $return .= '</form>';
5530
        }
5531
        return $return;
5532
    }
5533
5534
    /**
5535
     * @param string string $update_audio
5536
     * @param bool $drop_element_here
5537
     * @return string
5538
     */
5539
    public function return_new_tree($update_audio = 'false', $drop_element_here = false)
5540
    {
5541
        $return = '';
5542
        $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
5543
5544
        $course_id = api_get_course_int_id();
5545
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
5546
5547
        $sql = "SELECT * FROM $tbl_lp_item
5548
                WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
5549
5550
        $result = Database::query($sql);
5551
        $arrLP = array();
5552
        while ($row = Database :: fetch_array($result)) {
5553
5554
            $arrLP[] = array(
5555
                'id' => $row['id'],
5556
                'item_type' => $row['item_type'],
5557
                'title' => Security :: remove_XSS($row['title']),
5558
                'path' => $row['path'],
5559
                'description' => Security::remove_XSS($row['description']),
5560
                'parent_item_id' => $row['parent_item_id'],
5561
                'previous_item_id' => $row['previous_item_id'],
5562
                'next_item_id' => $row['next_item_id'],
5563
                'max_score' => $row['max_score'],
5564
                'min_score' => $row['min_score'],
5565
                'mastery_score' => $row['mastery_score'],
5566
                'prerequisite' => $row['prerequisite'],
5567
                'display_order' => $row['display_order'],
5568
                'audio' => $row['audio'],
5569
                'prerequisite_max_score' => $row['prerequisite_max_score'],
5570
                'prerequisite_min_score' => $row['prerequisite_min_score']
5571
            );
5572
        }
5573
5574
        $this->tree_array($arrLP);
5575
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
5576
        unset ($this->arrMenu);
5577
        $default_data = null;
5578
        $default_content = null;
5579
5580
        $elements = array();
5581
        $return_audio = null;
5582
5583
        for ($i = 0; $i < count($arrLP); $i++) {
5584
            $title = $arrLP[$i]['title'];
5585
5586
            $title_cut = cut($arrLP[$i]['title'], 25);
5587
5588
            // Link for the documents
5589
            if ($arrLP[$i]['item_type'] == 'document') {
5590
                $url = api_get_self() . '?'.api_get_cidreq().'&action=view_item&mode=preview_document&id=' . $arrLP[$i]['id'] . '&lp_id=' . $this->lp_id;
5591
                $title_cut = Display::url(
5592
                    $title_cut,
5593
                    $url,
5594
                    array(
5595
                        'class' => 'ajax moved',
5596
                        'data-title' => $title_cut
5597
                    )
5598
                );
5599
            }
5600
5601
            // Detect if type is FINAL_ITEM to set path_id to SESSION
5602
            if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
5603
                $_SESSION['pathItem'] = $arrLP[$i]['path'];
5604
            }
5605
5606
            if (($i % 2) == 0) {
5607
                $oddClass = 'row_odd';
5608
            } else {
5609
                $oddClass = 'row_even';
5610
            }
5611
            $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'] .'" class="' . $oddClass . '">';
5612
5613
            $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
5614
5615
            if (file_exists('../img/lp_' . $icon_name . '.png')) {
5616
                $icon = Display::return_icon('lp_'.$icon_name.'.png');
5617
            } else {
5618
                if (file_exists('../img/lp_' . $icon_name . '.gif')) {
5619
                    $icon = Display::return_icon('lp_'.$icon_name.'.gif');
5620
                } else {
5621
                    if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
5622
                        $icon = Display::return_icon('certificate.png');
5623
                    } else {
5624
                        $icon = Display::return_icon('folder_document.gif');
5625
                    }
5626
                }
5627
            }
5628
5629
            // The audio column.
5630
            $return_audio  .= '<td align="left" style="padding-left:10px;">';
5631
            $audio = '';
5632
5633
            if (!$update_audio || $update_audio <> 'true') {
5634
                if (!empty($arrLP[$i]['audio'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
5635
                } else {
5636
                    $audio .= '';
5637
                }
5638
            } else {
5639
                $types = self::getChapterTypes();
5640
                if (!in_array($arrLP[$i]['item_type'], $types)) {
5641
                    $audio .= '<input type="file" name="mp3file' . $arrLP[$i]['id'] . '" id="mp3file" />';
5642
                    if (!empty ($arrLP[$i]['audio'])) {
5643
                        $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
5644
                        <input type="checkbox" name="removemp3' . $arrLP[$i]['id'] . '" id="checkbox' . $arrLP[$i]['id'] . '" />' . get_lang('RemoveAudio');
5645
                    }
5646
                }
5647
            }
5648
            $return_audio .= Display::span($icon.' '.$title).Display::tag('td', $audio, array('style'=>''));
5649
            $return_audio .= '</td>';
5650
            $move_icon = '';
5651
            $move_item_icon = '';
5652
            $edit_icon = '';
5653
            $delete_icon = '';
5654
            $audio_icon = '';
5655
            $prerequisities_icon = '';
5656
            $forumIcon = '';
5657
5658
            if ($is_allowed_to_edit) {
5659
                if (!$update_audio || $update_audio <> 'true') {
5660 View Code Duplication
                    if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
5661
                        $move_icon .= '<a class="moved" href="#">';
5662
                        $move_icon .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
5663
                        $move_icon .= '</a>';
5664
                    }
5665
                }
5666
5667
                // No edit for this item types
5668
                if (!in_array($arrLP[$i]['item_type'], array('sco', 'asset', 'final_item'))) {
5669
                    if (!in_array($arrLP[$i]['item_type'], array('dokeos_chapter', 'dokeos_module'))) {
5670
                        $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&view=build&id=' . $arrLP[$i]['id'] . '&lp_id=' . $this->lp_id . '&path_item=' . $arrLP[$i]['path'] . '" class="btn btn-default">';
5671
                        $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(), ICON_SIZE_TINY);
5672
                        $edit_icon .= '</a>';
5673
5674
                        if (
5675
                        !in_array($arrLP[$i]['item_type'], ['forum', 'thread'])
5676
                        ) {
5677
                            if (
5678
                            $this->items[$arrLP[$i]['id']]->getForumThread(
5679
                                $this->course_int_id,
5680
                                $this->lp_session_id
5681
                            )
5682
                            ) {
5683
                                $forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
5684
                                    'action' => 'dissociate_forum',
5685
                                    'id' => $arrLP[$i]['id'],
5686
                                    'lp_id' => $this->lp_id
5687
                                ]);
5688
                                $forumIcon = Display::url(
5689
                                    Display::return_icon('forum.png', get_lang('DissociateForumToLPItem'), [], ICON_SIZE_TINY),
5690
                                    $forumIconUrl,
5691
                                    ['class' => 'btn btn-default lp-btn-dissociate-forum']
5692
                                );
5693
                            } else {
5694
                                $forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
5695
                                    'action' => 'create_forum',
5696
                                    'id' => $arrLP[$i]['id'],
5697
                                    'lp_id' => $this->lp_id
5698
                                ]);
5699
                                $forumIcon = Display::url(
5700
                                    Display::return_icon('forum.png', get_lang('AssociateForumToLPItem'), [], ICON_SIZE_TINY),
5701
                                    $forumIconUrl,
5702
                                    ['class' => "btn btn-default lp-btn-associate-forum"]
5703
                                );
5704
                            }
5705
                        }
5706
                    } else {
5707
                        $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id=' . $arrLP[$i]['id'] . '&lp_id=' . $this->lp_id . '&path_item=' . $arrLP[$i]['path'] . '" class="btn btn-default">';
5708
                        $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(), ICON_SIZE_TINY);
5709
                        $edit_icon .= '</a>';
5710
                    }
5711
                }
5712
5713
                $delete_icon .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete_item&id=' . $arrLP[$i]['id'] . '&lp_id=' . $this->lp_id . '" onclick="return confirmation(\'' . addslashes($title) . '\');" class="btn btn-default">';
5714
                $delete_icon .= Display::return_icon('delete.png', get_lang('LearnpathDeleteModule'), array(), ICON_SIZE_TINY);
5715
                $delete_icon .= '</a>';
5716
5717
                $url = api_get_self() . '?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'] .'&lp_id='.$this->lp_id;
5718
5719
                if (!in_array($arrLP[$i]['item_type'], array('dokeos_chapter', 'dokeos_module', 'dir'))) {
5720
                    $prerequisities_icon = Display::url(Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_TINY), $url.'&action=edit_item_prereq', ['class' => 'btn btn-default']);
5721
                    $move_item_icon = Display::url(Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_TINY), $url.'&action=move_item', ['class' => 'btn btn-default']);
5722
                    $audio_icon = Display::url(Display::return_icon('audio.png', get_lang('UplUpload'), array(), ICON_SIZE_TINY), $url.'&action=add_audio', ['class' => 'btn btn-default']);
5723
                }
5724
            }
5725
            if ($update_audio != 'true') {
5726
                $row = $move_icon . ' ' . $icon .
5727
                    Display::span($title_cut) .
5728
                    Display::tag(
5729
                        'div',
5730
                        "<div class=\"btn-group btn-group-xs\">$audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
5731
                        array('class'=>'btn-toolbar button_actions')
5732
                    );
5733
            } else {
5734
                $row = Display::span($title.$icon).Display::span($audio, array('class'=>'button_actions'));
5735
            }
5736
            $parent_id = $arrLP[$i]['parent_item_id'];
5737
5738
            $default_data[$arrLP[$i]['id']] = $row;
5739
            $default_content[$arrLP[$i]['id']] = $arrLP[$i];
5740
5741
            if (empty($parent_id)) {
5742
                $elements[$arrLP[$i]['id']]['data'] = $row;
5743
                $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
5744
            } else {
5745
                $parent_arrays = array();
5746
                if ($arrLP[$i]['depth'] > 1) {
5747
                    //Getting list of parents
5748
                    for($j = 0; $j < $arrLP[$i]['depth']; $j++) {
5749
                        foreach($arrLP as $item) {
5750
                            if ($item['id'] == $parent_id) {
5751
                                if ($item['parent_item_id'] == 0) {
5752
                                    $parent_id = $item['id'];
5753
                                    break;
5754
                                } else {
5755
                                    $parent_id = $item['parent_item_id'];
5756
                                    if (empty($parent_arrays)) {
5757
                                        $parent_arrays[] = intval($item['id']);
5758
                                    }
5759
                                    $parent_arrays[] = $parent_id;
5760
                                    break;
5761
                                }
5762
                            }
5763
                        }
5764
                    }
5765
                }
5766
5767
                if (!empty($parent_arrays)) {
5768
                    $parent_arrays = array_reverse($parent_arrays);
5769
                    $val = '$elements';
5770
                    $x = 0;
5771
                    foreach($parent_arrays as $item) {
5772
                        if ($x != count($parent_arrays) -1) {
5773
                            $val .= '["'.$item.'"]["children"]';
5774
                        } else {
5775
                            $val .= '["'.$item.'"]["children"]';
5776
                        }
5777
                        $x++;
5778
                    }
5779
                    $val .= "";
5780
                    $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
5781
                    eval($code_str);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
5782
                } else {
5783
                    $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
5784
                    $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
5785
                }
5786
            }
5787
        }
5788
5789
        $list = '<ul id="lp_item_list">';
5790
        $tree = self::print_recursive($elements, $default_data, $default_content);
5791
5792
        if (!empty($tree)) {
5793
            $list .= $tree;
5794
        } else {
5795
            if ($drop_element_here) {
5796
                $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
5797
            }
5798
        }
5799
        $list .= '</ul>';
5800
5801
        //$return .= Display::panel($list, $this->name);
5802
        $return .= Display::panelCollapse($this->name, $list, 'scorm-list', null, 'scorm-list-accordion', 'scorm-list-collapse');
5803
5804
        if ($update_audio == 'true') {
5805
            $return = $return_audio;
5806
        }
5807
5808
        return $return;
5809
    }
5810
5811
    /**
5812
     * @param array $elements
5813
     * @param array $default_data
5814
     * @param array $default_content
5815
     * @return string
5816
     */
5817
    public function print_recursive($elements, $default_data, $default_content)
5818
    {
5819
        $return = '';
5820
        foreach ($elements as $key => $item) {
5821
            if (isset($item['load_data']) || empty($item['data'])) {
5822
                $item['data'] = $default_data[$item['load_data']];
5823
                $item['type'] = $default_content[$item['load_data']]['item_type'];
5824
            }
5825
            $sub_list = '';
5826
            if (isset($item['type']) && $item['type'] == 'dokeos_chapter') {
5827
                $sub_list = Display::tag('li', '', array('class'=>'sub_item empty')); // empty value
5828
            }
5829
            if (empty($item['children'])) {
5830
                $sub_list = Display::tag('ul', $sub_list, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
5831
                $active = null;
5832
                if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
5833
                    $active = 'active';
5834
                }
5835
                $return  .= Display::tag('li', Display::div($item['data'], array('class'=>"item_data $active")).$sub_list, array('id'=>$key, 'class'=>'record li_container'));
5836
            } else {
5837
                //sections
5838
                if (isset($item['children'])) {
5839
                    $data = self::print_recursive($item['children'], $default_data, $default_content);
5840
                }
5841
                $sub_list = Display::tag('ul', $sub_list.$data, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
5842
                $return .= Display::tag('li', Display::div($item['data'], array('class'=>'item_data')).$sub_list, array('id'=>$key, 'class'=>'record li_container'));
5843
            }
5844
        }
5845
5846
        return $return;
5847
    }
5848
5849
    /**
5850
     * This function builds the action menu
5851
     * @param bool $returnContent
5852
     * @return void
5853
     */
5854
    public function build_action_menu($returnContent = false)
5855
    {
5856
        $gradebook = isset($_GET['gradebook']) ? Security :: remove_XSS($_GET['gradebook']) : null;
5857
        $return = '<div class="actions">';
5858
        $return .=  '<a href="lp_controller.php?'.api_get_cidreq().'&gradebook=' . $gradebook . '&action=view&lp_id=' . $_SESSION['oLP']->lp_id . '&isStudentView=true">' . Display :: return_icon('preview_view.png', get_lang('Display'),'',ICON_SIZE_MEDIUM).'</a> ';
5859
        $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=admin_view&lp_id=' . $_SESSION['oLP']->lp_id . '&updateaudio=true">' . Display :: return_icon('upload_audio.png', get_lang('UpdateAllAudioFragments'),'',ICON_SIZE_MEDIUM).'</a>';
5860
        $return .= '<a href="lp_controller.php?'.api_get_cidreq().'&action=edit&lp_id=' . $_SESSION['oLP']->lp_id . '">' . Display :: return_icon('settings.png', get_lang('CourseSettings'),'',ICON_SIZE_MEDIUM).'</a>';
5861
        $buttons = array(
5862
            array(
5863
                'title' => get_lang('SetPrerequisiteForEachItem'),
5864
                'href' => 'lp_controller.php?'.api_get_cidreq().'&action=set_previous_step_as_prerequisite&lp_id=' . $_SESSION['oLP']->lp_id,
5865
            ),
5866
            array(
5867
                'title' => get_lang('ClearAllPrerequisites'),
5868
                'href' => 'lp_controller.php?'.api_get_cidreq().'&action=clear_prerequisites&lp_id=' . $_SESSION['oLP']->lp_id,
5869
            ),
5870
        );
5871
        $return .= Display::group_button(get_lang('PrerequisitesOptions'), $buttons);
5872
        $return .= '</div>';
5873
5874
        if ($returnContent) {
5875
            return $return;
5876
        }
5877
        echo $return;
5878
    }
5879
5880
    /**
5881
     * Creates the default learning path folder
5882
     * @param array $course
5883
     * @param int $creatorId
5884
     *
5885
     * @return bool
5886
     */
5887
    public static function generate_learning_path_folder($course, $creatorId = 0)
5888
    {
5889
        // Creating learning_path folder
5890
        $dir = '/learning_path';
5891
        $filepath = api_get_path(SYS_COURSE_PATH).$course['path'] . '/document';
5892
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5893
5894
        $folder = false;
5895
        if (!is_dir($filepath.'/'.$dir)) {
5896
            $folderData = create_unexisting_directory(
5897
                $course,
5898
                $creatorId,
5899
                api_get_session_id(),
5900
                0,
5901
                0,
5902
                $filepath,
5903
                $dir,
5904
                get_lang('LearningPaths'),
5905
                0
5906
            );
5907
            if (!empty($folderData)) {
5908
                $folder = true;
5909
            }
5910
        } else {
5911
            $folder = true;
5912
        }
5913
5914
        return $folder;
5915
    }
5916
5917
    /**
5918
     * @param array $course
5919
     * @param string $lp_name
5920
     * @param int $creatorId
5921
     *
5922
     * @return array
5923
     */
5924
    public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
5925
    {
5926
        $filepath = '';
5927
        $dir = '/learning_path/';
5928
5929
        if (empty($lp_name)) {
5930
            $lp_name = $this->name;
5931
        }
5932
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5933
5934
        $folder = self::generate_learning_path_folder($course, $creatorId);
5935
        // Creating LP folder
5936
        if ($folder) {
5937
            //Limits title size
5938
            $title = api_substr(api_replace_dangerous_char($lp_name), 0 , 80);
5939
            $dir   = $dir.$title;
5940
            $filepath = api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document';
5941
            if (!is_dir($filepath.'/'.$dir)) {
5942
                $folderData = create_unexisting_directory(
5943
                    $course,
5944
                    $creatorId,
5945
                    0,
5946
                    0,
5947
                    0,
5948
                    $filepath,
5949
                    $dir,
5950
                    $lp_name
5951
                );
5952
                if (!empty($folderData)) {
5953
                    $folder = true;
5954
                }
5955
            } else {
5956
                $folder = true;
5957
            }
5958
            $dir = $dir.'/';
5959
            if ($folder) {
5960
                $filepath = api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document'.$dir;
5961
            }
5962
        }
5963
        $array = array(
5964
            'dir' => $dir,
5965
            'filepath' => $filepath,
5966
            'folder' => $folder
5967
        );
5968
        return $array;
5969
    }
5970
5971
    /**
5972
     * Create a new document //still needs some finetuning
5973
     * @param array $courseInfo
5974
     * @param string $content
5975
     * @param string $title
5976
     * @param string $extension
5977
     * @param int $creatorId creator id
5978
     *
5979
     * @return string
5980
     */
5981
    public function create_document($courseInfo, $content = '', $title = '', $extension = 'html', $creatorId = 0)
5982
    {
5983
        if (!empty($courseInfo)) {
5984
            $course_id = $courseInfo['real_id'];
5985
        } else {
5986
            $course_id = api_get_course_int_id();
5987
        }
5988
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5989
        $sessionId = api_get_session_id();
5990
5991
        global $charset;
5992
        $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
5993
        $dir = isset ($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
5994
        // Please, do not modify this dirname formatting.
5995
        if (strstr($dir, '..')) {
5996
            $dir = '/';
5997
        }
5998
        if (!empty($dir[0]) && $dir[0] == '.') {
5999
            $dir = substr($dir, 1);
6000
        }
6001
        if (!empty($dir[0]) && $dir[0] != '/') {
6002
            $dir = '/' . $dir;
6003
        }
6004
        if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
6005
            $dir .= '/';
6006
        }
6007
        $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document' . $dir;
6008
6009
        if (empty($_POST['dir']) && empty($_GET['dir'])) {
6010
            //Generates folder
6011
            $result = $this->generate_lp_folder($courseInfo, '', $creatorId);
6012
            $dir = $result['dir'];
6013
            $filepath = $result['filepath'];
6014
        }
6015
6016 View Code Duplication
        if (!is_dir($filepath)) {
6017
            $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document/';
6018
            $dir = '/';
6019
        }
6020
6021
        // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
6022
        // is already escaped twice when it gets here.
6023
6024
        $originalTitle = !empty($title) ? $title : $_POST['title'];
6025
        if (!empty($title)) {
6026
            $title = api_replace_dangerous_char(stripslashes($title));
6027
        } else {
6028
            $title = api_replace_dangerous_char(stripslashes($_POST['title']));
6029
        }
6030
6031
        $title = disable_dangerous_file($title);
6032
        $filename = $title;
6033
        $content = !empty($content) ? $content : $_POST['content_lp'];
6034
        $tmp_filename = $filename;
6035
6036
        $i = 0;
6037 View Code Duplication
        while (file_exists($filepath . $tmp_filename . '.'.$extension))
6038
            $tmp_filename = $filename . '_' . ++ $i;
6039
6040
        $filename = $tmp_filename . '.'.$extension;
6041
        if ($extension == 'html') {
6042
            $content = stripslashes($content);
6043
            $content = str_replace(
6044
                api_get_path(WEB_COURSE_PATH),
6045
                api_get_path(REL_PATH).'courses/',
6046
                $content
6047
            );
6048
6049
            // Change the path of mp3 to absolute.
6050
6051
            // The first regexp deals with :// urls.
6052
            $content = preg_replace(
6053
                "|(flashvars=\"file=)([^:/]+)/|",
6054
                "$1".api_get_path(
6055
                    REL_COURSE_PATH
6056
                ).$courseInfo['path'].'/document/',
6057
                $content
6058
            );
6059
            // The second regexp deals with audio/ urls.
6060
            $content = preg_replace(
6061
                "|(flashvars=\"file=)([^/]+)/|",
6062
                "$1".api_get_path(
6063
                    REL_COURSE_PATH
6064
                ).$courseInfo['path'].'/document/$2/',
6065
                $content
6066
            );
6067
            // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
6068
            $content = str_replace(
6069
                '</body>',
6070
                '<style type="text/css">body{}</style></body>',
6071
                $content
6072
            );
6073
        }
6074
6075
        if (!file_exists($filepath . $filename)) {
6076
            if ($fp = @ fopen($filepath . $filename, 'w')) {
6077
                fputs($fp, $content);
6078
                fclose($fp);
6079
6080
                $file_size = filesize($filepath . $filename);
6081
                $save_file_path = $dir.$filename;
6082
6083
                $document_id = add_document(
6084
                    $courseInfo,
6085
                    $save_file_path,
6086
                    'file',
6087
                    $file_size,
6088
                    $tmp_filename,
6089
                    '',
6090
                    0, //readonly
6091
                    true,
6092
                    null,
6093
                    $sessionId,
6094
                    $creatorId
6095
                );
6096
6097
                if ($document_id) {
6098
                    api_item_property_update(
6099
                        $courseInfo,
6100
                        TOOL_DOCUMENT,
6101
                        $document_id,
6102
                        'DocumentAdded',
6103
                        $creatorId,
6104
                        null,
6105
                        null,
6106
                        null,
6107
                        null,
6108
                        $sessionId
6109
                    );
6110
6111
                    $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
6112
                    $new_title = $originalTitle;
6113
6114
                    if ($new_comment || $new_title) {
6115
                        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6116
                        $ct = '';
6117
                        if ($new_comment)
6118
                            $ct .= ", comment='" . Database::escape_string($new_comment). "'";
6119
                        if ($new_title)
6120
                            $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset))."' ";
6121
6122
                        $sql = "UPDATE " . $tbl_doc ." SET " . substr($ct, 1)."
6123
                               WHERE c_id = ".$course_id." AND id = " . $document_id;
6124
                        Database::query($sql);
6125
                    }
6126
                }
6127
                return $document_id;
6128
            }
6129
        }
6130
    }
6131
6132
    /**
6133
     * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'
6134
     * @param 	array $_course array
6135
     * @return 	void
6136
     */
6137
    public function edit_document($_course)
6138
    {
6139
        $course_id = api_get_course_int_id();
6140
        global $_configuration;
6141
        // Please, do not modify this dirname formatting.
6142
        $dir = isset($_GET['dir']) ? $_GET['dir'] : $_POST['dir'];
6143
6144
        if (strstr($dir, '..'))
6145
            $dir = '/';
6146
6147
        if ($dir[0] == '.')
6148
            $dir = substr($dir, 1);
6149
6150
        if ($dir[0] != '/')
6151
            $dir = '/' . $dir;
6152
6153
        if ($dir[strlen($dir) - 1] != '/')
6154
            $dir .= '/';
6155
6156
        $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $dir;
6157
6158 View Code Duplication
        if (!is_dir($filepath)) {
6159
            $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
6160
        }
6161
6162
        $table_doc = Database :: get_course_table(TABLE_DOCUMENT);
6163
        if (isset($_POST['path']) && !empty($_POST['path'])) {
6164
            $document_id = intval($_POST['path']);
6165
            $sql = "SELECT path FROM " . $table_doc . "
6166
                    WHERE c_id = $course_id AND id = " . $document_id;
6167
            $res = Database::query($sql);
6168
            $row = Database :: fetch_array($res);
6169
            $content = stripslashes($_POST['content_lp']);
6170
            $file = $filepath . $row['path'];
6171
6172
            if ($fp = @ fopen($file, 'w')) {
6173
                $content = str_replace(api_get_path(WEB_COURSE_PATH), $_configuration['url_append'] . '/courses/', $content);
6174
6175
                // Change the path of mp3 to absolute.
6176
                // The first regexp deals with :// urls.
6177
                $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content);
6178
                // The second regexp deals with audio/ urls.
6179
                $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/$2/', $content);
6180
                fputs($fp, $content);
6181
                fclose($fp);
6182
6183
                $sql = "UPDATE " . $table_doc ." SET
6184
                            title='".Database::escape_string($_POST['title'])."'
6185
                        WHERE c_id = ".$course_id." AND id = " . $document_id;
6186
                Database::query($sql);
6187
            }
6188
        }
6189
    }
6190
6191
    /**
6192
     * Displays the selected item, with a panel for manipulating the item
6193
     * @param int $item_id
6194
     * @param string $msg
6195
     * @return string
6196
     */
6197
    public function display_item($item_id, $msg = null, $show_actions = true)
6198
    {
6199
        $course_id = api_get_course_int_id();
6200
        $return = '';
6201
        if (is_numeric($item_id)) {
6202
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6203
            $sql = "SELECT lp.* FROM " . $tbl_lp_item . " as lp
6204
                    WHERE c_id = ".$course_id." AND lp.id = " . intval($item_id);
6205
            $result = Database::query($sql);
6206
            while ($row = Database :: fetch_array($result,'ASSOC')) {
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
6207
                $_SESSION['parent_item_id'] = ($row['item_type'] == 'dokeos_chapter' || $row['item_type'] == 'dokeos_module' || $row['item_type'] == 'dir') ? $item_id : 0;
6208
6209
                // Prevents wrong parent selection for document, see Bug#1251.
6210
                if ($row['item_type'] != 'dokeos_chapter' || $row['item_type'] != 'dokeos_module') {
6211
                    $_SESSION['parent_item_id'] = $row['parent_item_id'];
6212
                }
6213
6214
                if ($show_actions) {
6215
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6216
                }
6217
                $return .= '<div style="padding:10px;">';
6218
6219
                if ($msg != '')
6220
                    $return .= $msg;
6221
6222
                $return .= '<h3>'.$row['title'].'</h3>';
6223
                switch ($row['item_type']) {
6224
                    case TOOL_QUIZ:
6225
                        if (!empty($row['path'])) {
6226
                            $exercise = new Exercise();
6227
                            $exercise->read($row['path']);
6228
                            $return .= $exercise->description.'<br />';
6229
                        }
6230
                        break;
6231
                    case TOOL_DOCUMENT:
6232
                        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6233
                        $sql_doc = "SELECT path FROM " . $tbl_doc . "
6234
                                    WHERE c_id = ".$course_id." AND id = " . intval($row['path']);
6235
                        $result = Database::query($sql_doc);
6236
                        $path_file = Database::result($result, 0, 0);
6237
                        $path_parts = pathinfo($path_file);
6238
                        // TODO: Correct the following naive comparisons, also, htm extension is missing.
6239
                        if (in_array($path_parts['extension'], array(
6240
                            'html',
6241
                            'txt',
6242
                            'png',
6243
                            'jpg',
6244
                            'JPG',
6245
                            'jpeg',
6246
                            'JPEG',
6247
                            'gif',
6248
                            'swf'
6249
                        ))) {
6250
                            $return .= $this->display_document($row['path'], true, true);
6251
                        }
6252
                        break;
6253
                }
6254
                $return .= '</div>';
6255
            }
6256
        }
6257
6258
        return $return;
6259
    }
6260
6261
    /**
6262
     * Shows the needed forms for editing a specific item
6263
     * @param int $item_id
6264
     * @return string
6265
     */
6266
    public function display_edit_item($item_id)
6267
    {
6268
        $course_id = api_get_course_int_id();
6269
        $return = '';
6270
        if (is_numeric($item_id)) {
6271
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6272
            $sql = "SELECT * FROM $tbl_lp_item
6273
                    WHERE c_id = ".$course_id." AND id = " . intval($item_id);
6274
            $res = Database::query($sql);
6275
            $row = Database::fetch_array($res);
6276
            switch ($row['item_type']) {
6277
                case 'dokeos_chapter' :
6278
                case 'dir' :
6279
                case 'asset' :
6280 View Code Duplication
                case 'sco' :
6281
                    if (isset ($_GET['view']) && $_GET['view'] == 'build') {
6282
                        $return .= $this->display_manipulate($item_id, $row['item_type']);
6283
                        $return .= $this->display_item_form($row['item_type'], get_lang('EditCurrentChapter') . ' :', 'edit', $item_id, $row);
6284
                    } else {
6285
                        $return .= $this->display_item_small_form($row['item_type'], get_lang('EditCurrentChapter') . ' :', $row);
6286
                    }
6287
                    break;
6288 View Code Duplication
                case TOOL_DOCUMENT :
6289
                    $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6290
                    $sql = "SELECT lp.*, doc.path as dir
6291
                            FROM " . $tbl_lp_item . " as lp
6292
                            LEFT JOIN " . $tbl_doc . " as doc
6293
                            ON doc.id = lp.path
6294
                            WHERE
6295
                                lp.c_id = $course_id AND
6296
                                doc.c_id = $course_id AND
6297
                                lp.id = " . intval($item_id);
6298
                    $res_step = Database::query($sql);
6299
                    $row_step = Database :: fetch_array($res_step, 'ASSOC');
6300
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6301
                    $return .= $this->display_document_form('edit', $item_id, $row_step);
6302
                    break;
6303
                case TOOL_LINK :
6304
                    $link_id = (string) $row['path'];
6305
                    if (ctype_digit($link_id)) {
6306
                        $tbl_link = Database :: get_course_table(TABLE_LINK);
6307
                        $sql_select = 'SELECT url FROM ' . $tbl_link . '
6308
                                       WHERE c_id = '.$course_id.' AND id = ' . intval($link_id);
6309
                        $res_link = Database::query($sql_select);
6310
                        $row_link = Database :: fetch_array($res_link);
6311
                        if (is_array($row_link)) {
6312
                            $row['url'] = $row_link['url'];
6313
                        }
6314
                    }
6315
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6316
                    $return .= $this->display_link_form('edit', $item_id, $row);
6317
                    break;
6318 View Code Duplication
                case TOOL_LP_FINAL_ITEM :
6319
                    $_SESSION['finalItem'] = true;
6320
                    $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6321
                    $sql = "SELECT lp.*, doc.path as dir
6322
                            FROM " . $tbl_lp_item . " as lp
6323
                            LEFT JOIN " . $tbl_doc . " as doc
6324
                            ON doc.id = lp.path
6325
                            WHERE
6326
                                lp.c_id = $course_id AND
6327
                                doc.c_id = $course_id AND
6328
                                lp.id = " . intval($item_id);
6329
                    $res_step = Database::query($sql);
6330
                    $row_step = Database :: fetch_array($res_step, 'ASSOC');
6331
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6332
                    $return .= $this->display_document_form('edit', $item_id, $row_step);
6333
                    break;
6334 View Code Duplication
                case 'dokeos_module' :
6335
                    if (isset ($_GET['view']) && $_GET['view'] == 'build') {
6336
                        $return .= $this->display_manipulate($item_id, $row['item_type']);
6337
                        $return .= $this->display_item_form($row['item_type'], get_lang('EditCurrentModule') . ' :', 'edit', $item_id, $row);
6338
                    } else {
6339
                        $return .= $this->display_item_small_form($row['item_type'], get_lang('EditCurrentModule') . ' :', $row);
6340
                    }
6341
                    break;
6342 View Code Duplication
                case TOOL_QUIZ :
6343
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6344
                    $return .= $this->display_quiz_form('edit', $item_id, $row);
6345
                    break;
6346
                case TOOL_HOTPOTATOES :
6347
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6348
                    $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
6349
                    break;
6350 View Code Duplication
                case TOOL_STUDENTPUBLICATION :
6351
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6352
                    $return .= $this->display_student_publication_form('edit', $item_id, $row);
6353
                    break;
6354
                case TOOL_FORUM :
6355
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6356
                    $return .= $this->display_forum_form('edit', $item_id, $row);
6357
                    break;
6358 View Code Duplication
                case TOOL_THREAD :
6359
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6360
                    $return .= $this->display_thread_form('edit', $item_id, $row);
6361
                    break;
6362
            }
6363
        }
6364
6365
        return $return;
6366
    }
6367
6368
    /**
6369
     * Function that displays a list with al the resources that
6370
     * could be added to the learning path
6371
     * @return string
6372
     */
6373
    public function display_resources()
6374
    {
6375
        $course_code = api_get_course_id();
6376
6377
        // Get all the docs.
6378
        $documents = $this->get_documents(true);
6379
6380
        // Get all the exercises.
6381
        $exercises = $this->get_exercises();
6382
6383
        // Get all the links.
6384
        $links = $this->get_links();
6385
6386
        // Get all the student publications.
6387
        $works = $this->get_student_publications();
6388
6389
        // Get all the forums.
6390
        $forums = $this->get_forums(null, $course_code);
6391
6392
        // Get the final item form (see BT#11048) .
6393
        $finish = $this->getFinalItemForm();
6394
6395
        $headers = array(
6396
            Display::return_icon('folder_document.png', get_lang('Documents'), array(), ICON_SIZE_BIG),
6397
            Display::return_icon('quiz.png',  get_lang('Quiz'), array(), ICON_SIZE_BIG),
6398
            Display::return_icon('links.png', get_lang('Links'), array(), ICON_SIZE_BIG),
6399
            Display::return_icon('works.png', get_lang('Works'), array(), ICON_SIZE_BIG),
6400
            Display::return_icon('forum.png', get_lang('Forums'), array(), ICON_SIZE_BIG),
6401
            Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), array(), ICON_SIZE_BIG),
6402
            Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
6403
        );
6404
6405
        echo Display::display_normal_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'));
6406
        $chapter = $_SESSION['oLP']->display_item_form('chapter', get_lang('EnterDataNewChapter'), 'add_item');
6407
        echo Display::tabs(
6408
            $headers,
6409
            array($documents, $exercises, $links, $works, $forums, $chapter, $finish), 'resource_tab'
6410
        );
6411
6412
        return true;
6413
    }
6414
6415
    /**
6416
     * Returns the extension of a document
6417
     * @param string filename
6418
     * @return string Extension (part after the last dot)
6419
     */
6420
    public function get_extension($filename)
6421
    {
6422
        $explode = explode('.', $filename);
6423
        return $explode[count($explode) - 1];
6424
    }
6425
6426
    /**
6427
     * Displays a document by id
6428
     *
6429
     * @param int $id
6430
     * @return string
6431
     */
6432
    public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
6433
    {
6434
        $_course = api_get_course_info();
6435
        $course_id = api_get_course_int_id();
6436
        $return = '';
6437
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6438
        $sql_doc = "SELECT * FROM " . $tbl_doc . "
6439
                    WHERE c_id = ".$course_id." AND id = " . $id;
6440
        $res_doc = Database::query($sql_doc);
6441
        $row_doc = Database :: fetch_array($res_doc);
6442
6443
        // TODO: Add a path filter.
6444
        if ($iframe) {
6445
            $return .= '<iframe id="learnpath_preview_frame" frameborder="0" height="400" width="100%" scrolling="auto" src="' . api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/document' . str_replace('%2F', '/', urlencode($row_doc['path'])) . '?' . api_get_cidreq() . '"></iframe>';
6446
        } else {
6447
            $return .= file_get_contents(api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $row_doc['path']);
6448
        }
6449
6450
        return $return;
6451
    }
6452
6453
    /**
6454
     * Return HTML form to add/edit a quiz
6455
     * @param	string	Action (add/edit)
6456
     * @param	integer	Item ID if already exists
6457
     * @param	mixed	Extra information (quiz ID if integer)
6458
     * @return	string	HTML form
6459
     */
6460
    public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
6461
    {
6462
        $course_id = api_get_course_int_id();
6463
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6464
        $tbl_quiz = Database :: get_course_table(TABLE_QUIZ_TEST);
6465
6466 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6467
            $item_title = $extra_info['title'];
6468
            $item_description = $extra_info['description'];
6469
        } elseif (is_numeric($extra_info)) {
6470
            $sql = "SELECT title, description
6471
                    FROM " . $tbl_quiz . "
6472
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
6473
6474
            $result = Database::query($sql);
6475
            $row = Database::fetch_array($result);
6476
            $item_title = $row['title'];
6477
            $item_description = $row['description'];
6478
        } else {
6479
            $item_title = '';
6480
            $item_description = '';
6481
        }
6482
        $item_title			= Security::remove_XSS($item_title);
6483
        $item_description 	= Security::remove_XSS($item_description);
6484
6485 View Code Duplication
        if ($id != 0 && is_array($extra_info))
6486
            $parent = $extra_info['parent_item_id'];
6487
        else
6488
            $parent = 0;
6489
6490
        $sql = "SELECT * FROM " . $tbl_lp_item . "
6491
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
6492
6493
        $result = Database::query($sql);
6494
        $arrLP = array ();
6495 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6496
            $arrLP[] = array (
6497
                'id' => $row['id'],
6498
                'item_type' => $row['item_type'],
6499
                'title' => $row['title'],
6500
                'path' => $row['path'],
6501
                'description' => $row['description'],
6502
                'parent_item_id' => $row['parent_item_id'],
6503
                'previous_item_id' => $row['previous_item_id'],
6504
                'next_item_id' => $row['next_item_id'],
6505
                'display_order' => $row['display_order'],
6506
                'max_score' => $row['max_score'],
6507
                'min_score' => $row['min_score'],
6508
                'mastery_score' => $row['mastery_score'],
6509
                'prerequisite' => $row['prerequisite'],
6510
                'max_time_allowed' => $row['max_time_allowed']
6511
            );
6512
        }
6513
6514
        $this->tree_array($arrLP);
6515
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
6516
        unset ($this->arrMenu);
6517
6518
        $form = new FormValidator('quiz_form', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING']);
6519
        $defaults = [];
6520
6521
        if ($action == 'add') {
6522
            $legend = get_lang('CreateTheExercise');
6523
        } elseif ($action == 'move') {
6524
            $legend = get_lang('MoveTheCurrentExercise');
6525
        } else {
6526
            $legend = get_lang('EditCurrentExecice');
6527
        }
6528
6529 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
6530
            $legend .= Display :: return_warning_message(get_lang('Warning') . ' ! ' . get_lang('WarningEditingDocument'));
6531
        }
6532
6533
        $form->addHeader($legend);
6534
6535
        if ($action != 'move') {
6536
            $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
6537
            $defaults['title'] = $item_title;
6538
        }
6539
6540
        // Select for Parent item, root or chapter
6541
        $selectParent = $form->addSelect(
6542
            'parent',
6543
            get_lang('Parent'),
6544
            [],
6545
            ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
6546
        );
6547
        $selectParent->addOption($this->name, 0);
6548
6549
        $arrHide = array (
6550
            $id
6551
        );
6552 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6553
            if ($action != 'add') {
6554
                if (
6555
                    (
6556
                        $arrLP[$i]['item_type'] == 'dokeos_module' ||
6557
                        $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
6558
                        $arrLP[$i]['item_type'] == 'dir'
6559
                    ) &&
6560
                    !in_array($arrLP[$i]['id'], $arrHide) &&
6561
                    !in_array($arrLP[$i]['parent_item_id'], $arrHide)
6562
                ) {
6563
                    $selectParent->addOption(
6564
                        $arrLP[$i]['title'],
6565
                        $arrLP[$i]['id'],
6566
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
6567
                    );
6568
6569
                    if ($parent == $arrLP[$i]['id']) {
6570
                        $selectParent->setSelected($arrLP[$i]['id']);
6571
                    }
6572
                } else {
6573
                    $arrHide[] = $arrLP[$i]['id'];
6574
                }
6575
            } else {
6576
                if (
6577
                    $arrLP[$i]['item_type'] == 'dokeos_module' ||
6578
                    $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
6579
                    $arrLP[$i]['item_type'] == 'dir'
6580
                ) {
6581
                    $selectParent->addOption(
6582
                        $arrLP[$i]['title'],
6583
                        $arrLP[$i]['id'], ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
6584
                    );
6585
6586
                    if ($parent == $arrLP[$i]['id']) {
6587
                        $selectParent->setSelected($arrLP[$i]['id']);
6588
                    }
6589
                }
6590
            }
6591
        }
6592
        if (is_array($arrLP)) {
6593
            reset($arrLP);
6594
        }
6595
6596
        $selectPrevious = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
6597
        $selectPrevious->addOption(get_lang('FirstPosition'), 0);
6598
6599 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6600
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
6601
                $selectPrevious->addOption(get_lang('After') . ' "' . $arrLP[$i]['title'] . '"', $arrLP[$i]['id']);
6602
6603
                if (is_array($extra_info)) {
6604
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
6605
                        $selectPrevious->setSelected($arrLP[$i]['id']);
6606
                    }
6607
                } elseif ($action == 'add') {
6608
                    $selectPrevious->setSelected($arrLP[$i]['id']);
6609
                }
6610
            }
6611
        }
6612
6613 View Code Duplication
        if ($action != 'move') {
6614
            $id_prerequisite = 0;
6615
            if (is_array($arrLP)) {
6616
                foreach ($arrLP as $key => $value) {
6617
                    if ($value['id'] == $id) {
6618
                        $id_prerequisite = $value['prerequisite'];
6619
                        break;
6620
                    }
6621
                }
6622
            }
6623
            $arrHide = array ();
6624
            for ($i = 0; $i < count($arrLP); $i++) {
6625
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
6626
                    if (is_array($extra_info)) {
6627
                        if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
6628
                            $s_selected_position = $arrLP[$i]['id'];
6629
                        }
6630
                    } elseif ($action == 'add') {
6631
                        $s_selected_position = 0;
6632
                    }
6633
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
6634
                }
6635
            }
6636
            /*// Commented the prerequisites, only visible in edit (exercise).
6637
            $return .= '<tr>';
6638
            $return .= '<td class="label"><label for="idPrerequisites">'.get_lang('LearnpathPrerequisites').'</label></td>';
6639
            $return .= '<td class="input"><select name="prerequisites" id="prerequisites" class="learnpath_item_form"><option value="0">'.get_lang('NoPrerequisites').'</option>';
6640
6641
                foreach($arrHide as $key => $value){
6642
                    if($key==$s_selected_position && $action == 'add'){
6643
                        $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
6644
                    }
6645
                    elseif($key==$id_prerequisite && $action == 'edit'){
6646
                        $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
6647
                    }
6648
                    else{
6649
                        $return .= '<option value="'.$key.'">'.$value['value'].'</option>';
6650
                    }
6651
                }
6652
6653
            $return .= "</select></td>";
6654
            */
6655
            /*$return .= '<tr>';
6656
            $return .= '<td class="label"><label for="maxTimeAllowed">' . get_lang('MaxTimeAllowed') . '</label></td>';
6657
            $return .= '<td class="input"><input name="maxTimeAllowed" style="width:98%;" id="maxTimeAllowed" value="' . $extra_info['max_time_allowed'] . '" /></td>';
6658
6659
            // Remove temporarily the test description.
6660
            //$return .= '<td class="label"><label for="idDescription">'.get_lang('Description').' :</label></td>';
6661
            //$return .= '<td class="input"><textarea id="idDescription" name="description" rows="4">' . $item_description . '</textarea></td>';
6662
6663
            $return .= '</tr>'; */
6664
        }
6665
6666
        if ($action == 'add') {
6667
            $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
6668
        } else {
6669
            $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
6670
        }
6671
6672
        if ($action == 'move') {
6673
            $form->addHidden('title', $item_title);
6674
            $form->addHidden('description', $item_description);
6675
        }
6676
6677 View Code Duplication
        if (is_numeric($extra_info)) {
6678
            $form->addHidden('path', $extra_info);
6679
        } elseif (is_array($extra_info)) {
6680
            $form->addHidden('path', $extra_info['path']);
6681
        }
6682
6683
        $form->addHidden('type', TOOL_QUIZ);
6684
        $form->addHidden('post_time', time());
6685
6686
        $form->setDefaults($defaults);
6687
6688
        return '<div class="sectioncomment">' . $form->returnForm() . '</div>';
6689
    }
6690
6691
    /**
6692
     * Addition of Hotpotatoes tests
6693
     * @param	string	Action
6694
     * @param	integer	Internal ID of the item
6695
     * @param	mixed	Extra information - can be an array with title and description indexes
6696
     * @return  string	HTML structure to display the hotpotatoes addition formular
6697
     */
6698
    public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
6699
    {
6700
        $course_id = api_get_course_int_id();
6701
        $uploadPath = DIR_HOTPOTATOES; //defined in main_api
6702
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6703
6704
        if ($id != 0 && is_array($extra_info)) {
6705
            $item_title = stripslashes($extra_info['title']);
6706
            $item_description = stripslashes($extra_info['description']);
6707
        } elseif (is_numeric($extra_info)) {
6708
            $TBL_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
6709
6710
            $sql = "SELECT * FROM " . $TBL_DOCUMENT . "
6711
                    WHERE
6712
                        c_id = ".$course_id." AND
6713
                        path LIKE '" . $uploadPath . "/%/%htm%' AND
6714
                        id = " . (int) $extra_info . "
6715
                    ORDER BY id ASC";
6716
6717
            $res_hot = Database::query($sql);
6718
            $row = Database::fetch_array($res_hot);
6719
6720
            $item_title = $row['title'];
6721
            $item_description = $row['description'];
6722
6723
            if (!empty ($row['comment'])) {
6724
                $item_title = $row['comment'];
6725
            }
6726
        } else {
6727
            $item_title = '';
6728
            $item_description = '';
6729
        }
6730
6731 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6732
            $parent = $extra_info['parent_item_id'];
6733
        } else {
6734
            $parent = 0;
6735
        }
6736
6737
        $sql = "SELECT * FROM $tbl_lp_item
6738
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
6739
        $result = Database::query($sql);
6740
        $arrLP = array ();
6741 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6742
            $arrLP[] = array (
6743
                'id' => $row['id'],
6744
                'item_type' => $row['item_type'],
6745
                'title' => $row['title'],
6746
                'path' => $row['path'],
6747
                'description' => $row['description'],
6748
                'parent_item_id' => $row['parent_item_id'],
6749
                'previous_item_id' => $row['previous_item_id'],
6750
                'next_item_id' => $row['next_item_id'],
6751
                'display_order' => $row['display_order'],
6752
                'max_score' => $row['max_score'],
6753
                'min_score' => $row['min_score'],
6754
                'mastery_score' => $row['mastery_score'],
6755
                'prerequisite' => $row['prerequisite'],
6756
                'max_time_allowed' => $row['max_time_allowed']
6757
            );
6758
        }
6759
6760
        $legend = '<legend>';
6761
        if ($action == 'add')
6762
            $legend .= get_lang('CreateTheExercise');
6763
        elseif ($action == 'move') $legend .= get_lang('MoveTheCurrentExercise');
6764
        else
6765
            $legend .= get_lang('EditCurrentExecice');
6766 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
6767
            $legend .= Display :: return_warning_message(get_lang('Warning') . ' ! ' . get_lang('WarningEditingDocument'));
6768
        }
6769
        $legend .= '</legend>';
6770
6771
        $return = '<form method="POST">';
6772
        $return .= $legend;
6773
        $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
6774
        $return .= '<tr>';
6775
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . ' :</label></td>';
6776
        $return .= '<td class="input">';
6777
        $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
6778
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
6779
        $arrHide = array (
6780
            $id
6781
        );
6782
6783
        if (count($arrLP) > 0) {
6784
            for ($i = 0; $i < count($arrLP); $i++) {
6785
                if ($action != 'add') {
6786
                    if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
6787
                        $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6788
                    } else {
6789
                        $arrHide[] = $arrLP[$i]['id'];
6790
                    }
6791
                } else {
6792
                    if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
6793
                        $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6794
                }
6795
            }
6796
6797
            reset($arrLP);
6798
        }
6799
6800
        $return .= '</select>';
6801
        $return .= '</td>';
6802
        $return .= '</tr>';
6803
        $return .= '<tr>';
6804
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . ' :</label></td>';
6805
        $return .= '<td class="input">';
6806
        $return .= '<select id="previous" name="previous" size="1">';
6807
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
6808
6809
        for ($i = 0; $i < count($arrLP); $i++) {
6810
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
6811
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
6812
                    $selected = 'selected="selected" ';
6813
                elseif ($action == 'add') $selected = 'selected="selected" ';
6814
                else
6815
                    $selected = '';
6816
6817
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' . get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
6818
            }
6819
        }
6820
6821
        $return .= '</select>';
6822
        $return .= '</td>';
6823
        $return .= '</tr>';
6824
6825
        if ($action != 'move') {
6826
            $return .= '<tr>';
6827
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . ' :</label></td>';
6828
            $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="' . $item_title . '" /></td>';
6829
            $return .= '</tr>';
6830
            $id_prerequisite = 0;
6831 View Code Duplication
            if (is_array($arrLP) && count($arrLP) > 0) {
6832
                foreach ($arrLP as $key => $value) {
6833
                    if ($value['id'] == $id) {
6834
                        $id_prerequisite = $value['prerequisite'];
6835
                        break;
6836
                    }
6837
                }
6838
6839
                $arrHide = array ();
6840
                for ($i = 0; $i < count($arrLP); $i++) {
6841
                    if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
6842
                        if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
6843
                            $s_selected_position = $arrLP[$i]['id'];
6844
                        elseif ($action == 'add') $s_selected_position = 0;
6845
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
6846
6847
                    }
6848
                }
6849
            }
6850
        }
6851
6852
        $return .= '<tr>';
6853
        $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">' . get_lang('SaveHotpotatoes') . '</button></td>';
6854
        $return .= '</tr>';
6855
        $return .= '</table>';
6856
6857
        if ($action == 'move') {
6858
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
6859
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
6860
        }
6861
6862
        if (is_numeric($extra_info)) {
6863
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
6864
        } elseif (is_array($extra_info)) {
6865
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
6866
        }
6867
        $return .= '<input name="type" type="hidden" value="' . TOOL_HOTPOTATOES . '" />';
6868
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
6869
        $return .= '</form>';
6870
6871
        return $return;
6872
    }
6873
6874
    /**
6875
     * Return the form to display the forum edit/add option
6876
     * @param	string	Action (add/edit)
6877
     * @param	integer	ID of the lp_item if already exists
6878
     * @param	mixed	Forum ID or title
6879
     * @return	string	HTML form
6880
     */
6881
    public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
6882
    {
6883
        $course_id = api_get_course_int_id();
6884
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6885
        $tbl_forum = Database :: get_course_table(TABLE_FORUM);
6886
6887 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6888
            $item_title = stripslashes($extra_info['title']);
6889
        } elseif (is_numeric($extra_info)) {
6890
            $sql = "SELECT forum_title as title, forum_comment as comment
6891
                    FROM " . $tbl_forum . "
6892
                    WHERE c_id = ".$course_id." AND forum_id = " . $extra_info;
6893
6894
            $result = Database::query($sql);
6895
            $row = Database :: fetch_array($result);
6896
6897
            $item_title = $row['title'];
6898
            $item_description = $row['comment'];
6899
        } else {
6900
            $item_title = '';
6901
            $item_description = '';
6902
        }
6903
6904 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6905
            $parent = $extra_info['parent_item_id'];
6906
        } else {
6907
            $parent = 0;
6908
        }
6909
6910
        $sql = "SELECT * FROM " . $tbl_lp_item . "
6911
                WHERE
6912
                    c_id = ".$course_id." AND
6913
                    lp_id = " . $this->lp_id;
6914
        $result = Database::query($sql);
6915
        $arrLP = array();
6916
6917 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6918
            $arrLP[] = array (
6919
                'id' => $row['id'],
6920
                'item_type' => $row['item_type'],
6921
                'title' => $row['title'],
6922
                'path' => $row['path'],
6923
                'description' => $row['description'],
6924
                'parent_item_id' => $row['parent_item_id'],
6925
                'previous_item_id' => $row['previous_item_id'],
6926
                'next_item_id' => $row['next_item_id'],
6927
                'display_order' => $row['display_order'],
6928
                'max_score' => $row['max_score'],
6929
                'min_score' => $row['min_score'],
6930
                'mastery_score' => $row['mastery_score'],
6931
                'prerequisite' => $row['prerequisite']
6932
            );
6933
        }
6934
6935
        $this->tree_array($arrLP);
6936
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
6937
        unset($this->arrMenu);
6938
6939 View Code Duplication
        if ($action == 'add') {
6940
            $legend = get_lang('CreateTheForum');
6941
        } elseif ($action == 'move') {
6942
            $legend = get_lang('MoveTheCurrentForum');
6943
        } else {
6944
            $legend = get_lang('EditCurrentForum');
6945
        }
6946
6947
        $form = new FormValidator('forum_form', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING']);
6948
        $defaults = [];
6949
6950
        $form->addHeader($legend);
6951
6952 View Code Duplication
        if ($action != 'move') {
6953
            $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
6954
            $defaults['title'] = $item_title;
6955
        }
6956
6957
        $selectParent = $form->addSelect(
6958
            'parent',
6959
            get_lang('Parent'),
6960
            [],
6961
            ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
6962
        );
6963
        $selectParent->addOption($this->name, 0);
6964
6965
        $arrHide = array(
6966
            $id
6967
        );
6968
6969
        //$parent_item_id = $_SESSION['parent_item_id'];
6970 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6971
            if ($action != 'add') {
6972
                if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
6973
                    $selectParent->addOption(
6974
                        $arrLP[$i]['title'],
6975
                        $arrLP[$i]['id'],
6976
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
6977
                    );
6978
6979
                    if ($parent == $arrLP[$i]['id']) {
6980
                        $selectParent->setSelected($arrLP[$i]['id']);
6981
                    }
6982
                } else {
6983
                    $arrHide[] = $arrLP[$i]['id'];
6984
                }
6985
            } else {
6986
                if (
6987
                    $arrLP[$i]['item_type'] == 'dokeos_module' ||
6988
                    $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
6989
                    $arrLP[$i]['item_type'] == 'dir'
6990
                ) {
6991
                    $selectParent->addOption(
6992
                        $arrLP[$i]['title'],
6993
                        $arrLP[$i]['id'],
6994
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
6995
                    );
6996
6997
                    if ($parent == $arrLP[$i]['id']) {
6998
                        $selectParent->setSelected($arrLP[$i]['id']);
6999
                    }
7000
                }
7001
            }
7002
        }
7003
        if (is_array($arrLP)) {
7004
            reset($arrLP);
7005
        }
7006
7007
        $selectPrevious = $form->addSelect(
7008
            'previous',
7009
            get_lang('Position'),
7010
            [],
7011
            ['id' => 'previous', 'class' => 'learnpath_item_form']
7012
        );
7013
        $selectPrevious->addOption(get_lang('FirstPosition'), 0);
7014
7015 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7016
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7017
                $selectPrevious->addOption(get_lang('After') . ' "' . $arrLP[$i]['title'] . '"', $arrLP[$i]['id']);
7018
7019
                if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
7020
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7021
                } elseif ($action == 'add') {
7022
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7023
                }
7024
            }
7025
        }
7026
7027 View Code Duplication
        if ($action != 'move') {
7028
            $id_prerequisite = 0;
7029
            if (is_array($arrLP)) {
7030
                foreach ($arrLP as $key => $value) {
7031
                    if ($value['id'] == $id) {
7032
                        $id_prerequisite = $value['prerequisite'];
7033
                        break;
7034
                    }
7035
                }
7036
            }
7037
7038
            $arrHide = array();
7039
            for ($i = 0; $i < count($arrLP); $i++) {
7040
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7041
                    if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'])
7042
                        $s_selected_position = $arrLP[$i]['id'];
7043
                    elseif ($action == 'add') $s_selected_position = 0;
7044
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7045
                }
7046
            }
7047
        }
7048
7049
        if ($action == 'add') {
7050
            $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
7051
        } else {
7052
            $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
7053
        }
7054
7055
        if ($action == 'move') {
7056
            $form->addHidden('title', $item_title);
7057
            $form->addHidden('description', $item_description);
7058
        }
7059
7060 View Code Duplication
        if (is_numeric($extra_info)) {
7061
            $form->addHidden('path', $extra_info);
7062
        } elseif (is_array($extra_info)) {
7063
            $form->addHidden('path', $extra_info['path']);
7064
        }
7065
        $form->addHidden('type', TOOL_FORUM);
7066
        $form->addHidden('post_time', time());
7067
        $form->setDefaults($defaults);
7068
7069
        return '<div class="sectioncomment">' . $form->returnForm() . '</div>';
7070
    }
7071
7072
    /**
7073
     * Return HTML form to add/edit forum threads
7074
     * @param	string	Action (add/edit)
7075
     * @param	integer	Item ID if already exists in learning path
7076
     * @param	mixed	Extra information (thread ID if integer)
7077
     * @return 	string	HTML form
7078
     */
7079
    public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
7080
    {
7081
        $course_id = api_get_course_int_id();
7082
        if (empty($course_id)) {
7083
            return null;
7084
        }
7085
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7086
        $tbl_forum = Database :: get_course_table(TABLE_FORUM_THREAD);
7087
7088
        if ($id != 0 && is_array($extra_info)) {
7089
            $item_title = stripslashes($extra_info['title']);
7090 View Code Duplication
        } elseif (is_numeric($extra_info)) {
7091
            $sql = "SELECT thread_title as title FROM $tbl_forum
7092
                    WHERE c_id = $course_id AND thread_id = " . $extra_info;
7093
7094
            $result = Database::query($sql);
7095
            $row = Database :: fetch_array($result);
7096
7097
            $item_title = $row['title'];
7098
            $item_description = '';
7099
        } else {
7100
            $item_title = '';
7101
            $item_description = '';
7102
        }
7103
7104 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7105
            $parent = $extra_info['parent_item_id'];
7106
        } else {
7107
            $parent = 0;
7108
        }
7109
7110
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7111
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7112
7113
        $result = Database::query($sql);
7114
7115
        $arrLP = array ();
7116
7117 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7118
            $arrLP[] = array (
7119
                'id' => $row['id'],
7120
                'item_type' => $row['item_type'],
7121
                'title' => $row['title'],
7122
                'path' => $row['path'],
7123
                'description' => $row['description'],
7124
                'parent_item_id' => $row['parent_item_id'],
7125
                'previous_item_id' => $row['previous_item_id'],
7126
                'next_item_id' => $row['next_item_id'],
7127
                'display_order' => $row['display_order'],
7128
                'max_score' => $row['max_score'],
7129
                'min_score' => $row['min_score'],
7130
                'mastery_score' => $row['mastery_score'],
7131
                'prerequisite' => $row['prerequisite']
7132
            );
7133
        }
7134
7135
        $this->tree_array($arrLP);
7136
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7137
        unset ($this->arrMenu);
7138
7139
        $form = new FormValidator('thread_form', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING']);
7140
        $defaults = [];
7141
7142 View Code Duplication
        if ($action == 'add') {
7143
            $legend = get_lang('CreateTheForum');
7144
        } elseif ($action == 'move') {
7145
            $legend = get_lang('MoveTheCurrentForum');
7146
        } else {
7147
            $legend = get_lang('EditCurrentForum');
7148
        }
7149
7150
        $form->addHeader($legend);
7151
        $selectParent = $form->addSelect(
7152
            'parent',
7153
            get_lang('Parent'),
7154
            [],
7155
            ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
7156
        );
7157
        $selectParent->addOption($this->name, 0);
7158
7159
        $arrHide = array (
7160
            $id
7161
        );
7162
7163 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7164
            if ($action != 'add') {
7165
                if (
7166
                    (
7167
                        $arrLP[$i]['item_type'] == 'dokeos_module' ||
7168
                        $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
7169
                        $arrLP[$i]['item_type'] == 'dir'
7170
                    ) &&
7171
                    !in_array($arrLP[$i]['id'], $arrHide) &&
7172
                    !in_array($arrLP[$i]['parent_item_id'], $arrHide)
7173
                ) {
7174
                    $selectParent->addOption(
7175
                        $arrLP[$i]['title'],
7176
                        $arrLP[$i]['id'],
7177
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
7178
                    );
7179
7180
                    if ($parent == $arrLP[$i]['id']) {
7181
                        $selectParent->setSelected($arrLP[$i]['id']);
7182
                    }
7183
                } else {
7184
                    $arrHide[] = $arrLP[$i]['id'];
7185
                }
7186
            } else {
7187
                if (
7188
                    $arrLP[$i]['item_type'] == 'dokeos_module' ||
7189
                    $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
7190
                    $arrLP[$i]['item_type'] == 'dir'
7191
                ) {
7192
                    $selectParent->addOption(
7193
                        $arrLP[$i]['title'],
7194
                        $arrLP[$i]['id'],
7195
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
7196
                    );
7197
7198
                    if ($parent == $arrLP[$i]['id']) {
7199
                        $selectParent->setSelected($arrLP[$i]['id']);
7200
                    }
7201
                }
7202
            }
7203
        }
7204
7205
        if ($arrLP != null) {
7206
            reset($arrLP);
7207
        }
7208
7209
        $selectPrevious = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
7210
        $selectPrevious->addOption(get_lang('FirstPosition'), 0);
7211
7212 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7213
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7214
                $selectPrevious->addOption(
7215
                    get_lang('After')  . ' "' . $arrLP[$i]['title'] . '"',
7216
                    $arrLP[$i]['id']
7217
                );
7218
7219
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
7220
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7221
                } elseif ($action == 'add') {
7222
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7223
                }
7224
            }
7225
        }
7226
7227
        if ($action != 'move') {
7228
            $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
7229
            $defaults['title'] = $item_title;
7230
7231
            $id_prerequisite = 0;
7232
            if ($arrLP != null) {
7233
                foreach ($arrLP as $key => $value) {
7234
                    if ($value['id'] == $id) {
7235
                        $id_prerequisite = $value['prerequisite'];
7236
                        break;
7237
                    }
7238
                }
7239
            }
7240
7241
            $arrHide = array();
7242
            $s_selected_position = 0;
7243
7244
            for ($i = 0; $i < count($arrLP); $i++) {
7245
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7246
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7247
                        $s_selected_position = $arrLP[$i]['id'];
7248
                    elseif ($action == 'add') $s_selected_position = 0;
7249
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7250
7251
                }
7252
            }
7253
7254
            $selectPrerequisites = $form->addSelect(
7255
                'prerequisites',
7256
                get_lang('LearnpathPrerequisites'),
7257
                [],
7258
                ['id' => 'prerequisites']
7259
            );
7260
            $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
7261
7262
            foreach ($arrHide as $key => $value) {
7263
                $selectPrerequisites->addOption($value['value'], $key);
7264
7265
                if ($key == $s_selected_position && $action == 'add') {
7266
                    $selectPrerequisites->setSelected($key);
7267
                } elseif ($key == $id_prerequisite && $action == 'edit') {
7268
                    $selectPrerequisites->setSelected($key);
7269
                }
7270
            }
7271
        }
7272
7273
        $form->addButtonSave(get_lang('Ok'), 'submit_button');
7274
7275
        if ($action == 'move') {
7276
            $form->addHidden('title', $item_title);
7277
            $form->addHidden('description', $item_description);
7278
        }
7279
7280 View Code Duplication
        if (is_numeric($extra_info)) {
7281
            $form->addHidden('path', $extra_info);
7282
        }
7283
        elseif (is_array($extra_info)) {
7284
            $form->addHidden('path', $extra_info['path']);
7285
        }
7286
7287
        $form->addHidden('type', TOOL_THREAD);
7288
        $form->addHidden('post_time', time());
7289
        $form->setDefaults($defaults);
7290
7291
        return $form->returnForm();
7292
    }
7293
7294
    /**
7295
     * Return the HTML form to display an item (generally a section/module item)
7296
     * @param	string	Item type (module/dokeos_module)
7297
     * @param	string	Title (optional, only when creating)
7298
     * @param	string	Action ('add'/'edit')
7299
     * @param	integer	lp_item ID
7300
     * @param	mixed	Extra info
7301
     * @return	string 	HTML form
7302
     */
7303
    public function display_item_form($item_type, $title = '', $action = 'add_item', $id = 0, $extra_info = 'new')
7304
    {
7305
        $course_id = api_get_course_int_id();
7306
        $_course = api_get_course_info();
7307
7308
        global $charset;
7309
7310
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7311
7312
        if ($id != 0 && is_array($extra_info)) {
7313
            $item_title 		= $extra_info['title'];
7314
            $item_description 	= $extra_info['description'];
7315
            $item_path = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
7316
            $item_path_fck = '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
7317
        } else {
7318
            $item_title = '';
7319
            $item_description = '';
7320
            $item_path_fck = '';
7321
        }
7322
7323 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7324
            $parent = $extra_info['parent_item_id'];
7325
        } else {
7326
            $parent = 0;
7327
        }
7328
7329
        $id  = intval($id);
7330
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7331
                WHERE
7332
                    c_id = ".$course_id." AND
7333
                    lp_id = " . $this->lp_id . " AND
7334
                    id != $id";
7335
7336
        if ($item_type == 'module')
7337
            $sql .= " AND parent_item_id = 0";
7338
7339
        $result = Database::query($sql);
7340
        $arrLP = array ();
7341
7342 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7343
            $arrLP[] = array(
7344
                'id' => $row['id'],
7345
                'item_type' => $row['item_type'],
7346
                'title' => $row['title'],
7347
                'path' => $row['path'],
7348
                'description' => $row['description'],
7349
                'parent_item_id' => $row['parent_item_id'],
7350
                'previous_item_id' => $row['previous_item_id'],
7351
                'next_item_id' => $row['next_item_id'],
7352
                'max_score' => $row['max_score'],
7353
                'min_score' => $row['min_score'],
7354
                'mastery_score' => $row['mastery_score'],
7355
                'prerequisite' => $row['prerequisite'],
7356
                'display_order' => $row['display_order']
7357
            );
7358
        }
7359
7360
        $this->tree_array($arrLP);
7361
7362
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7363
7364
        unset ($this->arrMenu);
7365
7366
        $gradebook = isset($_GET['gradebook']) ? Security :: remove_XSS($_GET['gradebook']) : null;
7367
7368
        $url = api_get_self() . '?' .api_get_cidreq().'&gradeboook='.$gradebook.'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
7369
7370
        $form = new FormValidator('form', 'POST',  $url);
7371
7372
        $defaults['title'] = api_html_entity_decode($item_title, ENT_QUOTES, $charset);
7373
        $defaults['description'] = $item_description;
7374
7375
        $form->addElement('header', $title);
7376
7377
        //$arrHide = array($id);
7378
        $arrHide[0]['value'] = Security :: remove_XSS($this->name);
7379
        $arrHide[0]['padding'] = 20;
7380
        $charset = api_get_system_encoding();
7381
7382
        if ($item_type != 'module' && $item_type != 'dokeos_module') {
7383 View Code Duplication
            for ($i = 0; $i < count($arrLP); $i++) {
7384
                if ($action != 'add') {
7385
                    if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
7386
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7387
                        $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
7388
                        if ($parent == $arrLP[$i]['id']) {
7389
                            $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7390
                        }
7391
                    }
7392
                } else {
7393
                    if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
7394
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7395
                        $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
7396
                        if ($parent == $arrLP[$i]['id']) {
7397
                            $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7398
                        }
7399
                    }
7400
                }
7401
            }
7402
7403
            if ($action != 'move') {
7404
                $form->addElement('text', 'title', get_lang('Title'));
7405
                $form->applyFilter('title', 'html_filter');
7406
                $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
7407
            } else {
7408
                $form->addElement('hidden', 'title');
7409
            }
7410
7411
            $parent_select = $form->addElement('select', 'parent', get_lang('Parent'), '', array('id' => 'idParent', 'onchange' => "javascript: load_cbo(this.value);"));
7412
7413
            foreach ($arrHide as $key => $value) {
7414
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7415
            }
7416
            if (!empty($s_selected_parent)) {
7417
                $parent_select->setSelected($s_selected_parent);
7418
            }
7419
        }
7420
        if (is_array($arrLP)) {
7421
            reset($arrLP);
7422
        }
7423
7424
        $arrHide = array();
7425
7426
        // POSITION
7427
        for ($i = 0; $i < count($arrLP); $i++) {
7428
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7429
                //this is the same!
7430
                if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
7431
                    $s_selected_position = $arrLP[$i]['id'];
7432
                } elseif ($action == 'add') {
7433
                    $s_selected_position = $arrLP[$i]['id'];
7434
                }
7435
7436
                $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
7437
            }
7438
        }
7439
7440
        $position = $form->addElement('select', 'previous', get_lang('Position'), '', array('id' => 'previous'));
7441
        $padding = isset($value['padding']) ? $value['padding'] : 0;
7442
        $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:' . $padding . 'px;"');
7443
7444
        foreach ($arrHide as $key => $value) {
7445
            $position->addOption($value['value'] . '"', $key, 'style="padding-left:' . $padding . 'px;"');
7446
        }
7447
7448
        if (!empty ($s_selected_position)) {
7449
            $position->setSelected($s_selected_position);
7450
        }
7451
7452
        if (is_array($arrLP)) {
7453
            reset($arrLP);
7454
        }
7455
7456
        $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
7457
7458
        if ($item_type == 'module' || $item_type == 'dokeos_module') {
7459
            $form->addElement('hidden', 'parent', '0');
7460
        }
7461
        //fix in order to use the tab
7462
        if ($item_type == 'chapter') {
7463
            $form->addElement('hidden', 'type', 'chapter');
7464
        }
7465
7466
        $extension = null;
7467
        if (!empty($item_path)) {
7468
            $extension = pathinfo($item_path, PATHINFO_EXTENSION);
7469
        }
7470
7471
        //assets can't be modified
7472
7473
        //$item_type == 'asset' ||
7474
        if (( $item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
7475
7476
            if ($item_type == 'sco') {
7477
                $form->addElement('html', '<script type="text/javascript">alert("' . get_lang('WarningWhenEditingScorm') . '")</script>');
7478
            }
7479
            $renderer = $form->defaultRenderer();
7480
            $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
7481
7482
            $relative_prefix = '';
7483
7484
            $editor_config = array( 'ToolbarSet' 			=> 'LearningPathDocuments',
7485
                'Width' 				=> '100%',
7486
                'Height' 				=> '500',
7487
                'FullPage' 				=> true,
7488
                'CreateDocumentDir' 	=> $relative_prefix,
7489
                'CreateDocumentWebDir' 	=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/scorm/',
7490
                'BaseHref' 				=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().$item_path_fck
7491
            );
7492
7493
            $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
7494
            $content_path = (api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck);
7495
            //$defaults['content_lp'] = file_get_contents($item_path);
7496
            $defaults['content_lp'] = file_get_contents($content_path);
7497
        }
7498
7499
        $form->addElement('hidden', 'type', 'dokeos_' . $item_type);
7500
        $form->addElement('hidden', 'post_time', time());
7501
        $form->setDefaults($defaults);
7502
        return $form->return_form();
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
7503
    }
7504
7505
    /**
7506
     * Returns the form to update or create a document
7507
     * @param	string	Action (add/edit)
7508
     * @param	integer	ID of the lp_item (if already exists)
7509
     * @param	mixed	Integer if document ID, string if info ('new')
7510
     * @return	string	HTML form
7511
     */
7512
    public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
7513
    {
7514
        $course_id = api_get_course_int_id();
7515
        $_course = api_get_course_info();
7516
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7517
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
7518
7519
        $no_display_edit_textarea = false;
7520
        $item_description = '';
7521
        //If action==edit document
7522
        //We don't display the document form if it's not an editable document (html or txt file)
7523
        if ($action == "edit") {
7524
            if (is_array($extra_info)) {
7525
                $path_parts = pathinfo($extra_info['dir']);
7526
                if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
7527
                    $no_display_edit_textarea = true;
7528
                }
7529
            }
7530
        }
7531
        $no_display_add = false;
7532
7533
        // If action==add an existing document
7534
        // We don't display the document form if it's not an editable document (html or txt file).
7535
        if ($action == "add") {
7536
            if (is_numeric($extra_info)) {
7537
                $sql_doc = "SELECT path FROM " . $tbl_doc . "
7538
                            WHERE c_id = ".$course_id." AND id = " . intval($extra_info);
7539
                $result = Database::query($sql_doc);
7540
                $path_file = Database :: result($result, 0, 0);
7541
                $path_parts = pathinfo($path_file);
7542
                if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
7543
                    $no_display_add = true;
7544
                }
7545
            }
7546
        }
7547
        if ($id != 0 && is_array($extra_info)) {
7548
            $item_title = stripslashes($extra_info['title']);
7549
            $item_description = stripslashes($extra_info['description']);
7550
            $item_terms = stripslashes($extra_info['terms']);
7551 View Code Duplication
            if (empty ($item_title)) {
7552
                $path_parts = pathinfo($extra_info['path']);
7553
                $item_title = stripslashes($path_parts['filename']);
7554
            }
7555
        } elseif (is_numeric($extra_info)) {
7556
            $sql_doc = "SELECT path, title FROM " . $tbl_doc . "
7557
                        WHERE
7558
                            c_id = ".$course_id." AND
7559
                            id = " . intval($extra_info);
7560
7561
            $result = Database::query($sql_doc);
7562
            $row 	= Database::fetch_array($result);
7563
            $item_title = $row['title'];
7564
            $item_title = str_replace('_', ' ', $item_title);
7565 View Code Duplication
            if (empty ($item_title)) {
7566
                $path_parts = pathinfo($row['path']);
7567
                $item_title = stripslashes($path_parts['filename']);
7568
            }
7569
        } else {
7570
            $item_title = '';
7571
            $item_description = '';
7572
        }
7573
        $return = '<legend>';
7574
7575 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7576
            $parent = $extra_info['parent_item_id'];
7577
        } else {
7578
            $parent = 0;
7579
        }
7580
7581
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7582
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7583
7584
        $result = Database::query($sql);
7585
        $arrLP = array ();
7586 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7587
            $arrLP[] = array(
7588
                'id' => $row['id'],
7589
                'item_type' => $row['item_type'],
7590
                'title' => $row['title'],
7591
                'path' => $row['path'],
7592
                'description' => $row['description'],
7593
                'parent_item_id' => $row['parent_item_id'],
7594
                'previous_item_id' => $row['previous_item_id'],
7595
                'next_item_id' => $row['next_item_id'],
7596
                'display_order' => $row['display_order'],
7597
                'max_score' => $row['max_score'],
7598
                'min_score' => $row['min_score'],
7599
                'mastery_score' => $row['mastery_score'],
7600
                'prerequisite' => $row['prerequisite']
7601
            );
7602
        }
7603
7604
        $this->tree_array($arrLP);
7605
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7606
        unset ($this->arrMenu);
7607
7608
        if ($action == 'add') {
7609
            $return .= get_lang('CreateTheDocument');
7610
        } elseif ($action == 'move') {
7611
            $return .= get_lang('MoveTheCurrentDocument');
7612
        } else {
7613
            $return .= get_lang('EditTheCurrentDocument');
7614
        }
7615
7616
        $return .= '</legend>';
7617
7618 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
7619
            $return .= Display :: return_warning_message('<strong>' . get_lang('Warning') . ' !</strong><br />' . get_lang('WarningEditingDocument'), false);
7620
        }
7621
        $form = new FormValidator('form', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING'], '', array('enctype'=> "multipart/form-data"));
7622
        $defaults['title'] = Security :: remove_XSS($item_title);
7623
        if (empty($item_title)) {
7624
            $defaults['title'] = Security::remove_XSS($item_title);
7625
        }
7626
        $defaults['description'] = $item_description;
7627
        $form->addElement('html', $return);
7628
        if ($action != 'move') {
7629
            $form->addElement('text', 'title', get_lang('Title'), array('id' => 'idTitle', 'class' => 'col-md-4'));
7630
            $form->applyFilter('title', 'html_filter');
7631
        }
7632
7633
        $arrHide[0]['value'] = $this->name;
7634
        $arrHide[0]['padding'] = 20;
7635
7636 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7637
            if ($action != 'add') {
7638
                if (($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide) && !in_array($arrLP[$i]['parent_item_id'], $arrHide)) {
7639
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7640
                    $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
7641
                    if ($parent == $arrLP[$i]['id']) {
7642
                        $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7643
                    }
7644
                }
7645
            } else {
7646
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
7647
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7648
                    $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
7649
                    if ($parent == $arrLP[$i]['id']) {
7650
                        $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7651
                    }
7652
                }
7653
            }
7654
        }
7655
7656
        $parent_select = $form->addSelect('parent', get_lang('Parent'), [], ['id' => 'idParent', 'onchange' => 'javascript: load_cbo(this.value);']);
7657
        $my_count=0;
7658
        foreach ($arrHide as $key => $value) {
7659
            if ($my_count!=0) {
7660
                // The LP name is also the first section and is not in the same charset like the other sections.
7661
                $value['value'] = Security :: remove_XSS($value['value']);
7662
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7663
            } else {
7664
                $value['value'] = Security :: remove_XSS($value['value']);
7665
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7666
            }
7667
            $my_count++;
7668
        }
7669
7670
        if (!empty($id)) {
7671
            $parent_select->setSelected($parent);
7672
        } else {
7673
            $parent_item_id = isset($_SESSION['parent_item_id']) ? $_SESSION['parent_item_id'] : 0 ;
7674
            $parent_select->setSelected($parent_item_id);
7675
        }
7676
7677
        if (is_array($arrLP)) {
7678
            reset($arrLP);
7679
        }
7680
7681
        $arrHide = array();
7682
        $s_selected_position = null;
7683
7684
        //POSITION
7685
        for ($i = 0; $i < count($arrLP); $i++) {
7686
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id || $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
7687
                if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'] || $action == 'add') {
7688
                    $s_selected_position = $arrLP[$i]['id'];
7689
                }
7690
                $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
7691
            }
7692
        }
7693
7694
        $position = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
7695
        $position->addOption(get_lang('FirstPosition'), 0);
7696
7697
        foreach ($arrHide as $key => $value) {
7698
            $padding = isset($value['padding']) ? $value['padding']: 20;
7699
            $position->addOption($value['value'], $key, 'style="padding-left:' . $padding . 'px;"');
7700
        }
7701
7702
        $position->setSelected($s_selected_position);
7703
7704
        if (is_array($arrLP)) {
7705
            reset($arrLP);
7706
        }
7707
7708
        if ($action != 'move') {
7709
            $id_prerequisite = 0;
7710
            if (is_array($arrLP)) {
7711
                foreach ($arrLP as $key => $value) {
7712
                    if ($value['id'] == $id) {
7713
                        $id_prerequisite = $value['prerequisite'];
7714
                        break;
7715
                    }
7716
                }
7717
            }
7718
7719
            $arrHide = array();
7720
7721
            for ($i = 0; $i < count($arrLP); $i++) {
7722
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter' && $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
7723
                    if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'])
7724
                        $s_selected_position = $arrLP[$i]['id'];
7725
                    elseif ($action == 'add') $s_selected_position = $arrLP[$i]['id'];
7726
7727
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7728
7729
                }
7730
            }
7731
7732
            if (!$no_display_add) {
7733
                $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
7734
                $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
7735
                if (($extra_info == 'new' || $item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true')) {
7736
                    if (isset ($_POST['content']))
7737
                        $content = stripslashes($_POST['content']);
7738
                    elseif (is_array($extra_info)) {
7739
                        //If it's an html document or a text file
7740
                        if (!$no_display_edit_textarea) {
7741
                            $content = $this->display_document($extra_info['path'], false, false);
7742
                        }
7743
                    } elseif (is_numeric($extra_info))
7744
                        $content = $this->display_document($extra_info, false, false);
7745
                    else
7746
                        $content = '';
7747
7748
                    if (!$no_display_edit_textarea) {
7749
                        // We need to calculate here some specific settings for the online editor.
7750
                        // The calculated settings work for documents in the Documents tool
7751
                        // (on the root or in subfolders).
7752
                        // For documents in native scorm packages it is unclear whether the
7753
                        // online editor should be activated or not.
7754
7755
                        // A new document, it is in the root of the repository.
7756
                        $relative_path 	 = '';
7757
                        $relative_prefix = '';
7758
7759
                        if (is_array($extra_info) && $extra_info != 'new') {
7760
                            // The document already exists. Whe have to determine its relative path towards the repository root.
7761
                            $relative_path = explode('/', $extra_info['dir']);
7762
                            $cnt = count($relative_path) - 2;
7763
                            if ($cnt < 0) {
7764
                                $cnt = 0;
7765
                            }
7766
                            $relative_prefix = str_repeat('../', $cnt);
7767
                            $relative_path 	 = array_slice($relative_path, 1, $cnt);
7768
                            $relative_path 	 = implode('/', $relative_path);
7769
                            if (strlen($relative_path) > 0) {
7770
                                $relative_path = $relative_path . '/';
7771
                            }
7772
                        } else {
7773
                            $result = $this->generate_lp_folder($_course);
7774
                            $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
7775
                            $relative_prefix = '../../';
7776
                        }
7777
7778
                        $editor_config = array(
7779
                            'ToolbarSet'=> 'LearningPathDocuments',
7780
                            'Width' 				=> '100%',
7781
                            'Height' 				=> '500',
7782
                            'FullPage' 				=> true,
7783
                            'CreateDocumentDir' 	=> $relative_prefix,
7784
                            'CreateDocumentWebDir' 	=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/document/',
7785
                            'BaseHref' 				=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/document/'.$relative_path
7786
                        );
7787
7788
                        if ($_GET['action'] == 'add_item') {
7789
                            $class = 'add';
7790
                            $text = get_lang('LPCreateDocument');
7791
                        } else {
7792
                            if ($_GET['action'] == 'edit_item') {
7793
                                $class = 'save';
7794
                                $text = get_lang('SaveDocument');
7795
                            }
7796
                        }
7797
7798
                        $form->addButtonSave($text, 'submit_button');
7799
                        $renderer = $form->defaultRenderer();
7800
                        $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
7801
                        $form->addElement('html', '<div class="editor-lp">');
7802
                        $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
7803
                        $form->addElement('html', '</div>');
7804
                        $defaults['content_lp'] = $content;
7805
                    }
7806
                } elseif (is_numeric($extra_info)) {
7807
                    $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7808
7809
                    $return = $this->display_document($extra_info, true, true, true);
7810
                    $form->addElement('html', $return);
7811
                }
7812
            }
7813
        }
7814
7815
        if ($action == 'move') {
7816
            $form->addElement('hidden', 'title', $item_title);
7817
            $form->addElement('hidden', 'description', $item_description);
7818
        }
7819
        if (is_numeric($extra_info)) {
7820
            $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7821
            $form->addElement('hidden', 'path', $extra_info);
7822
        } elseif (is_array($extra_info)) {
7823
            $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7824
            $form->addElement('hidden', 'path', $extra_info['path']);
7825
        }
7826
        $form->addElement('hidden', 'type', TOOL_DOCUMENT);
7827
        $form->addElement('hidden', 'post_time', time());
7828
        $form->setDefaults($defaults);
7829
7830
        return $form->return_form();
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
7831
    }
7832
7833
    /**
7834
     * Return HTML form to add/edit a link item
7835
     * @param string	$action (add/edit)
7836
     * @param integer	$id Item ID if exists
7837
     * @param mixed		$extra_info
7838
     * @return	string	HTML form
7839
     */
7840
    public function display_link_form($action = 'add', $id = 0, $extra_info = '')
7841
    {
7842
        $course_id = api_get_course_int_id();
7843
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7844
        $tbl_link = Database :: get_course_table(TABLE_LINK);
7845
7846
        if ($id != 0 && is_array($extra_info)) {
7847
            $item_title = stripslashes($extra_info['title']);
7848
            $item_description = stripslashes($extra_info['description']);
7849
            $item_url = stripslashes($extra_info['url']);
7850
        } elseif (is_numeric($extra_info)) {
7851
            $extra_info = intval($extra_info);
7852
            $sql = "SELECT title, description, url FROM " . $tbl_link . "
7853
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
7854
            $result = Database::query($sql);
7855
            $row = Database :: fetch_array($result);
7856
            $item_title       = $row['title'];
7857
            $item_description = $row['description'];
7858
            $item_url = $row['url'];
7859
        } else {
7860
            $item_title = '';
7861
            $item_description = '';
7862
            $item_url = '';
7863
        }
7864
7865
        $form = new FormValidator('edit_link', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING']);
7866
        $defaults = [];
7867
7868 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7869
            $parent = $extra_info['parent_item_id'];
7870
        } else {
7871
            $parent = 0;
7872
        }
7873
7874
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7875
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7876
        $result = Database::query($sql);
7877
        $arrLP = array();
7878
7879 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7880
            $arrLP[] = array(
7881
                'id' => $row['id'],
7882
                'item_type' => $row['item_type'],
7883
                'title' => $row['title'],
7884
                'path' => $row['path'],
7885
                'description' => $row['description'],
7886
                'parent_item_id' => $row['parent_item_id'],
7887
                'previous_item_id' => $row['previous_item_id'],
7888
                'next_item_id' => $row['next_item_id'],
7889
                'display_order' => $row['display_order'],
7890
                'max_score' => $row['max_score'],
7891
                'min_score' => $row['min_score'],
7892
                'mastery_score' => $row['mastery_score'],
7893
                'prerequisite' => $row['prerequisite']
7894
            );
7895
        }
7896
7897
        $this->tree_array($arrLP);
7898
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7899
        unset ($this->arrMenu);
7900
7901
        if ($action == 'add') {
7902
            $legend = get_lang('CreateTheLink');
7903
        } elseif ($action == 'move') {
7904
            $legend = get_lang('MoveCurrentLink');
7905
        } else {
7906
            $legend = get_lang('EditCurrentLink');
7907
        }
7908
7909
        $form->addHeader($legend);
7910
7911 View Code Duplication
        if ($action != 'move') {
7912
            $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
7913
            $defaults['title'] = $item_title;
7914
        }
7915
7916
        $selectParent = $form->addSelect(
7917
            'parent',
7918
            get_lang('Parent'),
7919
            [],
7920
            ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
7921
        );
7922
        $selectParent->addOption($this->name, 0);
7923
        $arrHide = array(
7924
            $id
7925
        );
7926
7927
        $parent_item_id = isset($_SESSION['parent_item_id']) ? $_SESSION['parent_item_id'] : 0;
7928
7929 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7930
            if ($action != 'add') {
7931
                if (
7932
                    (
7933
                        $arrLP[$i]['item_type'] == 'dokeos_module' ||
7934
                        $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
7935
                        $arrLP[$i]['item_type'] == 'dir'
7936
                    ) &&
7937
                    !in_array($arrLP[$i]['id'], $arrHide) &&
7938
                    !in_array($arrLP[$i]['parent_item_id'], $arrHide)
7939
                ) {
7940
                    $selectParent->addOption(
7941
                        $arrLP[$i]['title'],
7942
                        $arrLP[$i]['id'],
7943
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px;']
7944
                    );
7945
7946
                    if ($parent == $arrLP[$i]['id']) {
7947
                        $selectParent->setSelected($arrLP[$i]['id']);
7948
                    }
7949
                } else {
7950
                    $arrHide[] = $arrLP[$i]['id'];
7951
                }
7952
            } else {
7953
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
7954
                    $selectParent->addOption(
7955
                        $arrLP[$i]['title'],
7956
                        $arrLP[$i]['id'],
7957
                        ['style' => 'padding-left: ' . (20 + $arrLP[$i]['depth'] * 20) . 'px']
7958
                    );
7959
7960
                    if ($parent_item_id == $arrLP[$i]['id']) {
7961
                        $selectParent->setSelected($arrLP[$i]['id']);
7962
                    }
7963
                }
7964
            }
7965
        }
7966
7967
        if (is_array($arrLP)) {
7968
            reset($arrLP);
7969
        }
7970
7971
        $selectPrevious = $form->addSelect(
7972
            'previous',
7973
            get_lang('Position'),
7974
            [],
7975
            ['id' => 'previous', 'class' => 'learnpath_item_form']
7976
        );
7977
        $selectPrevious->addOption(get_lang('FirstPosition'), 0);
7978
7979
        for ($i = 0; $i < count($arrLP); $i++) {
7980
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7981
                $selectPrevious->addOption($arrLP[$i]['title'], $arrLP[$i]['id']);
7982
7983
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
7984
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7985
                } elseif ($action == 'add') {
7986
                    $selectPrevious->setSelected($arrLP[$i]['id']);
7987
                }
7988
            }
7989
        }
7990
7991
        if ($action != 'move') {
7992
            $urlAttributes = ['class' => 'learnpath_item_form'];
7993
7994
            if (is_numeric($extra_info)) {
7995
                $urlAttributes['disabled'] = 'disabled';
7996
            }
7997
7998
            $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
7999
            $defaults['url'] = $item_url;
8000
8001
            $id_prerequisite = 0;
8002
            if (is_array($arrLP)) {
8003
                foreach ($arrLP as $key => $value) {
8004
                    if ($value['id'] == $id) {
8005
                        $id_prerequisite = $value['prerequisite'];
8006
                        break;
8007
                    }
8008
                }
8009
            }
8010
8011
            $arrHide = array();
8012
            for ($i = 0; $i < count($arrLP); $i++) {
8013
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
8014
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
8015
                        $s_selected_position = $arrLP[$i]['id'];
8016
                    elseif ($action == 'add') $s_selected_position = 0;
8017
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
8018
8019
                }
8020
            }
8021
        }
8022
8023
        if ($action == 'add') {
8024
            $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
8025
        } else {
8026
            $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
8027
        }
8028
8029
        if ($action == 'move') {
8030
            $form->addHidden('title', $item_title);
8031
            $form->addHidden('description', $item_description);
8032
        }
8033
8034 View Code Duplication
        if (is_numeric($extra_info)) {
8035
            $form->addHidden('path', $extra_info);
8036
        } elseif (is_array($extra_info)) {
8037
            $form->addHidden('path', $extra_info['path']);
8038
        }
8039
        $form->addHidden('type', TOOL_LINK);
8040
        $form->addHidden('post_time', time());
8041
8042
        $form->setDefaults($defaults);
8043
8044
        return '<div class="sectioncomment">' . $form->returnForm() . '</div>';
8045
    }
8046
8047
    /**
8048
     * Return HTML form to add/edit a student publication (work)
8049
     * @param	string	Action (add/edit)
8050
     * @param	integer	Item ID if already exists
8051
     * @param	mixed	Extra info (work ID if integer)
8052
     * @return	string	HTML form
8053
     */
8054
    public function display_student_publication_form($action = 'add', $id = 0, $extra_info = '')
8055
    {
8056
        $course_id = api_get_course_int_id();
8057
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8058
        $tbl_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
8059
8060
        if ($id != 0 && is_array($extra_info)) {
8061
            $item_title = stripslashes($extra_info['title']);
8062
            $item_description = stripslashes($extra_info['description']);
8063
        } elseif (is_numeric($extra_info)) {
8064
            $extra_info = intval($extra_info);
8065
            $sql = "SELECT title, description
8066
                    FROM " . $tbl_publication . "
8067
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
8068
8069
            $result = Database::query($sql);
8070
            $row = Database :: fetch_array($result);
8071
8072
            $item_title = $row['title'];
8073
        } else {
8074
            $item_title = get_lang('Student_publication');
8075
        }
8076
8077 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
8078
            $parent = $extra_info['parent_item_id'];
8079
        } else {
8080
            $parent = 0;
8081
        }
8082
8083
        $sql = "SELECT * FROM " . $tbl_lp_item . "
8084
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
8085
8086
        $result = Database::query($sql);
8087
        $arrLP = array();
8088 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
8089
            $arrLP[] = array (
8090
                'id' => $row['id'],
8091
                'item_type' => $row['item_type'],
8092
                'title' => $row['title'],
8093
                'path' => $row['path'],
8094
                'description' => $row['description'],
8095
                'parent_item_id' => $row['parent_item_id'],
8096
                'previous_item_id' => $row['previous_item_id'],
8097
                'next_item_id' => $row['next_item_id'],
8098
                'display_order' => $row['display_order'],
8099
                'max_score' => $row['max_score'],
8100
                'min_score' => $row['min_score'],
8101
                'mastery_score' => $row['mastery_score'],
8102
                'prerequisite' => $row['prerequisite']
8103
            );
8104
        }
8105
8106
        $this->tree_array($arrLP);
8107
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
8108
        unset ($this->arrMenu);
8109
8110
        $form = new FormValidator('frm_student_publication', 'post', '#');
8111
8112
        if ($action == 'add') {
8113
            $form->addHeader(get_lang('Student_publication'));
8114
        } elseif ($action == 'move') {
8115
            $form->addHeader(get_lang('MoveCurrentStudentPublication'));
8116
        } else {
8117
            $form->addHeader(get_lang('EditCurrentStudentPublication'));
8118
        }
8119
8120 View Code Duplication
        if ($action != 'move') {
8121
            $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form', 'id' => 'idTitle']);
8122
        }
8123
8124
        $parentSelect = $form->addSelect(
8125
            'parent',
8126
            get_lang('Parent'),
8127
            ['0' => $this->name],
8128
            [
8129
                'onchange' => 'javascript: load_cbo(this.value);',
8130
                'class' => 'learnpath_item_form',
8131
                'id' => 'idParent'
8132
            ]
8133
        );
8134
8135
        $arrHide = array (
8136
            $id
8137
        );
8138
8139 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
8140
            if ($action != 'add') {
8141
                if (
8142
                    (
8143
                        $arrLP[$i]['item_type'] == 'dokeos_module' ||
8144
                        $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
8145
                        $arrLP[$i]['item_type'] == 'dir'
8146
                    ) &&
8147
                    !in_array($arrLP[$i]['id'], $arrHide) &&
8148
                    !in_array($arrLP[$i]['parent_item_id'], $arrHide)
8149
                ) {
8150
                    $parentSelect->addOption(
8151
                        $arrLP[$i]['title'],
8152
                        $arrLP[$i]['id'],
8153
                        ['style' => 'padding-left: ' . (($arrLP[$i]['depth'] * 10) + 20) . 'px;']
8154
                    );
8155
8156
                    if ($parent == $arrLP[$i]['id']) {
8157
                        $parentSelect->setSelected($arrLP[$i]['id']);
8158
                    }
8159
                } else {
8160
                    $arrHide[] = $arrLP[$i]['id'];
8161
                }
8162
            } else {
8163
                if (
8164
                    $arrLP[$i]['item_type'] == 'dokeos_module' ||
8165
                    $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir'
8166
                ) {
8167
                    $parentSelect->addOption(
8168
                        $arrLP[$i]['title'],
8169
                        $arrLP[$i]['id'],
8170
                        ['style' => 'padding-left: ' . (($arrLP[$i]['depth'] * 10) + 20) . 'px;']
8171
                    );
8172
8173
                    if ($parent == $arrLP[$i]['id']) {
8174
                        $parentSelect->setSelected($arrLP[$i]['id']);
8175
                    }
8176
                }
8177
            }
8178
        }
8179
8180
        if (is_array($arrLP)) {
8181
            reset($arrLP);
8182
        }
8183
8184
        $previousSelect = $form->addSelect(
8185
            'previous',
8186
            get_lang('Position'),
8187
            ['0' => get_lang('FirstPosition')],
8188
            ['id' => 'previous', 'class' => 'learnpath_item_form']
8189
        );
8190
8191 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
8192
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
8193
                $previousSelect->addOption(
8194
                    get_lang('After') . ' "' . $arrLP[$i]['title'] . '"',
8195
                    $arrLP[$i]['id']
8196
                );
8197
8198
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
8199
                    $previousSelect->setSelected($arrLP[$i]['id']);
8200
                } elseif ($action == 'add') {
8201
                    $previousSelect->setSelected($arrLP[$i]['id']);
8202
                }
8203
            }
8204
        }
8205
8206 View Code Duplication
        if ($action != 'move') {
8207
            $id_prerequisite = 0;
8208
            if (is_array($arrLP)) {
8209
                foreach ($arrLP as $key => $value) {
8210
                    if ($value['id'] == $id) {
8211
                        $id_prerequisite = $value['prerequisite'];
8212
                        break;
8213
                    }
8214
                }
8215
            }
8216
            $arrHide = array ();
8217
            for ($i = 0; $i < count($arrLP); $i++) {
8218
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
8219
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
8220
                        $s_selected_position = $arrLP[$i]['id'];
8221
                    elseif ($action == 'add') $s_selected_position = 0;
8222
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
8223
8224
                }
8225
            }
8226
        }
8227
8228
        if ($action == 'add') {
8229
            $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
8230
        } else {
8231
            $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
8232
        }
8233
8234
        if ($action == 'move') {
8235
            $form->addHidden('title', $item_title);
8236
            $form->addHidden('description', $item_description);
8237
        }
8238
8239 View Code Duplication
        if (is_numeric($extra_info)) {
8240
            $form->addHidden('path', $extra_info);
8241
        } elseif (is_array($extra_info)) {
8242
            $form->addHidden('path', $extra_info['path']);
8243
        }
8244
8245
        $form->addHidden('type', TOOL_STUDENTPUBLICATION);
8246
        $form->addHidden('post_time', time());
8247
        $form->setDefaults(['title' => $item_title]);
8248
8249
        $return = '<div class="sectioncomment">';
8250
        $return .= $form->returnForm();
8251
        $return .= '</div>';
8252
8253
        return $return;
8254
    }
8255
8256
    /**
8257
     * Displays the menu for manipulating a step
8258
     *
8259
     * @param $item_id
8260
     * @param string $item_type
8261
     * @return string
8262
     */
8263
    public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
8264
    {
8265
        $_course = api_get_course_info();
8266
        $course_id = api_get_course_int_id();
8267
        $course_code = api_get_course_id();
8268
8269
        $return = '<div class="actions">';
8270
8271
        switch ($item_type) {
8272
            case 'dokeos_chapter' :
8273
            case 'chapter' :
8274
                // Commented the message cause should not show it.
8275
                //$lang = get_lang('TitleManipulateChapter');
8276
                break;
8277
8278
            case 'dokeos_module' :
8279
            case 'module' :
8280
                // Commented the message cause should not show it.
8281
                //$lang = get_lang('TitleManipulateModule');
8282
                break;
8283
            case TOOL_LP_FINAL_ITEM :
8284
            case TOOL_DOCUMENT :
8285
                // Commented the message cause should not show it.
8286
                //$lang = get_lang('TitleManipulateDocument');
8287
                break;
8288
8289
            case TOOL_LINK :
8290
            case 'link' :
8291
                // Commented the message cause should not show it.
8292
                //$lang = get_lang('TitleManipulateLink');
8293
                break;
8294
8295
            case TOOL_QUIZ :
8296
                // Commented the message cause should not show it.
8297
                //$lang = get_lang('TitleManipulateQuiz');
8298
                break;
8299
8300
            case TOOL_STUDENTPUBLICATION :
8301
                // Commented the message cause should not show it.
8302
                //$lang = get_lang('TitleManipulateStudentPublication');
8303
                break;
8304
        }
8305
8306
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8307
        $item_id = intval($item_id);
8308
        $sql = "SELECT * FROM " . $tbl_lp_item . " as lp
8309
                WHERE lp.c_id = ".$course_id." AND lp.id = " . $item_id;
8310
        $result = Database::query($sql);
8311
        $row = Database::fetch_assoc($result);
8312
8313
        $audio_player = null;
8314
        // We display an audio player if needed.
8315
        if (!empty($row['audio'])) {
8316
            $audio_player .= '<div class="lp_mediaplayer" id="container">
8317
                              <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
8318
                              </div>';
8319
            $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
8320
            $audio_player .= '<script>
8321
                                var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
8322
                                s1.addParam("allowscriptaccess","always");
8323
                                s1.addParam("flashvars","file=../../courses/' . $_course['path'] . '/document/audio/' . $row['audio'] . '&autostart=true");
8324
                                s1.write("container");
8325
                            </script>';
8326
        }
8327
8328
        $url = api_get_self().'?cidReq='.Security::remove_XSS($_GET['cidReq']).'&view=build&id='.$item_id .'&lp_id='.$this->lp_id;
8329
8330
        $return .= Display::url(
8331
            Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL),
8332
            $url.'&action=edit_item&path_item=' . $row['path']
8333
        );
8334
8335
        $return .= Display::url(
8336
            Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL),
8337
            $url.'&action=move_item'
8338
        );
8339
8340
        // Commented for now as prerequisites cannot be added to chapters.
8341
        if ($item_type != 'dokeos_chapter' && $item_type != 'chapter') {
8342
            $return .= Display::url(
8343
                Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_SMALL),
8344
                $url.'&action=edit_item_prereq'
8345
            );
8346
        }
8347
        $return .= Display::url(
8348
            Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL),
8349
            $url.'&action=delete_item'
8350
        );
8351
8352 View Code Duplication
        if ($item_type == TOOL_HOTPOTATOES ) {
8353
            $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
8354
            $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
8355
        }
8356
8357 View Code Duplication
        if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
8358
            $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
8359
            $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
8360
        }
8361
8362
        $return .= '</div>';
8363
8364
        if (!empty($audio_player)) {
8365
            $return .= '<br />'.$audio_player;
8366
        }
8367
8368
        return $return;
8369
    }
8370
8371
    /**
8372
     * Creates the javascript needed for filling up the checkboxes without page reload
8373
     * @return string
8374
     */
8375
    public function get_js_dropdown_array()
8376
    {
8377
        $course_id = api_get_course_int_id();
8378
        $return = 'var child_name = new Array();' . "\n";
8379
        $return .= 'var child_value = new Array();' . "\n\n";
8380
        $return .= 'child_name[0] = new Array();' . "\n";
8381
        $return .= 'child_value[0] = new Array();' . "\n\n";
8382
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8383
        $sql_zero = "SELECT * FROM " . $tbl_lp_item . "
8384
                    WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id . " AND parent_item_id = 0
8385
                    ORDER BY display_order ASC";
8386
        $res_zero = Database::query($sql_zero);
8387
        $i = 0;
8388
8389
        while ($row_zero = Database :: fetch_array($res_zero)) {
8390
            if ($row_zero['item_type'] == TOOL_QUIZ) {
8391
                $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
8392
            }
8393
            $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
8394
            $return .= 'child_name[0][' . $i . '] = '.$js_var.' ;' . "\n";
8395
            $return .= 'child_value[0][' . $i++ . '] = "' . $row_zero['id'] . '";' . "\n";
8396
        }
8397
        $return .= "\n";
8398
        $sql = "SELECT * FROM " . $tbl_lp_item . "
8399
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
8400
        $res = Database::query($sql);
8401
        while ($row = Database :: fetch_array($res)) {
8402
            $sql_parent = "SELECT * FROM " . $tbl_lp_item . "
8403
                           WHERE
8404
                                c_id = ".$course_id." AND
8405
                                parent_item_id = " . $row['id'] . "
8406
                           ORDER BY display_order ASC";
8407
            $res_parent = Database::query($sql_parent);
8408
            $i = 0;
8409
            $return .= 'child_name[' . $row['id'] . '] = new Array();' . "\n";
8410
            $return .= 'child_value[' . $row['id'] . '] = new Array();' . "\n\n";
8411
8412
            while ($row_parent = Database :: fetch_array($res_parent)) {
8413
                $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
8414
                $return .= 'child_name[' . $row['id'] . '][' . $i . '] =   '.$js_var.' ;' . "\n";
8415
                $return .= 'child_value[' . $row['id'] . '][' . $i++ . '] = "' . $row_parent['id'] . '";' . "\n";
8416
            }
8417
            $return .= "\n";
8418
        }
8419
8420
        return $return;
8421
    }
8422
8423
    /**
8424
     * Display the form to allow moving an item
8425
     * @param	integer		Item ID
8426
     * @return	string		HTML form
8427
     */
8428
    public function display_move_item($item_id)
8429
    {
8430
        $course_id = api_get_course_int_id();
8431
        $return = '';
8432
8433
        if (is_numeric($item_id)) {
8434
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8435
8436
            $sql = "SELECT * FROM " . $tbl_lp_item . "
8437
                    WHERE c_id = ".$course_id." AND id = " . $item_id;
8438
8439
            $res = Database::query($sql);
8440
            $row = Database :: fetch_array($res);
8441
8442
            switch ($row['item_type']) {
8443
                case 'dokeos_chapter' :
8444
                case 'dir' :
8445
                case 'asset' :
8446
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8447
                    $return .= $this->display_item_form($row['item_type'], get_lang('MoveCurrentChapter'), 'move', $item_id, $row);
8448
                    break;
8449
                case 'dokeos_module' :
8450
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8451
                    $return .= $this->display_item_form($row['item_type'], 'Move th current module:', 'move', $item_id, $row);
8452
                    break;
8453
                case TOOL_DOCUMENT :
8454
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8455
                    $return .= $this->display_document_form('move', $item_id, $row);
8456
                    break;
8457 View Code Duplication
                case TOOL_LINK :
8458
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8459
                    $return .= $this->display_link_form('move', $item_id, $row);
8460
                    break;
8461 View Code Duplication
                case TOOL_HOTPOTATOES :
8462
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8463
                    $return .= $this->display_link_form('move', $item_id, $row);
8464
                    break;
8465 View Code Duplication
                case TOOL_QUIZ :
8466
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8467
                    $return .= $this->display_quiz_form('move', $item_id, $row);
8468
                    break;
8469 View Code Duplication
                case TOOL_STUDENTPUBLICATION :
8470
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8471
                    $return .= $this->display_student_publication_form('move', $item_id, $row);
8472
                    break;
8473
                case TOOL_FORUM :
8474
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8475
                    $return .= $this->display_forum_form('move', $item_id, $row);
8476
                    break;
8477 View Code Duplication
                case TOOL_THREAD :
8478
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8479
                    $return .= $this->display_forum_form('move', $item_id, $row);
8480
                    break;
8481
            }
8482
        }
8483
8484
        return $return;
8485
    }
8486
8487
    /**
8488
     * Displays a basic form on the overview page for changing the item title and the item description.
8489
     * @param string $item_type
8490
     * @param string $title
8491
     * @param array $data
8492
     * @return string
8493
     */
8494
    public function display_item_small_form($item_type, $title = '', $data = array())
8495
    {
8496
        $url = api_get_self() . '?' .api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
8497
        $form = new FormValidator('small_form', 'post', $url);
8498
        $form->addElement('header', $title);
8499
        $form->addElement('text', 'title', get_lang('Title'));
8500
        $form->addButtonSave(get_lang('Save'), 'submit_button');
8501
        $form->addElement('hidden', 'id', $data['id']);
8502
        $form->addElement('hidden', 'parent', $data['parent_item_id']);
8503
        $form->addElement('hidden', 'previous', $data['previous_item_id']);
8504
        $form->setDefaults(array('title' => $data['title']));
8505
8506
        return $form->toHtml();
8507
    }
8508
8509
    /**
8510
     * Return HTML form to allow prerequisites selection
8511
     * @todo use FormValidator
8512
     * @param	integer Item ID
8513
     * @return	string	HTML form
8514
     */
8515
    public function display_item_prerequisites_form($item_id)
8516
    {
8517
        $course_id = api_get_course_int_id();
8518
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8519
        $item_id = intval($item_id);
8520
        /* Current prerequisite */
8521
        $sql = "SELECT * FROM $tbl_lp_item
8522
                WHERE c_id = $course_id AND id = " . $item_id;
8523
        $result = Database::query($sql);
8524
        $row    = Database::fetch_array($result);
8525
        $prerequisiteId = $row['prerequisite'];
8526
        $return = '<legend>';
8527
        $return .= get_lang('AddEditPrerequisites');
8528
        $return .= '</legend>';
8529
        $return .= '<form method="POST">';
8530
        $return .= '<table class="data_table">';
8531
        $return .= '<tr>';
8532
        $return .= '<th height="24">' . get_lang('LearnpathPrerequisites') . '</th>';
8533
        $return .= '<th width="70" >' . get_lang('Minimum') . '</th>';
8534
        $return .= '<th width="70">' . get_lang('Maximum') . '</th>';
8535
        $return .= '</tr>';
8536
8537
        // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
8538
        $return .= '<tr >';
8539
        $return .= '<td colspan="3" class="radio">';
8540
        $return .= '<input checked="checked" id="idNone" name="prerequisites"  style="margin-left:0px; margin-right:10px;" type="radio" />';
8541
        $return .= '<label for="idNone">' . get_lang('None') . '</label>';
8542
        $return .= '</tr>';
8543
8544
        $sql = "SELECT * FROM $tbl_lp_item
8545
                WHERE c_id = $course_id AND lp_id = " . $this->lp_id;
8546
        $result = Database::query($sql);
8547
        $arrLP = array();
8548
8549
        $selectedMinScore = array();
8550
        $selectedMaxScore = array();
8551
        while ($row = Database :: fetch_array($result)) {
8552
            if ($row['id'] == $item_id) {
8553
                $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
8554
                $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
8555
            }
8556
            $arrLP[] = array(
8557
                'id' => $row['id'],
8558
                'item_type' => $row['item_type'],
8559
                'title' => $row['title'],
8560
                'ref' => $row['ref'],
8561
                'description' => $row['description'],
8562
                'parent_item_id' => $row['parent_item_id'],
8563
                'previous_item_id' => $row['previous_item_id'],
8564
                'next_item_id' => $row['next_item_id'],
8565
                'max_score' => $row['max_score'],
8566
                'min_score' => $row['min_score'],
8567
                'mastery_score' => $row['mastery_score'],
8568
                'prerequisite' => $row['prerequisite'],
8569
                'next_item_id' => $row['next_item_id'],
8570
                'display_order' => $row['display_order'],
8571
                'prerequisite_min_score' => $row['prerequisite_min_score'],
8572
                'prerequisite_max_score' => $row['prerequisite_max_score'],
8573
            );
8574
        }
8575
8576
        $this->tree_array($arrLP);
8577
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
8578
        unset($this->arrMenu);
8579
8580
        for ($i = 0; $i < count($arrLP); $i++) {
8581
            $item = $arrLP[$i];
8582
8583
            if ($item['id'] == $item_id) {
8584
                break;
8585
            }
8586
8587
            $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
8588
            $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']]: 0;
8589
8590
            $return .= '<tr>';
8591
            $return .= '<td class="radio"' . (($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '') . '>';
8592
            $return .= '<label for="id' . $item['id'] . '">';
8593
            $return .= '<input' . (in_array($prerequisiteId, array($item['id'], $item['ref'])) ? ' checked="checked" ' : '') . (($item['item_type'] == 'dokeos_module' || $item['item_type'] == 'dokeos_chapter') ? ' disabled="disabled" ' : ' ') . 'id="id' . $item['id'] . '" name="prerequisites" style="margin-left:' . $item['depth'] * 10 . 'px; margin-right:10px;" type="radio" value="' . $item['id'] . '" />';
8594
            $icon_name = str_replace(' ', '', $item['item_type']);
8595
8596
            if (file_exists('../img/lp_' . $icon_name . '.png')) {
8597
                $return .= Display::return_icon('lp_' . $icon_name . '.png');
8598
            } else {
8599
                if (file_exists('../img/lp_' . $icon_name . '.gif')) {
8600
                    $return .= Display::return_icon('lp_' . $icon_name . '.gif');
8601
                } else {
8602
                    $return .= Display::return_icon('folder_document.gif', '', array('style'=>'margin-right:5px;'));
8603
                }
8604
            }
8605
8606
            $return .=  $item['title'] . '</label>';
8607
            $return .= '</td>';
8608
8609
            if ($item['item_type'] == TOOL_QUIZ) {
8610
                // lets update max_score Quiz information depending of the Quiz Advanced properties
8611
                $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
8612
                $tmp_obj_exercice = new Exercise();
8613
                $tmp_obj_exercice->read($tmp_obj_lp_item->path);
8614
                $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
8615
8616
                $tmp_obj_lp_item->update_in_bdd();
8617
                $item['max_score'] = $tmp_obj_lp_item->max_score;
8618
8619
                $return .= '<td class="exercise">';
8620
                $return .= '<input size="4" maxlength="3" name="min_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMinScoreValue. '" />';
8621
                $return .= '</td>';
8622
                $return .= '<td class="exercise">';
8623
                $return .= '<input size="4" maxlength="3" name="max_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMaxScoreValue . '" />';
8624
                $return .= '</td>';
8625
            }
8626
8627
            if ($item['item_type'] == TOOL_HOTPOTATOES) {
8628
                $return .= '<td class="exercise">';
8629
                $return .= '<center><input size="4" maxlength="3" name="min_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMinScoreValue . '" /></center>';
8630
                $return .= '</td>';
8631
                $return .= '<td class="exercise"">';
8632
                $return .= '<center><input size="4" maxlength="3" name="max_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'"  value="'.$selectedMaxScoreValue . '" /></center>';
8633
                $return .= '</td>';
8634
            }
8635
            $return .= '</tr>';
8636
        }
8637
        $return .= '<tr>';
8638
        $return .= '</tr>';
8639
        $return .= '</table>';
8640
        $return .= '<div style="padding-top:3px;">';
8641
        $return .= '<button class="btn btn-primary" name="submit_button" type="submit">' . get_lang('ModifyPrerequisites') . '</button>';
8642
        $return .= '</form>';
8643
8644
        return $return;
8645
    }
8646
8647
    /**
8648
     * Return HTML list to allow prerequisites selection for lp
8649
     * @param	integer Item ID
8650
     * @return	string	HTML form
8651
     */
8652
    public function display_lp_prerequisites_list()
8653
    {
8654
        $course_id = api_get_course_int_id();
8655
        $lp_id = $this->lp_id;
8656
        $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
8657
8658
        // get current prerequisite
8659
        $sql = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $lp_id ";
8660
        $result = Database::query($sql);
8661
        $row = Database :: fetch_array($result);
8662
        $prerequisiteId = $row['prerequisite'];
8663
        $session_id = api_get_session_id();
8664
        $session_condition = api_get_session_condition($session_id);
8665
        $sql = "SELECT * FROM $tbl_lp
8666
                WHERE c_id = $course_id $session_condition
8667
                ORDER BY display_order ";
8668
        $rs = Database::query($sql);
8669
        $return = '';
8670
        $return .= '<select name="prerequisites" class="form-control">';
8671
        $return .= '<option value="0">'.get_lang('None').'</option>';
8672
        if (Database::num_rows($rs) > 0) {
8673
            while ($row = Database::fetch_array($rs)) {
8674
                if ($row['id'] == $lp_id) {
8675
                    continue;
8676
                }
8677
                $return .= '<option value="'.$row['id'].'" '.(($row['id']==$prerequisiteId)?' selected ' : '').'>'.$row['name'].'</option>';
8678
            }
8679
        }
8680
        $return .= '</select>';
8681
8682
        return $return;
8683
    }
8684
8685
    /**
8686
     * Creates a list with all the documents in it
8687
     * @param bool $showInvisibleFiles
8688
     * @return string
8689
     */
8690
    public function get_documents($showInvisibleFiles = false)
8691
    {
8692
        $course_info = api_get_course_info();
8693
        $sessionId = api_get_session_id();
8694
8695
        $document_tree = DocumentManager::get_document_preview(
8696
            $course_info,
8697
            $this->lp_id,
8698
            null,
8699
            $sessionId,
8700
            true,
8701
            null,
8702
            null,
8703
            $showInvisibleFiles,
8704
            true
8705
        );
8706
8707
        return $document_tree;
8708
    }
8709
8710
    /**
8711
     * Creates a list with all the exercises (quiz) in it
8712
     * @return string
8713
     */
8714
    public function get_exercises()
8715
    {
8716
        $course_id = api_get_course_int_id();
8717
8718
        // New for hotpotatoes.
8719
        $uploadPath = DIR_HOTPOTATOES; //defined in main_api
8720
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
8721
        $tbl_quiz = Database :: get_course_table(TABLE_QUIZ_TEST);
8722
8723
        $session_id = api_get_session_id();
8724
        $condition_session = api_get_session_condition($session_id);
8725
8726
        $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
8727
8728
        $activeCondition = " active <> -1 ";
8729
        if ($setting) {
8730
            $activeCondition = " active = 1 ";
8731
        }
8732
8733
        $sql_quiz = "SELECT * FROM $tbl_quiz
8734
                     WHERE c_id = $course_id AND $activeCondition $condition_session
8735
                     ORDER BY title ASC";
8736
8737
        $sql_hot  = "SELECT * FROM $tbl_doc
8738
                     WHERE c_id = $course_id AND path LIKE '" . $uploadPath . "/%/%htm%'  $condition_session
8739
                     ORDER BY id ASC";
8740
8741
        $res_quiz = Database::query($sql_quiz);
8742
        $res_hot  = Database::query($sql_hot);
8743
8744
        $return = '<ul class="lp_resource">';
8745
        $return .= '<li class="lp_resource_element">';
8746
        $return .= Display::return_icon('new_test_small.gif');
8747
        $return .= '<a href="' . api_get_path(WEB_CODE_PATH) . 'exercice/exercise_admin.php?'.api_get_cidreq().'&lp_id=' . $this->lp_id . '">' .
8748
            get_lang('NewExercise') . '</a>';
8749
        $return .= '</li>';
8750
8751
        // Display hotpotatoes
8752
        while ($row_hot = Database :: fetch_array($res_hot)) {
8753
            $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
8754
8755
            $return .= '<a class="moved" href="#">';
8756
            $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8757
            $return .= '</a> ';
8758
8759
            $return .= Display::return_icon('hotpotatoes_s.png');
8760
            $return .= '<a href="' . api_get_self() . '?' . api_get_cidreq().'&action=add_item&type=' . TOOL_HOTPOTATOES . '&file=' . $row_hot['id'] . '&lp_id=' . $this->lp_id . '">'.
8761
                ((!empty ($row_hot['comment'])) ? $row_hot['comment'] : Security :: remove_XSS($row_hot['title'])) . '</a>';
8762
            $return .= '</li>';
8763
        }
8764
8765
        while ($row_quiz = Database :: fetch_array($res_quiz)) {
8766
            $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$row_quiz['title'].'" >';
8767
            $return .= '<a class="moved" href="#">';
8768
            $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8769
            $return .= '</a> ';
8770
            $return .= Display::return_icon('quizz_small.gif', '', array(), ICON_SIZE_TINY);
8771
            $return .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&action=add_item&type=' . TOOL_QUIZ . '&file=' . $row_quiz['id'] . '&lp_id=' . $this->lp_id . '">' .
8772
                Security :: remove_XSS(cut($row_quiz['title'], 80)).
8773
                '</a>';
8774
            $return .= '</li>';
8775
        }
8776
8777
        $return .= '</ul>';
8778
8779
        return $return;
8780
    }
8781
8782
    /**
8783
     * Creates a list with all the links in it
8784
     * @return string
8785
     */
8786
    public function get_links()
8787
    {
8788
        $selfUrl = api_get_self();
8789
        $courseIdReq = api_get_cidreq();
8790
        $course = api_get_course_info();
8791
        $course_id = $course['real_id'];
8792
        $tbl_link = Database::get_course_table(TABLE_LINK);
8793
        $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
8794
        $moveEverywhereIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8795
8796
        $session_id = api_get_session_id();
8797
        $condition_session = api_get_session_condition($session_id, true, null, "link.session_id");
8798
8799
        $sql = "SELECT link.id as link_id,
8800
                    link.title as link_title,
8801
                    link.category_id as category_id,
8802
                    link_category.category_title as category_title
8803
                FROM $tbl_link as link
8804
                LEFT JOIN $linkCategoryTable as link_category
8805
                ON link.category_id = link_category.id
8806
                WHERE link.c_id = ".$course_id." $condition_session
8807
                ORDER BY link_category.category_title ASC, link.title ASC";
8808
        $links = Database::query($sql);
8809
8810
        $categorizedLinks = array();
8811
        $categories = array();
8812
8813
        while ($link = Database :: fetch_array($links)) {
8814
            if (!$link['category_id']) {
8815
                $link['category_title'] = get_lang('Uncategorized');
8816
            }
8817
            $categories[$link['category_id']] = $link['category_title'];
8818
            $categorizedLinks[$link['category_id']][$link['link_id']] = $link['link_title'];
8819
        }
8820
8821
        $linksHtmlCode =
8822
            '<script>
8823
            function toggle_tool(tool, id){
8824
                if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
8825
                    document.getElementById(tool+"_"+id+"_content").style.display = "block";
8826
                    document.getElementById(tool+"_"+id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
8827
                } else {
8828
                    document.getElementById(tool+"_"+id+"_content").style.display = "none";
8829
                    document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
8830
                }
8831
            }
8832
        </script>
8833
8834
        <ul class="lp_resource">
8835
            <li class="lp_resource_element">
8836
                '.Display::return_icon('linksnew.gif').'
8837
                <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
8838
                get_lang('LinkAdd').'
8839
                </a>
8840
            </li>';
8841
8842
        foreach ($categorizedLinks as $categoryId => $links) {
8843
            $linkNodes = null;
8844
            foreach ($links as $key => $title) {
8845
                if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2)  {
8846
                    $linkNodes .=
8847
                        '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
8848
                        <a class="moved" href="#">'.
8849
                        $moveEverywhereIcon.
8850
                        '</a>
8851
                        '.Display::return_icon('lp_link.png').'
8852
                        <a href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
8853
                        TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
8854
                        Security::remove_XSS($title).
8855
                        '</a>
8856
                    </li>';
8857
                }
8858
            }
8859
            $linksHtmlCode .=
8860
                '<li>
8861
                <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
8862
                    <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
8863
                    align="absbottom" />
8864
                </a>
8865
                <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
8866
            </li>
8867
            <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
8868
        }
8869
        $linksHtmlCode .= '</ul>';
8870
8871
        return $linksHtmlCode;
8872
    }
8873
8874
    /**
8875
     * Creates a list with all the student publications in it
8876
     * @return unknown
8877
     */
8878
    public function get_student_publications()
8879
    {
8880
        $return = '<div class="lp_resource" >';
8881
        $return .= '<div class="lp_resource_element">';
8882
        $return .= Display::return_icon('works_small.gif', '', array(), ICON_SIZE_TINY);
8883
        $return .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&action=add_item&type=' . TOOL_STUDENTPUBLICATION . '&lp_id=' . $this->lp_id . '">' . get_lang('AddAssignmentPage') . '</a>';
8884
        $return .= '</div>';
8885
        $return .= '</div>';
8886
        return $return;
8887
    }
8888
8889
    /**
8890
     * Creates a list with all the forums in it
8891
     * @return string
8892
     */
8893
    public function get_forums()
8894
    {
8895
        require_once '../forum/forumfunction.inc.php';
8896
        require_once '../forum/forumconfig.inc.php';
8897
8898
        $a_forums = get_forums();
8899
        $return = '<ul class="lp_resource">';
8900
8901
        //First add link
8902
        $return .= '<li class="lp_resource_element">';
8903
        $return .= Display::return_icon('forum_new_small.gif');
8904
        $return .= Display::url(
8905
            get_lang('CreateANewForum'),
8906
            api_get_path(WEB_CODE_PATH) . 'forum/index.php?' . api_get_cidreq() . '&' . http_build_query([
8907
                'action' => 'add',
8908
                'content' => 'forum',
8909
                'lp_id' => $this->lp_id
8910
            ]),
8911
            ['title' => get_lang('CreateANewForum')]
8912
        );
8913
        $return .= '</li>';
8914
8915
        $return .= '<script>
8916
                    function toggle_forum(forum_id){
8917
                        if(document.getElementById("forum_"+forum_id+"_content").style.display == "none"){
8918
                            document.getElementById("forum_"+forum_id+"_content").style.display = "block";
8919
                            document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
8920
                        } else {
8921
                            document.getElementById("forum_"+forum_id+"_content").style.display = "none";
8922
                            document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('add.gif').'";
8923
                        }
8924
                    }
8925
                </script>';
8926
8927
        foreach ($a_forums as $forum) {
8928
            if (!empty($forum['forum_id'])) {
8929
                $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
8930
                $return .= '<a class="moved" href="#">';
8931
                $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8932
                $return .= ' </a>';
8933
                $return .= Display::return_icon('lp_forum.png', '', array(), ICON_SIZE_TINY);
8934
                $return .= '<a style="cursor:hand" onclick="javascript: toggle_forum(' . $forum['forum_id'] . ')" style="vertical-align:middle">
8935
                                <img src="' . Display::returnIconPath('add.gif').'" id="forum_' . $forum['forum_id'] . '_opener" align="absbottom" />
8936
                            </a>
8937
                            <a href="' . api_get_self() . '?'.api_get_cidreq().'&action=add_item&type=' . TOOL_FORUM . '&forum_id=' . $forum['forum_id'] . '&lp_id=' . $this->lp_id . '" style="vertical-align:middle">' .
8938
                    Security :: remove_XSS($forum['forum_title']) . '</a>';
8939
8940
                $return .= '</li>';
8941
8942
                $return .= '<div style="display:none" id="forum_' . $forum['forum_id'] . '_content">';
8943
                $a_threads = get_threads($forum['forum_id']);
8944
                if (is_array($a_threads)) {
8945
                    foreach ($a_threads as $thread) {
8946
                        $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
8947
                        $return .= '&nbsp;<a class="moved" href="#">';
8948
                        $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8949
                        $return .= ' </a>';
8950
                        $return .= Display::return_icon('forumthread.png', get_lang('Thread'), array(), ICON_SIZE_TINY);
8951
                        $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type=' . TOOL_THREAD . '&thread_id=' . $thread['thread_id'] . '&lp_id=' . $this->lp_id . '">' .
8952
                            Security :: remove_XSS($thread['thread_title']) . '</a>';
8953
                        $return .= '</li>';
8954
                    }
8955
                }
8956
                $return .= '</div>';
8957
            }
8958
        }
8959
        $return .= '</ul>';
8960
8961
        return $return;
8962
    }
8963
8964
    /**
8965
     * // TODO: The output encoding should be equal to the system encoding.
8966
     *
8967
     * Exports the learning path as a SCORM package. This is the main function that
8968
     * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
8969
     * whole thing and returns the zip.
8970
     *
8971
     * This method needs to be called in PHP5, as it will fail with non-adequate
8972
     * XML package (like the ones for PHP4), and it is *not* a static method, so
8973
     * you need to call it on a learnpath object.
8974
     * @TODO The method might be redefined later on in the scorm class itself to avoid
8975
     * creating a SCORM structure if there is one already. However, if the initial SCORM
8976
     * path has been modified, it should use the generic method here below.
8977
     * @TODO link this function with the export_lp() function in the same class
8978
     * @param	string	Optional name of zip file. If none, title of learnpath is
8979
     * 					domesticated and trailed with ".zip"
8980
     * @return	string	Returns the zip package string, or null if error
8981
     */
8982
    public function scorm_export()
8983
    {
8984
        $_course = api_get_course_info();
8985
        $course_id = $_course['real_id'];
8986
8987
        // Remove memory and time limits as much as possible as this might be a long process...
8988
        if (function_exists('ini_set')) {
8989
            api_set_memory_limit('128M');
8990
            ini_set('max_execution_time', 600);
8991
        }
8992
8993
        // Create the zip handler (this will remain available throughout the method).
8994
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
8995
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
8996
        $temp_dir_short = uniqid();
8997
        $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
8998
        $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
8999
        $zip_folder = new PclZip($temp_zip_file);
9000
        $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
9001
        $root_path = $main_path = api_get_path(SYS_PATH);
9002
        $files_cleanup = array();
9003
9004
        // Place to temporarily stash the zip file.
9005
        // create the temp dir if it doesn't exist
9006
        // or do a cleanup before creating the zip file.
9007
        if (!is_dir($temp_zip_dir)) {
9008
            mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
9009
        } else {
9010
            // Cleanup: Check the temp dir for old files and delete them.
9011
            $handle = opendir($temp_zip_dir);
9012
            while (false !== ($file = readdir($handle))) {
9013
                if ($file != '.' && $file != '..') {
9014
                    unlink("$temp_zip_dir/$file");
9015
                }
9016
            }
9017
            closedir($handle);
9018
        }
9019
        $zip_files = $zip_files_abs = $zip_files_dist = array();
9020
        if (is_dir($current_course_path.'/scorm/'.$this->path) && is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')) {
9021
            // Remove the possible . at the end of the path.
9022
            $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
9023
            $dest_path_to_scorm_folder = str_replace('//','/',$temp_zip_dir.'/scorm/'.$dest_path_to_lp);
9024
            mkdir($dest_path_to_scorm_folder, api_get_permissions_for_new_directories(), true);
9025
            $zip_files_dist = copyr($current_course_path.'/scorm/'.$this->path, $dest_path_to_scorm_folder, array('imsmanifest'), $zip_files);
9026
        }
9027
9028
        // Build a dummy imsmanifest structure.
9029
        // Do not add to the zip yet (we still need it).
9030
        // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
9031
        // Aggregation Model official document, section "2.3 Content Packaging".
9032
        // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
9033
        $xmldoc = new DOMDocument('1.0');
9034
        $root = $xmldoc->createElement('manifest');
9035
        $root->setAttribute('identifier', 'SingleCourseManifest');
9036
        $root->setAttribute('version', '1.1');
9037
        $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
9038
        $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
9039
        $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
9040
        $root->setAttribute('xsi:schemaLocation', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd');
9041
        // Build mandatory sub-root container elements.
9042
        $metadata = $xmldoc->createElement('metadata');
9043
        $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
9044
        $metadata->appendChild($md_schema);
9045
        $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
9046
        $metadata->appendChild($md_schemaversion);
9047
        $root->appendChild($metadata);
9048
9049
        $organizations = $xmldoc->createElement('organizations');
9050
        $resources = $xmldoc->createElement('resources');
9051
9052
        // Build the only organization we will use in building our learnpaths.
9053
        $organizations->setAttribute('default', 'chamilo_scorm_export');
9054
        $organization = $xmldoc->createElement('organization');
9055
        $organization->setAttribute('identifier', 'chamilo_scorm_export');
9056
        // To set the title of the SCORM entity (=organization), we take the name given
9057
        // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
9058
        // learning path charset) as it is the encoding that defines how it is stored
9059
        // in the database. Then we convert it to HTML entities again as the "&" character
9060
        // alone is not authorized in XML (must be &amp;).
9061
        // The title is then decoded twice when extracting (see scorm::parse_manifest).
9062
        $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
9063
        $organization->appendChild($org_title);
9064
9065
        $folder_name = 'document';
9066
9067
        // Removes the learning_path/scorm_folder path when exporting see #4841
9068
        $path_to_remove = null;
9069
        $result = $this->generate_lp_folder($_course);
9070
9071
        if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
9072
            $path_to_remove = 'document'.$result['dir'];
9073
            $path_to_replace = $folder_name.'/';
9074
        }
9075
9076
        //Fixes chamilo scorm exports
9077
        if ($this->ref == 'chamilo_scorm_export') {
9078
            $path_to_remove = 'scorm/'.$this->path.'/document/';
9079
        }
9080
9081
        // For each element, add it to the imsmanifest structure, then add it to the zip.
9082
        // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
9083
        $link_updates = array();
9084
        $links_to_create = array();
9085
        foreach ($this->items as $index => $item) {
9086
            if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) {
9087
                // Get included documents from this item.
9088
                if ($item->type == 'sco') {
9089
                    $inc_docs = $item->get_resources_from_source(
9090
                        null,
9091
                        api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/' . 'scorm/' . $this->path . '/' . $item->get_path()
9092
                    );
9093
                } else {
9094
                    $inc_docs = $item->get_resources_from_source();
9095
                }
9096
                // Give a child element <item> to the <organization> element.
9097
                $my_item_id = $item->get_id();
9098
                $my_item = $xmldoc->createElement('item');
9099
                $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
9100
                $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
9101
                $my_item->setAttribute('isvisible', 'true');
9102
                // Give a child element <title> to the <item> element.
9103
                $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9104
                $my_item->appendChild($my_title);
9105
                // Give a child element <adlcp:prerequisites> to the <item> element.
9106
                $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $this->get_scorm_prereq_string($my_item_id));
9107
                $my_prereqs->setAttribute('type', 'aicc_script');
9108
                $my_item->appendChild($my_prereqs);
9109
                // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
9110
                //$xmldoc->createElement('adlcp:maxtimeallowed','');
9111
                // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
9112
                //$xmldoc->createElement('adlcp:timelimitaction','');
9113
                // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
9114
                //$xmldoc->createElement('adlcp:datafromlms','');
9115
                // Give a child element <adlcp:masteryscore> to the <item> element.
9116
                $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9117
                $my_item->appendChild($my_masteryscore);
9118
9119
                // Attach this item to the organization element or hits parent if there is one.
9120
                if (!empty($item->parent) && $item->parent != 0) {
9121
                    $children = $organization->childNodes;
9122
                    $possible_parent = &$this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
9123
                    if (is_object($possible_parent)) {
9124
                        $possible_parent->appendChild($my_item);
9125 View Code Duplication
                    } else {
9126
                        if ($this->debug > 0) { error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found'); }
9127
                    }
9128
                } else {
9129
                    if ($this->debug > 0) { error_log('No parent'); }
9130
                    $organization->appendChild($my_item);
9131
                }
9132
9133
                // Get the path of the file(s) from the course directory root.
9134
                $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
9135
9136
                if (!empty($path_to_remove)) {
9137
                    //From docs
9138
                    $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
9139
9140
                    //From quiz
9141
                    if ($this->ref == 'chamilo_scorm_export') {
9142
                        $path_to_remove = 'scorm/'.$this->path.'/';
9143
                        $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
9144
                    }
9145
                } else {
9146
                    $my_xml_file_path = $my_file_path;
9147
                }
9148
9149
                $my_sub_dir = dirname($my_file_path);
9150
                $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9151
                $my_xml_sub_dir = $my_sub_dir;
9152
                // Give a <resource> child to the <resources> element
9153
                $my_resource = $xmldoc->createElement('resource');
9154
                $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9155
                $my_resource->setAttribute('type', 'webcontent');
9156
                $my_resource->setAttribute('href', $my_xml_file_path);
9157
                // adlcp:scormtype can be either 'sco' or 'asset'.
9158
                if ($item->type == 'sco') {
9159
                    $my_resource->setAttribute('adlcp:scormtype', 'sco');
9160
                } else {
9161
                    $my_resource->setAttribute('adlcp:scormtype', 'asset');
9162
                }
9163
                // xml:base is the base directory to find the files declared in this resource.
9164
                $my_resource->setAttribute('xml:base', '');
9165
                // Give a <file> child to the <resource> element.
9166
                $my_file = $xmldoc->createElement('file');
9167
                $my_file->setAttribute('href', $my_xml_file_path);
9168
                $my_resource->appendChild($my_file);
9169
9170
                // Dependency to other files - not yet supported.
9171
                $i = 1;
9172
                foreach ($inc_docs as $doc_info) {
9173
                    if (count($doc_info) < 1 || empty($doc_info[0])) { continue; }
9174
                    $my_dep = $xmldoc->createElement('resource');
9175
                    $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
9176
                    $my_dep->setAttribute('identifier', $res_id);
9177
                    $my_dep->setAttribute('type', 'webcontent');
9178
                    $my_dep->setAttribute('adlcp:scormtype', 'asset');
9179
                    $my_dep_file = $xmldoc->createElement('file');
9180
                    // Check type of URL.
9181
                    //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2], 0);
9182
                    if ($doc_info[1] == 'remote') {
9183
                        // Remote file. Save url as is.
9184
                        $my_dep_file->setAttribute('href', $doc_info[0]);
9185
                        $my_dep->setAttribute('xml:base', '');
9186
                    } elseif ($doc_info[1] == 'local') {
9187
                        switch ($doc_info[2]) {
9188
                            case 'url': // Local URL - save path as url for now, don't zip file.
9189
                                $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9190
                                $current_dir = dirname($abs_path);
9191
                                $current_dir = str_replace('\\', '/', $current_dir);
9192
                                $file_path = realpath($abs_path);
9193
                                $file_path = str_replace('\\', '/', $file_path);
9194
                                $my_dep_file->setAttribute('href', $file_path);
9195
                                $my_dep->setAttribute('xml:base', '');
9196
                                if (strstr($file_path, $main_path) !== false) {
9197
                                    // The calculated real path is really inside Chamilo's root path.
9198
                                    // Reduce file path to what's under the DocumentRoot.
9199
                                    $file_path = substr($file_path, strlen($root_path) - 1);
9200
                                    //echo $file_path;echo '<br /><br />';
9201
                                    //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
9202
                                    $zip_files_abs[] = $file_path;
9203
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9204
                                    $my_dep_file->setAttribute('href', $file_path);
9205
                                    $my_dep->setAttribute('xml:base', '');
9206
                                } elseif (empty($file_path)) {
9207
                                    /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9208
                                    if (strpos($document_root, -1) == '/') {
9209
                                        $document_root = substr(0, -1, $document_root);
9210
                                    }*/
9211
                                    $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
9212
                                    $file_path = str_replace('//', '/', $file_path);
9213
                                    if (file_exists($file_path)) {
9214
                                        $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9215
                                        $zip_files[] = $my_sub_dir.'/'.$file_path;
9216
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9217
                                        $my_dep_file->setAttribute('href', $file_path);
9218
                                        $my_dep->setAttribute('xml:base', '');
9219
                                    }
9220
                                }
9221
                                break;
9222
                            case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
9223
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9224
                                $my_dep->setAttribute('xml:base', '');
9225
9226
                                // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
9227
                                // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
9228
                                $abs_img_path_without_subdir = $doc_info[0];
9229
                                $relp = api_get_path(REL_PATH); // The url-append config param.
9230
                                $pos = strpos($abs_img_path_without_subdir, $relp);
9231
                                if ($pos === 0) {
9232
                                    $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir, strlen($relp));
9233
                                }
9234
                                $file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
9235
                                $file_path = str_replace('\\', '/', $file_path);
9236
                                $file_path = str_replace('//', '/', $file_path);
9237
9238
                                // Prepare the current directory path (until just under 'document') with a trailing slash.
9239
                                $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
9240
                                // Check if the current document is in that path.
9241
                                if (strstr($file_path, $cur_path) !== false) {
9242
                                    // The document is in that path, now get the relative path
9243
                                    // to the containing document.
9244
                                    $orig_file_path = dirname($cur_path.$my_file_path).'/';
9245
                                    $orig_file_path = str_replace('\\', '/', $orig_file_path);
9246
                                    $relative_path = '';
9247
                                    if (strstr($file_path, $cur_path) !== false) {
9248
                                        //$relative_path = substr($file_path, strlen($orig_file_path));
9249
                                        $relative_path = str_replace($cur_path, '', $file_path);
9250
                                        $file_path = substr($file_path, strlen($cur_path));
9251
                                    } else {
9252
                                        // This case is still a problem as it's difficult to calculate a relative path easily
9253
                                        // might still generate wrong links.
9254
                                        //$file_path = substr($file_path,strlen($cur_path));
9255
                                        // Calculate the directory path to the current file (without trailing slash).
9256
                                        $my_relative_path = dirname($file_path);
9257
                                        $my_relative_path = str_replace('\\', '/', $my_relative_path);
9258
                                        $my_relative_file = basename($file_path);
9259
                                        // Calculate the directory path to the containing file (without trailing slash).
9260
                                        $my_orig_file_path = substr($orig_file_path, 0, -1);
9261
                                        $dotdot = '';
9262
                                        $subdir = '';
9263
                                        while (strstr($my_relative_path, $my_orig_file_path) === false && (strlen($my_orig_file_path) > 1) && (strlen($my_relative_path) > 1)) {
9264
                                            $my_relative_path2 = dirname($my_relative_path);
9265
                                            $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
9266
                                            $my_orig_file_path = dirname($my_orig_file_path);
9267
                                            $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
9268
                                            $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'.$subdir;
9269
                                            $dotdot += '../';
9270
                                            $my_relative_path = $my_relative_path2;
9271
                                        }
9272
                                        $relative_path = $dotdot.$subdir.$my_relative_file;
9273
                                    }
9274
                                    // Put the current document in the zip (this array is the array
9275
                                    // that will manage documents already in the course folder - relative).
9276
                                    $zip_files[] = $file_path;
9277
                                    // Update the links to the current document in the containing document (make them relative).
9278
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $relative_path);
9279
                                    $my_dep_file->setAttribute('href', $file_path);
9280
                                    $my_dep->setAttribute('xml:base', '');
9281
                                } elseif (strstr($file_path, $main_path) !== false) {
9282
                                    // The calculated real path is really inside Chamilo's root path.
9283
                                    // Reduce file path to what's under the DocumentRoot.
9284
                                    $file_path = substr($file_path, strlen($root_path));
9285
                                    //echo $file_path;echo '<br /><br />';
9286
                                    //error_log('Reduced path: '.$file_path, 0);
9287
                                    $zip_files_abs[] = $file_path;
9288
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9289
                                    $my_dep_file->setAttribute('href', 'document/'.$file_path);
9290
                                    $my_dep->setAttribute('xml:base', '');
9291
                                } elseif (empty($file_path)) {
9292
                                    /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9293
                                    if(strpos($document_root,-1) == '/') {
9294
                                        $document_root = substr(0, -1, $document_root);
9295
                                    }*/
9296
                                    $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
9297
                                    $file_path = str_replace('//', '/', $file_path);
9298
9299
                                    $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9300
                                    $current_dir = dirname($abs_path);
9301
                                    $current_dir = str_replace('\\', '/', $current_dir);
9302
9303
                                    if (file_exists($file_path)) {
9304
                                        $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9305
                                        $zip_files[] = $my_sub_dir.'/'.$file_path;
9306
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9307
                                        $my_dep_file->setAttribute('href','document/'.$file_path);
9308
                                        $my_dep->setAttribute('xml:base', '');
9309
                                    }
9310
                                }
9311
                                break;
9312
                            case 'rel':
9313
                                // Path relative to the current document.
9314
                                // Save xml:base as current document's directory and save file in zip as subdir.file_path
9315
                                if (substr($doc_info[0], 0, 2) == '..') {
9316
                                    // Relative path going up.
9317
                                    $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9318
                                    $current_dir = str_replace('\\', '/', $current_dir);
9319
                                    $file_path = realpath($current_dir.$doc_info[0]);
9320
                                    $file_path = str_replace('\\', '/', $file_path);
9321
9322
                                    //error_log($file_path.' <-> '.$main_path,0);
9323
                                    if (strstr($file_path, $main_path) !== false) {
9324
                                        // The calculated real path is really inside Chamilo's root path.
9325
                                        // Reduce file path to what's under the DocumentRoot.
9326
                                        $file_path = substr($file_path, strlen($root_path));
9327
                                        //error_log('Reduced path: '.$file_path, 0);
9328
                                        $zip_files_abs[] = $file_path;
9329
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9330
                                        $my_dep_file->setAttribute('href', 'document/'.$file_path);
9331
                                        $my_dep->setAttribute('xml:base', '');
9332
                                    }
9333 View Code Duplication
                                } else {
9334
                                    $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
9335
                                    $my_dep_file->setAttribute('href', $doc_info[0]);
9336
                                    $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
9337
                                }
9338
                                break;
9339
                            default:
9340
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9341
                                $my_dep->setAttribute('xml:base', '');
9342
                                break;
9343
                        }
9344
                    }
9345
                    $my_dep->appendChild($my_dep_file);
9346
                    $resources->appendChild($my_dep);
9347
                    $dependency = $xmldoc->createElement('dependency');
9348
                    $dependency->setAttribute('identifierref', $res_id);
9349
                    $my_resource->appendChild($dependency);
9350
                    $i++;
9351
                }
9352
                $resources->appendChild($my_resource);
9353
                $zip_files[] = $my_file_path;
9354
            } else {
9355
9356
                // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
9357
                switch ($item->type) {
9358
                    case TOOL_LINK:
9359
                        $my_item = $xmldoc->createElement('item');
9360
                        $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
9361
                        $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
9362
                        $my_item->setAttribute('isvisible', 'true');
9363
                        // Give a child element <title> to the <item> element.
9364
                        $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9365
                        $my_item->appendChild($my_title);
9366
                        // Give a child element <adlcp:prerequisites> to the <item> element.
9367
                        $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
9368
                        $my_prereqs->setAttribute('type', 'aicc_script');
9369
                        $my_item->appendChild($my_prereqs);
9370
                        // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
9371
                        //$xmldoc->createElement('adlcp:maxtimeallowed', '');
9372
                        // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
9373
                        //$xmldoc->createElement('adlcp:timelimitaction', '');
9374
                        // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
9375
                        //$xmldoc->createElement('adlcp:datafromlms', '');
9376
                        // Give a child element <adlcp:masteryscore> to the <item> element.
9377
                        $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9378
                        $my_item->appendChild($my_masteryscore);
9379
9380
                        // Attach this item to the organization element or its parent if there is one.
9381 View Code Duplication
                        if (!empty($item->parent) && $item->parent != 0) {
9382
                            $children = $organization->childNodes;
9383
                            for ($i = 0; $i < $children->length; $i++) {
9384
                                $item_temp = $children->item($i);
9385
                                if ($item_temp -> nodeName == 'item') {
9386
                                    if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
9387
                                        $item_temp -> appendChild($my_item);
9388
                                    }
9389
                                }
9390
                            }
9391
                        } else {
9392
                            $organization->appendChild($my_item);
9393
                        }
9394
9395
                        $my_file_path = 'link_'.$item->get_id().'.html';
9396
                        $sql = 'SELECT url, title FROM '.Database :: get_course_table(TABLE_LINK).'
9397
                                WHERE c_id = '.$course_id.' AND id='.$item->path;
9398
                        $rs = Database::query($sql);
9399
                        if ($link = Database :: fetch_array($rs)) {
9400
                            $url = $link['url'];
9401
                            $title = stripslashes($link['title']);
9402
                            $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url);
9403
                            $my_xml_file_path = $my_file_path;
9404
                            $my_sub_dir = dirname($my_file_path);
9405
                            $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9406
                            $my_xml_sub_dir = $my_sub_dir;
9407
                            // Give a <resource> child to the <resources> element.
9408
                            $my_resource = $xmldoc->createElement('resource');
9409
                            $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9410
                            $my_resource->setAttribute('type', 'webcontent');
9411
                            $my_resource->setAttribute('href', $my_xml_file_path);
9412
                            // adlcp:scormtype can be either 'sco' or 'asset'.
9413
                            $my_resource->setAttribute('adlcp:scormtype', 'asset');
9414
                            // xml:base is the base directory to find the files declared in this resource.
9415
                            $my_resource->setAttribute('xml:base', '');
9416
                            // give a <file> child to the <resource> element.
9417
                            $my_file = $xmldoc->createElement('file');
9418
                            $my_file->setAttribute('href', $my_xml_file_path);
9419
                            $my_resource->appendChild($my_file);
9420
                            $resources->appendChild($my_resource);
9421
                        }
9422
                        break;
9423
                    case TOOL_QUIZ:
9424
                        $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
9425
                        $exe = new Exercise();
9426
                        $exe->read($exe_id);
9427
                        $my_item = $xmldoc->createElement('item');
9428
                        $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
9429
                        $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
9430
                        $my_item->setAttribute('isvisible', 'true');
9431
                        // Give a child element <title> to the <item> element.
9432
                        $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9433
                        $my_item->appendChild($my_title);
9434
                        $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
9435
                        //$my_item->appendChild($my_max_score);
9436
                        // Give a child element <adlcp:prerequisites> to the <item> element.
9437
                        $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
9438
                        $my_prereqs->setAttribute('type','aicc_script');
9439
                        $my_item->appendChild($my_prereqs);
9440
                        // Give a child element <adlcp:masteryscore> to the <item> element.
9441
                        $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9442
                        $my_item->appendChild($my_masteryscore);
9443
9444
                        // Attach this item to the organization element or hits parent if there is one.
9445 View Code Duplication
                        if (!empty($item->parent) && $item->parent != 0) {
9446
                            $children = $organization->childNodes;
9447
                            for ($i = 0; $i < $children->length; $i++) {
9448
                                $item_temp = $children->item($i);
9449
                                if ($item_temp -> nodeName == 'item') {
9450
                                    if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
9451
                                        $item_temp -> appendChild($my_item);
9452
                                    }
9453
                                }
9454
                            }
9455
                        } else {
9456
                            $organization->appendChild($my_item);
9457
                        }
9458
9459
                        // Get the path of the file(s) from the course directory root
9460
                        //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
9461
                        $my_file_path = 'quiz_'.$item->get_id().'.html';
9462
                        // Write the contents of the exported exercise into a (big) html file
9463
                        // to later pack it into the exported SCORM. The file will be removed afterwards.
9464
                        $contents = ScormSection::export_exercise_to_scorm($exe_id, true);
9465
                        $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
9466
                        $res = file_put_contents($tmp_file_path, $contents);
9467
                        if ($res === false) { error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0); }
9468
                        $files_cleanup[] = $tmp_file_path;
9469
                        //error_log($tmp_path); die();
9470
                        //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_QUOTES, 'UTF-8');
9471
                        $my_xml_file_path = $my_file_path;
9472
                        $my_sub_dir = dirname($my_file_path);
9473
                        $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9474
                        //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_QUOTES, 'UTF-8');
9475
                        $my_xml_sub_dir = $my_sub_dir;
9476
                        // Give a <resource> child to the <resources> element.
9477
                        $my_resource = $xmldoc->createElement('resource');
9478
                        $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9479
                        $my_resource->setAttribute('type', 'webcontent');
9480
                        $my_resource->setAttribute('href', $my_xml_file_path);
9481
                        // adlcp:scormtype can be either 'sco' or 'asset'.
9482
                        $my_resource->setAttribute('adlcp:scormtype', 'sco');
9483
                        // xml:base is the base directory to find the files declared in this resource.
9484
                        $my_resource->setAttribute('xml:base', '');
9485
                        // Give a <file> child to the <resource> element.
9486
                        $my_file = $xmldoc->createElement('file');
9487
                        $my_file->setAttribute('href', $my_xml_file_path);
9488
                        $my_resource->appendChild($my_file);
9489
9490
                        // Get included docs.
9491
                        $inc_docs = $item->get_resources_from_source(null,$tmp_file_path);
9492
                        // Dependency to other files - not yet supported.
9493
                        $i = 1;
9494
                        foreach ($inc_docs as $doc_info) {
9495
                            if (count($doc_info) < 1 || empty($doc_info[0])) { continue; }
9496
                            $my_dep = $xmldoc->createElement('resource');
9497
                            $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
9498
                            $my_dep->setAttribute('identifier', $res_id);
9499
                            $my_dep->setAttribute('type', 'webcontent');
9500
                            $my_dep->setAttribute('adlcp:scormtype', 'asset');
9501
                            $my_dep_file = $xmldoc->createElement('file');
9502
                            // Check type of URL.
9503
                            if ($doc_info[1] == 'remote') {
9504
                                // Remote file. Save url as is.
9505
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9506
                                $my_dep->setAttribute('xml:base', '');
9507
                            } elseif ($doc_info[1] == 'local') {
9508
                                switch ($doc_info[2]) {
9509
                                    case 'url': // Local URL - save path as url for now, don't zip file.
9510
                                        // Save file but as local file (retrieve from URL).
9511
                                        $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9512
                                        $current_dir = dirname($abs_path);
9513
                                        $current_dir = str_replace('\\', '/', $current_dir);
9514
                                        $file_path = realpath($abs_path);
9515
                                        $file_path = str_replace('\\', '/', $file_path);
9516
                                        $my_dep_file->setAttribute('href', 'document/'.$file_path);
9517
                                        $my_dep->setAttribute('xml:base', '');
9518 View Code Duplication
                                        if (strstr($file_path, $main_path) !== false) {
9519
                                            // The calculated real path is really inside the chamilo root path.
9520
                                            // Reduce file path to what's under the DocumentRoot.
9521
                                            $file_path = substr($file_path, strlen($root_path));
9522
                                            //echo $file_path;echo '<br /><br />';
9523
                                            //error_log('Reduced path: '.$file_path, 0);
9524
                                            $zip_files_abs[] = $file_path;
9525
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
9526
                                            $my_dep_file->setAttribute('href', 'document/'.$file_path);
9527
                                            $my_dep->setAttribute('xml:base', '');
9528
                                        } elseif (empty($file_path)) {
9529
                                            /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
9530
                                            if (strpos($document_root,-1) == '/') {
9531
                                                $document_root = substr(0, -1, $document_root);
9532
                                            }*/
9533
                                            $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
9534
                                            $file_path = str_replace('//', '/', $file_path);
9535
                                            if (file_exists($file_path)) {
9536
                                                $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9537
                                                $zip_files[] = $my_sub_dir.'/'.$file_path;
9538
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
9539
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9540
                                                $my_dep->setAttribute('xml:base', '');
9541
                                            }
9542
                                        }
9543
                                        break;
9544
                                    case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
9545
                                        $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9546
                                        $current_dir = str_replace('\\', '/', $current_dir);
9547
                                        $file_path = realpath($doc_info[0]);
9548
                                        $file_path = str_replace('\\', '/', $file_path);
9549
                                        $my_dep_file->setAttribute('href', $file_path);
9550
                                        $my_dep->setAttribute('xml:base', '');
9551
9552 View Code Duplication
                                        if (strstr($file_path,$main_path) !== false) {
9553
                                            // The calculated real path is really inside the chamilo root path.
9554
                                            // Reduce file path to what's under the DocumentRoot.
9555
                                            $file_path = substr($file_path, strlen($root_path));
9556
                                            //echo $file_path;echo '<br /><br />';
9557
                                            //error_log('Reduced path: '.$file_path, 0);
9558
                                            $zip_files_abs[] = $file_path;
9559
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9560
                                            $my_dep_file->setAttribute('href', 'document/'.$file_path);
9561
                                            $my_dep->setAttribute('xml:base', '');
9562
                                        } elseif (empty($file_path)) {
9563
                                            /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9564
                                            if (strpos($document_root,-1) == '/') {
9565
                                                $document_root = substr(0, -1, $document_root);
9566
                                            }*/
9567
                                            $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
9568
                                            $file_path = str_replace('//', '/', $file_path);
9569
                                            if (file_exists($file_path)) {
9570
                                                $file_path = substr($file_path,strlen($current_dir)); // We get the relative path.
9571
                                                $zip_files[] = $my_sub_dir.'/'.$file_path;
9572
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9573
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9574
                                                $my_dep->setAttribute('xml:base', '');
9575
                                            }
9576
                                        }
9577
                                        break;
9578
                                    case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
9579
                                        if (substr($doc_info[0], 0, 2) == '..') {
9580
                                            // Relative path going up.
9581
                                            $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9582
                                            $current_dir = str_replace('\\', '/', $current_dir);
9583
                                            $file_path = realpath($current_dir.$doc_info[0]);
9584
                                            $file_path = str_replace('\\', '/', $file_path);
9585
                                            //error_log($file_path.' <-> '.$main_path, 0);
9586
                                            if (strstr($file_path, $main_path) !== false) {
9587
                                                // The calculated real path is really inside Chamilo's root path.
9588
                                                // Reduce file path to what's under the DocumentRoot.
9589
9590
                                                $file_path = substr($file_path, strlen($root_path));
9591
                                                $file_path_dest = $file_path;
9592
9593
                                                // File path is courses/CHAMILO/document/....
9594
                                                $info_file_path = explode('/', $file_path);
9595
                                                if ($info_file_path[0] == 'courses') { // Add character "/" in file path.
9596
                                                    $file_path_dest = 'document/'.$file_path;
9597
                                                }
9598
9599
                                                //error_log('Reduced path: '.$file_path, 0);
9600
                                                $zip_files_abs[] = $file_path;
9601
9602
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path_dest);
9603
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9604
                                                $my_dep->setAttribute('xml:base', '');
9605
                                            }
9606 View Code Duplication
                                        } else {
9607
                                            $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
9608
                                            $my_dep_file->setAttribute('href', $doc_info[0]);
9609
                                            $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
9610
                                        }
9611
                                        break;
9612
                                    default:
9613
                                        $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
9614
                                        $my_dep->setAttribute('xml:base', '');
9615
                                        break;
9616
                                }
9617
                            }
9618
                            $my_dep->appendChild($my_dep_file);
9619
                            $resources->appendChild($my_dep);
9620
                            $dependency = $xmldoc->createElement('dependency');
9621
                            $dependency->setAttribute('identifierref', $res_id);
9622
                            $my_resource->appendChild($dependency);
9623
                            $i++;
9624
                        }
9625
                        $resources->appendChild($my_resource);
9626
                        $zip_files[] = $my_file_path;
9627
                        break;
9628
                    default:
9629
                        // Get the path of the file(s) from the course directory root
9630
                        $my_file_path = 'non_exportable.html';
9631
                        //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
9632
                        $my_xml_file_path = $my_file_path;
9633
                        $my_sub_dir = dirname($my_file_path);
9634
                        $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9635
                        //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
9636
                        $my_xml_sub_dir = $my_sub_dir;
9637
                        // Give a <resource> child to the <resources> element.
9638
                        $my_resource = $xmldoc->createElement('resource');
9639
                        $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9640
                        $my_resource->setAttribute('type', 'webcontent');
9641
                        $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
9642
                        // adlcp:scormtype can be either 'sco' or 'asset'.
9643
                        $my_resource->setAttribute('adlcp:scormtype', 'asset');
9644
                        // xml:base is the base directory to find the files declared in this resource.
9645
                        $my_resource->setAttribute('xml:base', '');
9646
                        // Give a <file> child to the <resource> element.
9647
                        $my_file = $xmldoc->createElement('file');
9648
                        $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
9649
                        $my_resource->appendChild($my_file);
9650
                        $resources->appendChild($my_resource);
9651
                        break;
9652
                }
9653
            }
9654
        }
9655
9656
        $organizations->appendChild($organization);
9657
        $root->appendChild($organizations);
9658
        $root->appendChild($resources);
9659
        $xmldoc->appendChild($root);
9660
9661
        // TODO: Add a readme file here, with a short description and a link to the Reload player
9662
        // then add the file to the zip, then destroy the file (this is done automatically).
9663
        // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
9664
9665
        foreach ($zip_files as $file_path) {
9666
            if (empty($file_path)) {
9667
                continue;
9668
            }
9669
9670
            $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
9671
            if (!empty($path_to_remove) && !empty($path_to_replace)) {
9672
                $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
9673
            }
9674
            $this->create_path($dest_file);
9675
            @copy($sys_course_path.$_course['path'].'/'.$file_path, $dest_file);
9676
            // Check if the file needs a link update.
9677
            if (in_array($file_path, array_keys($link_updates))) {
9678
                $string = file_get_contents($dest_file);
9679
                unlink($dest_file);
9680
                foreach ($link_updates[$file_path] as $old_new) {
9681
                    // This is an ugly hack that allows .flv files to be found by the flv player that
9682
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
9683
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
9684
                    // ../../.. to return from inc/lib/flv_player to the document/main path.
9685
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
9686
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
9687 View Code Duplication
                    } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
9688
                        $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
9689
                    }
9690
                    //Fix to avoid problems with default_course_document
9691
                    if (strpos("main/default_course_document", $old_new['dest'] === false)) {
9692
                        //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
9693
                        $newDestination = $old_new['dest'];
9694
                    } else {
9695
                        $newDestination = str_replace('document/', '', $old_new['dest']);
9696
                    }
9697
                    $string = str_replace($old_new['orig'], $newDestination, $string);
9698
9699
                    //Add files inside the HTMLs
9700
                    $new_path = str_replace('/courses/', '', $old_new['orig']);
9701
                    $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
9702
                    if (file_exists($sys_course_path.$new_path)) {
9703
                        copy($sys_course_path.$new_path, $destinationFile);
9704
                    }
9705
                }
9706
                file_put_contents($dest_file, $string);
9707
            }
9708
        }
9709
9710
        foreach ($zip_files_abs as $file_path) {
9711
            if (empty($file_path)) {
9712
                continue;
9713
            }
9714
            if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
9715
                continue;
9716
            }
9717
9718
            $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
9719
            $this->create_path($dest_file);
9720
            copy($main_path.$file_path, $dest_file);
9721
            // Check if the file needs a link update.
9722
            if (in_array($file_path, array_keys($link_updates))) {
9723
                $string = file_get_contents($dest_file);
9724
                unlink($dest_file);
9725
                foreach ($link_updates[$file_path] as $old_new) {
9726
                    // This is an ugly hack that allows .flv files to be found by the flv player that
9727
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
9728
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
9729
                    // ../../.. to return from inc/lib/flv_player to the document/main path.
9730 View Code Duplication
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
9731
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
9732
                    }
9733
                    $string = str_replace($old_new['orig'], $old_new['dest'], $string);
9734
                }
9735
                file_put_contents($dest_file, $string);
9736
            }
9737
        }
9738
9739
        if (is_array($links_to_create)) {
9740
            foreach ($links_to_create as $file => $link) {
9741
                $file_content = '<!DOCTYPE html><head>
9742
                                <meta charset="'.api_get_language_isocode().'" />
9743
                                <title>'.$link['title'].'</title>
9744
                                </head>
9745
                                <body dir="'.api_get_text_direction().'">
9746
                                <div style="text-align:center">
9747
                                <a href="'.$link['url'].'">'.$link['title'].'</a></div>
9748
                                </body>
9749
                                </html>';
9750
                file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
9751
            }
9752
        }
9753
9754
        // Add non exportable message explanation.
9755
        $lang_not_exportable = get_lang('ThisItemIsNotExportable');
9756
        $file_content = '<!DOCTYPE html><head>
9757
                        <meta charset="'.api_get_language_isocode().'" />
9758
                        <title>'.$lang_not_exportable.'</title>
9759
                        <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
9760
                        </head>
9761
                        <body dir="'.api_get_text_direction().'">';
9762
        $file_content .=
9763
            <<<EOD
9764
                    <style>
9765
            .error-message {
9766
                font-family: arial, verdana, helvetica, sans-serif;
9767
                border-width: 1px;
9768
                border-style: solid;
9769
                left: 50%;
9770
                margin: 10px auto;
9771
                min-height: 30px;
9772
                padding: 5px;
9773
                right: 50%;
9774
                width: 500px;
9775
                background-color: #FFD1D1;
9776
                border-color: #FF0000;
9777
                color: #000;
9778
            }
9779
        </style>
9780
    <body>
9781
        <div class="error-message">
9782
            $lang_not_exportable
9783
        </div>
9784
    </body>
9785
</html>
9786
EOD;
9787
        if (!is_dir($archive_path.$temp_dir_short.'/document')) {
9788
            @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
9789
        }
9790
        file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
9791
9792
        // Add the extra files that go along with a SCORM package.
9793
        $main_code_path = api_get_path(SYS_CODE_PATH).'newscorm/packaging/';
9794
        $extra_files = scandir($main_code_path);
9795
        foreach ($extra_files as $extra_file) {
9796
            if (strpos($extra_file, '.') === 0)
9797
                continue;
9798
            else {
9799
                $dest_file = $archive_path . $temp_dir_short . '/' . $extra_file;
9800
                $this->create_path($dest_file);
9801
                copy($main_code_path.$extra_file, $dest_file);
9802
            }
9803
        }
9804
9805
        // Finalize the imsmanifest structure, add to the zip, then return the zip.
9806
9807
        $manifest = @$xmldoc->saveXML();
9808
        $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
9809
        file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
9810
        $zip_folder->add($archive_path.'/'.$temp_dir_short, PCLZIP_OPT_REMOVE_PATH, $archive_path.'/'.$temp_dir_short.'/');
9811
9812
        // Clean possible temporary files.
9813
        foreach ($files_cleanup as $file) {
9814
            $res = unlink($file);
9815
            if ($res === false) {
9816
                error_log(
9817
                    'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
9818
                    0
9819
                );
9820
            }
9821
        }
9822
        $name = api_replace_dangerous_char($this->get_name()).'.zip';
9823
        DocumentManager::file_send_for_download($temp_zip_file, true, $name);
9824
    }
9825
9826
    /**
9827
     * @param int $lp_id
9828
     * @return bool
9829
     */
9830
    public function scorm_export_to_pdf($lp_id)
9831
    {
9832
        $lp_id = intval($lp_id);
9833
        $files_to_export = array();
9834
        $course_data = api_get_course_info($this->cc);
9835
        if (!empty($course_data)) {
9836
            $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
9837
9838
            $list = self::get_flat_ordered_items_list($lp_id);
9839
            if (!empty($list)) {
9840
                foreach ($list as $item_id) {
9841
                    $item = $this->items[$item_id];
9842
                    switch ($item->type) {
9843
                        case 'document':
9844
                            //Getting documents from a LP with chamilo documents
9845
                            $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
9846
                            // Try loading document from the base course.
9847
                            if (empty($file_data) && !empty($sessionId)) {
9848
                                $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc, false, 0);
9849
                            }
9850
                            $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
9851
                            if (file_exists($file_path)) {
9852
                                $files_to_export[] = array('title'=>$item->get_title(),'path'=>$file_path);
9853
                            }
9854
                            break;
9855
                        case 'asset': //commes from a scorm package generated by chamilo
9856
                        case 'sco':
9857
                            $file_path = $scorm_path.'/'.$item->path;
9858
                            if (file_exists($file_path)) {
9859
                                $files_to_export[] = array('title'=>$item->get_title(), 'path' => $file_path);
9860
                            }
9861
                            break;
9862
                        case 'dokeos_chapter':
9863
                        case 'dir':
9864
                        case 'chapter':
9865
                            $files_to_export[] = array('title'=> $item->get_title(), 'path'=>null);
9866
                            break;
9867
                    }
9868
                }
9869
            }
9870
            $pdf = new PDF();
9871
            $result = $pdf->html_to_pdf($files_to_export, $this->name, $this->cc, true);
9872
            return $result;
9873
        }
9874
9875
        return false;
9876
    }
9877
9878
    /**
9879
     * Temp function to be moved in main_api or the best place around for this.
9880
     * Creates a file path if it doesn't exist
9881
     * @param string $path
9882
     */
9883
    public function create_path($path)
9884
    {
9885
        $path_bits = explode('/', dirname($path));
9886
9887
        // IS_WINDOWS_OS has been defined in main_api.lib.php
9888
        $path_built = IS_WINDOWS_OS ? '' : '/';
9889
9890
        foreach ($path_bits as $bit) {
9891
            if (!empty ($bit)) {
9892
                $new_path = $path_built . $bit;
9893
                if (is_dir($new_path)) {
9894
                    $path_built = $new_path . '/';
9895
                } else {
9896
                    mkdir($new_path, api_get_permissions_for_new_directories());
9897
                    $path_built = $new_path . '/';
9898
                }
9899
            }
9900
        }
9901
    }
9902
9903
    /**
9904
     * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
9905
     * @return	boolean	The results of the unlink function, or false if there was no image to start with
9906
     */
9907
    public function delete_lp_image()
9908
    {
9909
        $img = $this->get_preview_image();
9910
        if ($img != '') {
9911
            $del_file = $this->get_preview_image_path(null, 'sys');
9912
            if (isset($del_file) && file_exists($del_file)) {
9913
                $del_file_2 = $this->get_preview_image_path(64, 'sys');
9914
                if (file_exists($del_file_2)) {
9915
                    unlink($del_file_2);
9916
                }
9917
                $this->set_preview_image('');
9918
                return @unlink($del_file);
9919
            }
9920
        }
9921
        return false;
9922
    }
9923
9924
    /**
9925
     * Uploads an author image to the upload/learning_path/images directory
9926
     * @param	array	The image array, coming from the $_FILES superglobal
9927
     * @return	boolean	True on success, false on error
9928
     */
9929
    public function upload_image($image_array)
9930
    {
9931
        $image_moved = false;
9932
        if (!empty ($image_array['name'])) {
9933
            $upload_ok = process_uploaded_file($image_array);
9934
            $has_attachment = true;
9935
        } else {
9936
            $image_moved = true;
9937
        }
9938
9939
        if ($upload_ok) {
9940
            if ($has_attachment) {
9941
                $courseDir = api_get_course_path() . '/upload/learning_path/images';
9942
                $sys_course_path = api_get_path(SYS_COURSE_PATH);
9943
                $updir = $sys_course_path . $courseDir;
9944
                // Try to add an extension to the file if it hasn't one.
9945
                $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
9946
9947
                if (!filter_extension($new_file_name)) {
9948
                    //Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
9949
                    $image_moved = false;
9950
                } else {
9951
                    $file_extension = explode('.', $image_array['name']);
9952
                    $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
9953
                    $filename = uniqid('');
9954
                    $new_file_name = $filename.'.'.$file_extension;
9955
                    $new_path = $updir.'/'.$new_file_name;
9956
9957
                    // Resize the image.
9958
                    $temp = new Image($image_array['tmp_name']);
9959
                    $temp->resize(104);
9960
                    $result = $temp->send_image($new_path);
9961
9962
                    // Storing the image filename.
9963
                    if ($result) {
9964
                        $image_moved = true;
9965
                        $this->set_preview_image($new_file_name);
9966
9967
                        //Resize to 64px to use on course homepage
9968
                        $temp->resize(64);
9969
                        $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
9970
                        return true;
9971
                    }
9972
                }
9973
            }
9974
        }
9975
9976
        return false;
9977
    }
9978
9979
    /**
9980
     * @param int $lp_id
9981
     * @param string $status
9982
     */
9983
    public function set_autolaunch($lp_id, $status)
9984
    {
9985
        $course_id = api_get_course_int_id();
9986
        $lp_id   = intval($lp_id);
9987
        $status  = intval($status);
9988
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
9989
9990
        // Setting everything to autolaunch = 0
9991
        $attributes['autolaunch'] = 0;
9992
        $where = array('session_id = ? AND c_id = ? '=> array(api_get_session_id(), $course_id));
9993
        Database::update($lp_table, $attributes, $where);
9994
        if ($status == 1) {
9995
            //Setting my lp_id to autolaunch = 1
9996
            $attributes['autolaunch'] = 1;
9997
            $where = array('id = ? AND session_id = ? AND c_id = ?'=> array($lp_id, api_get_session_id(), $course_id));
9998
            Database::update($lp_table, $attributes, $where );
9999
        }
10000
    }
10001
10002
    /**
10003
     * Gets previous_item_id for the next element of the lp_item table
10004
     * @author Isaac flores paz
10005
     * @return	integer	Previous item ID
10006
     */
10007
    public function select_previous_item_id()
10008
    {
10009
        $course_id = api_get_course_int_id();
10010
        if ($this->debug > 0) {
10011
            error_log('New LP - In learnpath::select_previous_item_id()', 0);
10012
        }
10013
        $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
10014
10015
        // Get the max order of the items
10016
        $sql_max_order = "SELECT max(display_order) AS display_order FROM $table_lp_item
10017
    	                  WHERE c_id = $course_id AND lp_id = '" . $this->lp_id . "'";
10018
        $rs_max_order = Database::query($sql_max_order);
10019
        $row_max_order = Database::fetch_object($rs_max_order);
10020
        $max_order = $row_max_order->display_order;
10021
        // Get the previous item ID
10022
        $sql = "SELECT id as previous FROM $table_lp_item
10023
                WHERE c_id = $course_id AND lp_id = '" . $this->lp_id . "' AND display_order = '".$max_order."' ";
10024
        $rs_max = Database::query($sql);
10025
        $row_max = Database::fetch_object($rs_max);
10026
10027
        // Return the previous item ID
10028
        return $row_max->previous;
10029
    }
10030
10031
    /**
10032
     * Copies an LP
10033
     */
10034
    public function copy()
10035
    {
10036
        $main_path = api_get_path(SYS_CODE_PATH);
10037
        require_once $main_path.'coursecopy/classes/CourseBuilder.class.php';
10038
        require_once $main_path.'coursecopy/classes/CourseArchiver.class.php';
10039
        require_once $main_path.'coursecopy/classes/CourseRestorer.class.php';
10040
        require_once $main_path.'coursecopy/classes/CourseSelectForm.class.php';
10041
10042
        //Course builder
10043
        $cb = new CourseBuilder();
10044
10045
        //Setting tools that will be copied
10046
        $cb->set_tools_to_build(array('learnpaths'));
10047
10048
        //Setting elements that will be copied
10049
        $cb->set_tools_specific_id_list(
10050
            array('learnpaths' => array($this->lp_id))
10051
        );
10052
10053
        $course = $cb->build();
10054
10055
        //Course restorer
10056
        $course_restorer = new CourseRestorer($course);
10057
        $course_restorer->set_add_text_in_items(true);
10058
        $course_restorer->set_tool_copy_settings(array('learnpaths' => array('reset_dates' => true)));
10059
        $course_restorer->restore(api_get_course_id(), api_get_session_id(), false, false);
10060
    }
10061
10062
    public function verify_document_size($s)
10063
    {
10064
        $post_max = ini_get('post_max_size');
10065 View Code Duplication
        if (substr($post_max, -1, 1) == 'M') {
10066
            $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
10067
        } elseif (substr($post_max, -1, 1) == 'G') {
10068
            $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
10069
        }
10070
        $upl_max = ini_get('upload_max_filesize');
10071 View Code Duplication
        if (substr($upl_max, -1, 1) == 'M') {
10072
            $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
10073
        } elseif (substr($upl_max, -1, 1) == 'G') {
10074
            $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
10075
        }
10076
        $documents_total_space = DocumentManager::documents_total_space();
10077
        $course_max_space = DocumentManager::get_course_quota();
10078
        $total_size = filesize($s) + $documents_total_space;
10079
        if (filesize($s)>$post_max || filesize($s)>$upl_max  || $total_size>$course_max_space ){
10080
            return true;
10081
        } else{
10082
            return false;
10083
        }
10084
    }
10085
10086
    /**
10087
     * Clear LP prerequisites
10088
     */
10089
    public function clear_prerequisites()
10090
    {
10091
        $course_id = $this->get_course_int_id();
10092
        if ($this->debug > 0) {
10093
            error_log('New LP - In learnpath::clear_prerequisites()', 0);
10094
        }
10095
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
10096
        $lp_id = $this->get_id();
10097
        //Cleaning prerequisites
10098
        $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
10099
                WHERE c_id = ".$course_id." AND lp_id = '$lp_id'";
10100
        Database::query($sql);
10101
10102
        //Cleaning mastery score for exercises
10103
        $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
10104
                WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND item_type = 'quiz'";
10105
        Database::query($sql);
10106
    }
10107
10108
    public function set_previous_step_as_prerequisite_for_all_items()
10109
    {
10110
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
10111
        $course_id = $this->get_course_int_id();
10112
        $lp_id = $this->get_id();
10113
10114
        if (!empty($this->items)) {
10115
            $previous_item_id = null;
10116
            $previous_item_max = 0;
10117
            $previous_item_type = null;
10118
            $last_item_not_chapter = null;
10119
            $last_item_not_chapter_type = null;
10120
            $last_item_not_chapter_max = null;
10121
            foreach ($this->items as $item) {
10122
                // if there was a previous item... (otherwise jump to set it)
10123
                if (!empty($previous_item_id)) {
10124
                    $current_item_id = $item->get_id(); //save current id
10125
                    if (!in_array($item->get_type(), array('dokeos_chapter', 'chapter'))) {
10126
                        // Current item is not a folder, so it qualifies to get a prerequisites
10127
                        if ($last_item_not_chapter_type == 'quiz') {
10128
                            // if previous is quiz, mark its max score as default score to be achieved
10129
                            $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_chapter_max'
10130
                                    WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$last_item_not_chapter'";
10131
                            Database::query($sql);
10132
                        }
10133
                        // now simply update the prerequisite to set it to the last non-chapter item
10134
                        $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_chapter'
10135
                                WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$current_item_id'";
10136
                        Database::query($sql);
10137
                        // record item as 'non-chapter' reference
10138
                        $last_item_not_chapter = $item->get_id();
10139
                        $last_item_not_chapter_type = $item->get_type();
10140
                        $last_item_not_chapter_max = $item->get_max();
10141
                    }
10142
                } else {
10143
                    if (!in_array($item->get_type(), array('dokeos_chapter', 'chapter'))) {
10144
                        // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
10145
                        $last_item_not_chapter = $item->get_id();
10146
                        $last_item_not_chapter_type = $item->get_type();
10147
                        $last_item_not_chapter_max = $item->get_max();
10148
                    }
10149
                }
10150
                // Saving the item as "previous item" for the next loop
10151
                $previous_item_id = $item->get_id();
10152
                $previous_item_max = $item->get_max();
10153
                $previous_item_type = $item->get_type();
10154
            }
10155
        }
10156
    }
10157
10158
    /**
10159
     * @param array $params
10160
     */
10161
    public static function createCategory($params)
10162
    {
10163
        $em = Database::getManager();
10164
        $item = new CLpCategory();
10165
        $item->setName($params['name']);
10166
        $item->setCId($params['c_id']);
10167
        $em->persist($item);
10168
        $em->flush();
10169
    }
10170
    /**
10171
     * @param array $params
10172
     */
10173
    public static function updateCategory($params)
10174
    {
10175
        $em = Database::getManager();
10176
        /** @var CLpCategory $item */
10177
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
10178
        if ($item) {
10179
            $item->setName($params['name']);
10180
            $em->merge($item);
10181
            $em->flush();
10182
        }
10183
    }
10184
10185
    /**
10186
     * @param int $id
10187
     */
10188 View Code Duplication
    public static function moveUpCategory($id)
10189
    {
10190
        $em = Database::getManager();
10191
        /** @var CLpCategory $item */
10192
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10193
        if ($item) {
10194
            $position = $item->getPosition() - 1;
10195
            $item->setPosition($position);
10196
            $em->persist($item);
10197
            $em->flush();
10198
        }
10199
    }
10200
10201
    /**
10202
     * @param int $id
10203
     */
10204 View Code Duplication
    public static function moveDownCategory($id)
10205
    {
10206
        $em = Database::getManager();
10207
        /** @var CLpCategory $item */
10208
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10209
        if ($item) {
10210
            $position = $item->getPosition() + 1;
10211
            $item->setPosition($position);
10212
            $em->persist($item);
10213
            $em->flush();
10214
        }
10215
    }
10216
10217
    /**
10218
     * @param int $courseId
10219
     * @return int|mixed
10220
     */
10221
    public static function getCountCategories($courseId)
10222
    {
10223
        if (empty($course_id)) {
0 ignored issues
show
Bug introduced by
The variable $course_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...
10224
            return 0;
10225
        }
10226
        $em = Database::getManager();
10227
        $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
10228
        $query->setParameter('id', $courseId);
10229
10230
        return $query->getSingleScalarResult();
10231
    }
10232
10233
    /**
10234
     * @param int $courseId
10235
     *
10236
     * @return mixed
10237
     */
10238 View Code Duplication
    public static function getCategories($courseId)
10239
    {
10240
        $em = Database::getManager();
10241
        //Default behaviour
10242
        /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
10243
            array('cId' => $course_id),
10244
            array('name' => 'ASC')
10245
        );*/
10246
10247
        // Using doctrine extensions
10248
        $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->getBySortableGroupsQuery(
10249
            array('cId' => $courseId)
10250
        )->getResult();
10251
10252
        return $items;
10253
    }
10254
10255
    /**
10256
     * @param int $id
10257
     *
10258
     * @return mixed
10259
     */
10260
    public static function getCategory($id)
10261
    {
10262
        $em = Database::getManager();
10263
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10264
10265
        return $item;
10266
    }
10267
10268
    /**
10269
     * @param int $courseId
10270
     * @return array
10271
     */
10272 View Code Duplication
    public static function getCategoryByCourse($courseId)
10273
    {
10274
        $em = Database::getManager();
10275
        $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(array('cId' => $courseId));
10276
10277
        return $items;
10278
    }
10279
10280
    /**
10281
     * @param int $id
10282
     *
10283
     * @return mixed
10284
     */
10285
    public static function deleteCategory($id)
10286
    {
10287
        $em = Database::getManager();
10288
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10289
        if ($item) {
10290
10291
            $courseId = $item->getCId();
10292
            $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
10293
            $query->setParameter('id', $courseId);
10294
            $query->setParameter('catId', $item->getId());
10295
            $lps = $query->getResult();
10296
10297
            // Setting category = 0.
10298
            if ($lps) {
10299
                foreach ($lps as $lpItem) {
10300
                    $lpItem->setCategoryId(0);
10301
                }
10302
            }
10303
10304
            // Removing category.
10305
            $em->remove($item);
10306
            $em->flush();
10307
        }
10308
    }
10309
10310
    /**
10311
     * @param int $courseId
10312
     * @param bool $addSelectOption
10313
     *
10314
     * @return mixed
10315
     */
10316
    static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
10317
    {
10318
        $items = self::getCategoryByCourse($courseId);
10319
        $cats = array();
10320
        if ($addSelectOption) {
10321
            $cats = array(get_lang('SelectACategory'));
10322
        }
10323
10324
        if (!empty($items)) {
10325
            foreach ($items as $cat) {
10326
                $cats[$cat->getId()] = $cat->getName();
10327
            }
10328
        }
10329
10330
        return $cats;
10331
    }
10332
10333
    /**
10334
     * Return the scorm item type object with spaces replaced with _
10335
     * The return result is use to build a css classname like scorm_type_$return
10336
     * @param $in_type
10337
     * @return mixed
10338
     */
10339
    private static function format_scorm_type_item($in_type)
10340
    {
10341
        return str_replace(' ', '_', $in_type);
10342
    }
10343
10344
    /**
10345
     * @return \learnpath
10346
     */
10347
    public static function getLpFromSession($courseCode, $lp_id, $user_id)
10348
    {
10349
        $lpObject = Session::read('lpobject');
10350
        $learnPath = null;
10351
        if (isset($lpObject)) {
10352
            $learnPath = unserialize($lpObject);
10353
        }
10354
10355
        if (!is_object($learnPath)) {
10356
            $learnPath = new learnpath($courseCode, $lp_id, $user_id);
10357
        }
10358
10359
        return $learnPath;
10360
    }
10361
10362
    /**
10363
     * @param int $itemId
10364
     * @return learnpathItem|false
10365
     */
10366
    public function getItem($itemId)
10367
    {
10368
        if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
10369
            return $this->items[$itemId];
10370
        }
10371
10372
        return false;
10373
    }
10374
10375
    /**
10376
     * @return int
10377
     */
10378
    public function getCategoryId()
10379
    {
10380
        return $this->categoryId;
10381
    }
10382
10383
    /**
10384
     * @param int $categoryId
10385
     * @return bool
10386
     */
10387
    public function setCategoryId($categoryId)
10388
    {
10389
        $this->categoryId = intval($categoryId);
10390
10391
        $courseId = api_get_course_int_id();
10392
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
10393
        $lp_id = $this->get_id();
10394
        $sql = "UPDATE $lp_table SET category_id = ".$this->categoryId."
10395
                WHERE c_id = $courseId AND id = $lp_id";
10396
        Database::query($sql);
10397
10398
        return true;
10399
    }
10400
10401
    /**
10402
     * Get whether this is a learning path with the possibility to subscribe
10403
     * users or not
10404
     * @return int
10405
     */
10406
    public function getSubscribeUsers()
10407
    {
10408
        return $this->subscribeUsers;
10409
    }
10410
10411
    /**
10412
     * Set whether this is a learning path with the possibility to subscribe
10413
     * users or not
10414
     * @param int $subscribeUsers (0 = false, 1 = true)
0 ignored issues
show
Bug introduced by
There is no parameter named $subscribeUsers. 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...
10415
     */
10416
    public function setSubscribeUsers($value)
10417
    {
10418
        if ($this->debug > 0) {
10419
            error_log('New LP - In learnpath::set_subscribe_users()', 0);
10420
        }
10421
        $this->subscribeUsers = intval($value);;
10422
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
10423
        $lp_id = $this->get_id();
10424
        $sql = "UPDATE $lp_table SET subscribe_users = ".$this->subscribeUsers."
10425
                WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
10426
        Database::query($sql);
10427
10428
        return true;
10429
    }
10430
10431
    /**
10432
     * Calculate the count of stars for a user in this LP
10433
     * This calculation is based on the following rules:
10434
     * - the student gets one star when he gets to 50% of the learning path
10435
     * - the student gets a second star when the average score of all tests inside the learning path >= 50%
10436
     * - the student gets a third star when the average score of all tests inside the learning path >= 80%
10437
     * - the student gets the final star when the score for the *last* test is >= 80%
10438
     * @param int $sessionId Optional. The session ID
10439
     * @return int The count of stars
10440
     */
10441
    public function getCalculateStars($sessionId = 0)
10442
    {
10443
        $stars = 0;
10444
10445
        $progress = self::getProgress($this->lp_id, $this->user_id, $this->course_int_id, $sessionId);
10446
10447
        if ($progress >= 50) {
10448
            $stars++;
10449
        }
10450
10451
        // Calculate stars chapters evaluation
10452
        $exercisesItems = $this->getExercisesItems();
10453
10454
        if (!empty($exercisesItems)) {
10455
            $totalResult = 0;
10456
10457
            foreach ($exercisesItems as $exerciseItem) {
10458
                $exerciseResultInfo = Event::getExerciseResultsByUser(
10459
                    $this->user_id,
10460
                    $exerciseItem->path,
10461
                    $this->course_int_id,
10462
                    $sessionId,
10463
                    $this->lp_id,
10464
                    $exerciseItem->db_id
10465
                );
10466
10467
                $exerciseResultInfo = end($exerciseResultInfo);
10468
10469
                if (!$exerciseResultInfo) {
10470
                    continue;
10471
                }
10472
10473
                $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
10474
10475
                $totalResult += $exerciseResult;
10476
            }
10477
10478
            $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
10479
10480
            if ($totalExerciseAverage >= 50) {
10481
                $stars++;
10482
            }
10483
10484
            if ($totalExerciseAverage >= 80) {
10485
                $stars++;
10486
            }
10487
        }
10488
10489
        // Calculate star for final evaluation
10490
        $finalEvaluationItem = $this->getFinalEvaluationItem();
10491
10492
        if (!empty($finalEvaluationItem)) {
10493
            $evaluationResultInfo = Event::getExerciseResultsByUser(
10494
                $this->user_id,
10495
                $finalEvaluationItem->path,
10496
                $this->course_int_id,
10497
                $sessionId,
10498
                $this->lp_id,
10499
                $finalEvaluationItem->db_id
10500
            );
10501
10502
            $evaluationResultInfo = end($evaluationResultInfo);
10503
10504
            if ($evaluationResultInfo) {
10505
                $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
10506
10507
                if ($evaluationResult >= 80) {
10508
                    $stars++;
10509
                }
10510
            }
10511
        }
10512
10513
        return $stars;
10514
    }
10515
10516
    /**
10517
     * Get the items of exercise type
10518
     * @return array The items. Otherwise return false
10519
     */
10520 View Code Duplication
    public function getExercisesItems()
10521
    {
10522
        $exercises = [];
10523
10524
        foreach ($this->items as $item) {
10525
            if ($item->type != 'quiz') {
10526
                continue;
10527
            }
10528
10529
            $exercises[] = $item;
10530
        }
10531
10532
        array_pop($exercises);
10533
10534
        return $exercises;
10535
    }
10536
10537
    /**
10538
     * Get the item of exercise type (evaluation type)
10539
     * @return array The final evaluation. Otherwise return false
10540
     */
10541 View Code Duplication
    public function getFinalEvaluationItem()
10542
    {
10543
        $exercises = [];
10544
10545
        foreach ($this->items as $item) {
10546
            if ($item->type != 'quiz') {
10547
                continue;
10548
            }
10549
10550
            $exercises[] = $item;
10551
        }
10552
10553
        return array_pop($exercises);
10554
    }
10555
10556
    /**
10557
     * Calculate the total points achieved for the current user in this learning path
10558
     * @param int $sessionId Optional. The session Id
10559
     * @return int
10560
     */
10561
    public function getCalculateScore($sessionId = 0)
10562
    {
10563
        // Calculate stars chapters evaluation
10564
        $exercisesItems = $this->getExercisesItems();
10565
        $finalEvaluationItem = $this->getFinalEvaluationItem();
10566
10567
        $totalExercisesResult = 0;
10568
        $totalEvaluationResult = 0;
10569
10570
        if ($exercisesItems !== false) {
10571
            foreach ($exercisesItems as $exerciseItem) {
10572
                $exerciseResultInfo = Event::getExerciseResultsByUser(
10573
                    $this->user_id,
10574
                    $exerciseItem->path,
10575
                    $this->course_int_id,
10576
                    $sessionId,
10577
                    $this->lp_id,
10578
                    $exerciseItem->db_id
10579
                );
10580
10581
                $exerciseResultInfo = end($exerciseResultInfo);
10582
10583
                if (!$exerciseResultInfo) {
10584
                    continue;
10585
                }
10586
10587
                $totalExercisesResult += $exerciseResultInfo['exe_result'];
10588
            }
10589
        }
10590
10591
        if (!empty($finalEvaluationItem)) {
10592
            $evaluationResultInfo = Event::getExerciseResultsByUser(
10593
                $this->user_id,
10594
                $finalEvaluationItem->path,
10595
                $this->course_int_id,
10596
                $sessionId,
10597
                $this->lp_id,
10598
                $finalEvaluationItem->db_id
10599
            );
10600
10601
            $evaluationResultInfo = end($evaluationResultInfo);
10602
10603
            if ($evaluationResultInfo) {
10604
                $totalEvaluationResult += $evaluationResultInfo['exe_result'];
10605
            }
10606
        }
10607
10608
        return $totalExercisesResult + $totalEvaluationResult;
10609
    }
10610
10611
    /**
10612
     * Check if URL is not allowed to be show in a iframe
10613
     * @param string $src
10614
     *
10615
     * @return string
10616
     */
10617
    public function fixBlockedLinks($src)
10618
    {
10619
        $urlInfo = parse_url($src);
10620
        //$platformProtocol = api_get_protocol();
10621
10622
        $platformProtocol = 'https';
10623
        if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
10624
            $platformProtocol = 'http';
10625
        }
10626
10627
        $protocolFixApplied = false;
10628
        //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
10629
        $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
10630
        if ($platformProtocol != $scheme) {
10631
            $_SESSION['x_frame_source'] = $src;
10632
            $src = 'blank.php?error=x_frames_options';
10633
            $protocolFixApplied = true;
10634
        }
10635
10636
        if ($protocolFixApplied == false) {
10637
            if (strpos($src, api_get_path(WEB_CODE_PATH)) === false) {
10638
                // Check X-Frame-Options
10639
                $ch = curl_init();
10640
10641
                $options = array(
10642
                    CURLOPT_URL => $src,
10643
                    CURLOPT_RETURNTRANSFER => true,
10644
                    CURLOPT_HEADER => true,
10645
                    CURLOPT_FOLLOWLOCATION => true,
10646
                    CURLOPT_ENCODING => "",
10647
                    CURLOPT_AUTOREFERER => true,
10648
                    CURLOPT_CONNECTTIMEOUT => 120,
10649
                    CURLOPT_TIMEOUT => 120,
10650
                    CURLOPT_MAXREDIRS => 10,
10651
                );
10652
                curl_setopt_array($ch, $options);
10653
                $response = curl_exec($ch);
10654
                $httpCode = curl_getinfo($ch);
10655
                $headers = substr($response, 0, $httpCode['header_size']);
10656
10657
                $error = false;
10658
                if (stripos($headers, 'X-Frame-Options: DENY') > -1 ||
10659
                    stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
10660
                ) {
10661
                    $error = true;
10662
                }
10663
10664
                if ($error) {
10665
                    $_SESSION['x_frame_source'] = $src;
10666
                    $src = 'blank.php?error=x_frames_options';
10667
                }
10668
            }
10669
        }
10670
10671
        return $src;
10672
    }
10673
10674
    /**
10675
     * Check if this LP has a created forum in the basis course
10676
     * @return boolean
10677
     */
10678
    public function lpHasForum()
10679
    {
10680
        $forumTable = Database::get_course_table(TABLE_FORUM);
10681
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
10682
10683
        $fakeFrom = "
10684
            $forumTable f
10685
            INNER JOIN $itemProperty ip
10686
            ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
10687
        ";
10688
10689
        $resultData = Database::select(
10690
            'COUNT(f.iid) AS qty',
10691
            $fakeFrom,
10692
            [
10693
                'where' => [
10694
                    'ip.visibility != ? AND ' => 2,
10695
                    'ip.tool = ? AND ' => TOOL_FORUM,
10696
                    'f.c_id = ? AND ' => intval($this->course_int_id),
10697
                    'f.lp_id = ?' => intval($this->lp_id)
10698
                ]
10699
            ],
10700
            'first'
10701
        );
10702
10703
        if ($resultData['qty'] > 0) {
10704
            return true;
10705
        }
10706
10707
        return false;
10708
    }
10709
10710
    /**
10711
     * Get the forum for this learning path
10712
     * @return boolean
10713
     */
10714
    public function getForum($sessionId = 0)
10715
    {
10716
        $forumTable = Database::get_course_table(TABLE_FORUM);
10717
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
10718
10719
        $fakeFrom = "$forumTable f
10720
            INNER JOIN $itemProperty ip ";
10721
10722
        if ($this->lp_session_id == 0) {
10723
            $fakeFrom .= "
10724
                ON (
10725
                    f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
10726
                        f.session_id = ip.session_id OR ip.session_id IS NULL
10727
                    )
10728
                )
10729
            ";
10730
        } else {
10731
            $fakeFrom .= "
10732
                ON (
10733
                    f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
10734
                )
10735
            ";
10736
        }
10737
10738
        $resultData = Database::select(
10739
            'f.*',
10740
            $fakeFrom,
10741
            [
10742
                'where' => [
10743
                    'ip.visibility != ? AND ' => 2,
10744
                    'ip.tool = ? AND ' => TOOL_FORUM,
10745
                    'f.session_id = ? AND ' => $sessionId,
10746
                    'f.c_id = ? AND ' => intval($this->course_int_id),
10747
                    'f.lp_id = ?' => intval($this->lp_id)
10748
                ]
10749
            ],
10750
            'first'
10751
        );
10752
10753
        if (empty($resultData)) {
10754
            return false;
10755
        }
10756
10757
        return $resultData;
10758
    }
10759
10760
    /**
10761
     * Create a forum for this learning path
10762
     * @param type $forumCategoryId
10763
     * @return int The forum ID if was created. Otherwise return false
10764
     */
10765
    public function createForum($forumCategoryId)
10766
    {
10767
        require_once api_get_path(SYS_CODE_PATH) . '/forum/forumfunction.inc.php';
10768
10769
        $forumId = store_forum(
10770
            [
10771
                'lp_id' => $this->lp_id,
10772
                'forum_title' => $this->name,
10773
                'forum_comment' => null,
10774
                'forum_category' => intval($forumCategoryId),
10775
                'students_can_edit_group' => ['students_can_edit' => 0],
10776
                'allow_new_threads_group' => ['allow_new_threads' => 0],
10777
                'default_view_type_group' => ['default_view_type' => 'flat'],
10778
                'group_forum' => 0,
10779
                'public_private_group_forum_group' => ['public_private_group_forum' => 'public']
10780
            ],
10781
            [],
10782
            true
10783
        );
10784
10785
        return $forumId;
10786
    }
10787
10788
    /**
10789
     * Check and obtain the lp final item if exist
10790
     *
10791
     * @return array lp items
10792
     */
10793
    private function getFinalItem()
10794
    {
10795
10796
        if (empty($this->items)) {
10797
            return null;
10798
        }
10799
10800
        foreach ($this->items as $item) {
10801
            if ($item->type !== 'final_item') {
10802
                continue;
10803
            }
10804
10805
            return $item;
10806
        }
10807
    }
10808
10809
    /**
10810
     * Get the LP Final Item Template
10811
     *
10812
     * @return html
10813
     */
10814
    private function getFinalItemTemplate()
10815
    {
10816
        return file_get_contents(api_get_path(SYS_CODE_PATH) . 'newscorm/final_item_template/template.html');
10817
    }
10818
10819
    /**
10820
     * Get the LP Final Item Url
10821
     *
10822
     * @return String
10823
     */
10824
    private function getSavedFinalItem()
10825
    {
10826
        $finalItem = $this->getFinalItem();
10827
        $doc = DocumentManager::get_document_data_by_id($finalItem->path, $this->cc);
10828
10829
        return file_get_contents($doc['absolute_path']);
10830
    }
10831
10832
    /**
10833
     * Get the LP Final Item form
10834
     *
10835
     * @return html
10836
     */
10837
    public function getFinalItemForm()
10838
    {
10839
        $finalItem = $this->getFinalItem();
10840
        $title = '';
10841
        $content = '';
10842
10843
        if ($finalItem) {
10844
            $title = $finalItem->title;
10845
            $buttonText = get_lang('Save');
10846
            $content = $this->getSavedFinalItem();
10847
        } else {
10848
            $buttonText = get_lang('LPCreateDocument');
10849
            $content = $this->getFinalItemTemplate();
10850
        }
10851
10852
        $courseInfo = api_get_course_info();
10853
        $result = $this->generate_lp_folder($courseInfo);
10854
        $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
10855
        $relative_prefix = '../../';
10856
10857
        $editorConfig = [
10858
            'ToolbarSet' => 'LearningPathDocuments',
10859
            'Width' => '100%',
10860
            'Height' => '500',
10861
            'FullPage' => true,
10862
            'CreateDocumentDir' => $relative_prefix,
10863
            'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/',
10864
            'BaseHref' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/' . $relative_path
10865
        ];
10866
10867
        $url = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
10868
            'type' => 'document',
10869
            'lp_id' => $this->lp_id
10870
        ]);
10871
10872
        $form = new FormValidator('final_item', 'POST', $url);
10873
        $form->addText('title', get_lang('Title'));
10874
        $form->addButtonSave($buttonText);
10875
        $form->addHtml('<div class="alert alert-info">Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b></div>');
10876
        $renderer = $form->defaultRenderer();
10877
        $renderer->setElementTemplate('<div class="editor-lp">&nbsp;{label}{element}</div>', 'content_lp');
10878
        $form->addHtmlEditor('content_lp', null, null, true, $editorConfig, true);
10879
        $form->addHidden('action', 'add_final_item');
10880
        $form->addHidden('path', isset($_SESSION['pathItem']) ? $_SESSION['pathItem'] : '');
10881
        $form->addHidden('previous', $this->get_last());
10882
10883
        $form->setDefaults(['title' => $title, 'content_lp' => $content]);
10884
10885
        if ($form->validate()) {
10886
            $values = $form->exportValues();
10887
10888
            $lastItemId = $this->get_last();
10889
10890
            if (!$finalItem) {
10891
                $documentId = $this->create_document($this->course_info, $values['content_lp'], $values['title']);
10892
                $this->add_item(
10893
                    0,
10894
                    $lastItemId,
10895
                    'final_item',
10896
                    $documentId,
10897
                    $values['title'],
10898
                    ''
10899
                );
10900
            } else {
10901
                $this->edit_document($this->course_info);
10902
            }
10903
        }
10904
10905
        return $form->returnForm();
10906
    }
10907
}
10908
10909
if (!function_exists('trim_value')) {
10910
    function trim_value(& $value) {
0 ignored issues
show
Best Practice introduced by
The function trim_value() has been defined more than once; this definition is ignored, only the first definition in main/inc/lib/search/ChamiloIndexer.class.php (L90-92) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
10911
        $value = trim($value);
10912
    }
10913
}
10914