Passed
Push — 1.10.x ( 1f0c91...36635d )
by Angel Fernando Quiroz
43:44
created

learnpath::getFinalItem()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 7
nc 4
nop 0
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', '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
            if (($i % 2) == 0) {
5602
                $oddClass = 'row_odd';
5603
            } else {
5604
                $oddClass = 'row_even';
5605
            }
5606
            $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'] .'" class="' . $oddClass . '">';
5607
5608
            $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
5609
5610
            if (file_exists('../img/lp_' . $icon_name . '.png')) {
5611
                $icon = Display::return_icon('lp_'.$icon_name.'.png');
5612
            } else {
5613
                if (file_exists('../img/lp_' . $icon_name . '.gif')) {
5614
                    $icon = Display::return_icon('lp_'.$icon_name.'.gif');
5615
                } else {
5616
                    if ($arrLP[$i]['item_type'] === 'final_item') {
5617
                        $icon = Display::return_icon('certificate.png');
5618
                    } else {
5619
                        $icon = Display::return_icon('folder_document.gif');
5620
                    }
5621
                }
5622
            }
5623
5624
            // The audio column.
5625
            $return_audio  .= '<td align="left" style="padding-left:10px;">';
5626
            $audio = '';
5627
5628
            if (!$update_audio || $update_audio <> 'true') {
5629
                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...
5630
                } else {
5631
                    $audio .= '';
5632
                }
5633
            } else {
5634
                $types = self::getChapterTypes();
5635
                if (!in_array($arrLP[$i]['item_type'], $types)) {
5636
                    $audio .= '<input type="file" name="mp3file' . $arrLP[$i]['id'] . '" id="mp3file" />';
5637
                    if (!empty ($arrLP[$i]['audio'])) {
5638
                        $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
5639
                        <input type="checkbox" name="removemp3' . $arrLP[$i]['id'] . '" id="checkbox' . $arrLP[$i]['id'] . '" />' . get_lang('RemoveAudio');
5640
                    }
5641
                }
5642
            }
5643
            $return_audio .= Display::span($icon.' '.$title).Display::tag('td', $audio, array('style'=>''));
5644
            $return_audio .= '</td>';
5645
            $move_icon = '';
5646
            $move_item_icon = '';
5647
            $edit_icon = '';
5648
            $delete_icon = '';
5649
            $audio_icon = '';
5650
            $prerequisities_icon = '';
5651
            $forumIcon = '';
5652
5653
            if ($is_allowed_to_edit) {
5654 View Code Duplication
                if (!$update_audio || $update_audio <> 'true') {
5655
                    $move_icon .= '<a class="moved" href="#">';
5656
                    $move_icon .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
5657
                    $move_icon .= '</a>';
5658
                }
5659
5660
                // No edit for this item types
5661
                if (!in_array($arrLP[$i]['item_type'], array('sco', 'asset'))) {
5662
                    if (!in_array($arrLP[$i]['item_type'], array('dokeos_chapter', 'dokeos_module'))) {
5663
                        $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">';
5664
                        $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(), ICON_SIZE_TINY);
5665
                        $edit_icon .= '</a>';
5666
5667
                        if (
5668
                        !in_array($arrLP[$i]['item_type'], ['forum', 'thread'])
5669
                        ) {
5670
                            if (
5671
                            $this->items[$arrLP[$i]['id']]->getForumThread(
5672
                                $this->course_int_id,
5673
                                $this->lp_session_id
5674
                            )
5675
                            ) {
5676
                                $forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
5677
                                    'action' => 'dissociate_forum',
5678
                                    'id' => $arrLP[$i]['id'],
5679
                                    'lp_id' => $this->lp_id
5680
                                ]);
5681
                                $forumIcon = Display::url(
5682
                                    Display::return_icon('forum.png', get_lang('DissociateForumToLPItem'), [], ICON_SIZE_TINY),
5683
                                    $forumIconUrl,
5684
                                    ['class' => 'btn btn-default lp-btn-dissociate-forum']
5685
                                );
5686
                            } else {
5687
                                $forumIconUrl = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
5688
                                    'action' => 'create_forum',
5689
                                    'id' => $arrLP[$i]['id'],
5690
                                    'lp_id' => $this->lp_id
5691
                                ]);
5692
                                $forumIcon = Display::url(
5693
                                    Display::return_icon('forum.png', get_lang('AssociateForumToLPItem'), [], ICON_SIZE_TINY),
5694
                                    $forumIconUrl,
5695
                                    ['class' => "btn btn-default lp-btn-associate-forum"]
5696
                                );
5697
                            }
5698
                        }
5699
                    } else {
5700
                        $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">';
5701
                        $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(), ICON_SIZE_TINY);
5702
                        $edit_icon .= '</a>';
5703
                    }
5704
                }
5705
5706
                $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">';
5707
                $delete_icon .= Display::return_icon('delete.png', get_lang('LearnpathDeleteModule'), array(), ICON_SIZE_TINY);
5708
                $delete_icon .= '</a>';
5709
5710
                $url = api_get_self() . '?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'] .'&lp_id='.$this->lp_id;
5711
5712
                if (!in_array($arrLP[$i]['item_type'], array('dokeos_chapter', 'dokeos_module', 'dir'))) {
5713
                    $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']);
5714
                    $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']);
5715
                    $audio_icon = Display::url(Display::return_icon('audio.png', get_lang('UplUpload'), array(), ICON_SIZE_TINY), $url.'&action=add_audio', ['class' => 'btn btn-default']);
5716
                }
5717
            }
5718
            if ($update_audio != 'true') {
5719
                $row = $move_icon . ' ' . $icon .
5720
                    Display::span($title_cut) .
5721
                    Display::tag(
5722
                        'div',
5723
                        "<div class=\"btn-group btn-group-xs\">$audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
5724
                        array('class'=>'btn-toolbar button_actions')
5725
                    );
5726
            } else {
5727
                $row = Display::span($title.$icon).Display::span($audio, array('class'=>'button_actions'));
5728
            }
5729
            $parent_id = $arrLP[$i]['parent_item_id'];
5730
5731
            $default_data[$arrLP[$i]['id']] = $row;
5732
            $default_content[$arrLP[$i]['id']] = $arrLP[$i];
5733
5734
            if (empty($parent_id)) {
5735
                $elements[$arrLP[$i]['id']]['data'] = $row;
5736
                $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
5737
            } else {
5738
                $parent_arrays = array();
5739
                if ($arrLP[$i]['depth'] > 1) {
5740
                    //Getting list of parents
5741
                    for($j = 0; $j < $arrLP[$i]['depth']; $j++) {
5742
                        foreach($arrLP as $item) {
5743
                            if ($item['id'] == $parent_id) {
5744
                                if ($item['parent_item_id'] == 0) {
5745
                                    $parent_id = $item['id'];
5746
                                    break;
5747
                                } else {
5748
                                    $parent_id = $item['parent_item_id'];
5749
                                    if (empty($parent_arrays)) {
5750
                                        $parent_arrays[] = intval($item['id']);
5751
                                    }
5752
                                    $parent_arrays[] = $parent_id;
5753
                                    break;
5754
                                }
5755
                            }
5756
                        }
5757
                    }
5758
                }
5759
5760
                if (!empty($parent_arrays)) {
5761
                    $parent_arrays = array_reverse($parent_arrays);
5762
                    $val = '$elements';
5763
                    $x = 0;
5764
                    foreach($parent_arrays as $item) {
5765
                        if ($x != count($parent_arrays) -1) {
5766
                            $val .= '["'.$item.'"]["children"]';
5767
                        } else {
5768
                            $val .= '["'.$item.'"]["children"]';
5769
                        }
5770
                        $x++;
5771
                    }
5772
                    $val .= "";
5773
                    $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
5774
                    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...
5775
                } else {
5776
                    $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
5777
                    $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
5778
                }
5779
            }
5780
        }
5781
5782
        $list = '<ul id="lp_item_list">';
5783
        $tree = self::print_recursive($elements, $default_data, $default_content);
5784
5785
        if (!empty($tree)) {
5786
            $list .= $tree;
5787
        } else {
5788
            if ($drop_element_here) {
5789
                $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
5790
            }
5791
        }
5792
        $list .= '</ul>';
5793
5794
        //$return .= Display::panel($list, $this->name);
5795
        $return .= Display::panelCollapse($this->name, $list, 'scorm-list', null, 'scorm-list-accordion', 'scorm-list-collapse');
5796
5797
        if ($update_audio == 'true') {
5798
            $return = $return_audio;
5799
        }
5800
5801
        return $return;
5802
    }
5803
5804
    /**
5805
     * @param array $elements
5806
     * @param array $default_data
5807
     * @param array $default_content
5808
     * @return string
5809
     */
5810
    public function print_recursive($elements, $default_data, $default_content)
5811
    {
5812
        $return = '';
5813
        foreach ($elements as $key => $item) {
5814
            if (isset($item['load_data']) || empty($item['data'])) {
5815
                $item['data'] = $default_data[$item['load_data']];
5816
                $item['type'] = $default_content[$item['load_data']]['item_type'];
5817
            }
5818
            $sub_list = '';
5819
            if (isset($item['type']) && $item['type'] == 'dokeos_chapter') {
5820
                $sub_list = Display::tag('li', '', array('class'=>'sub_item empty')); // empty value
5821
            }
5822
            if (empty($item['children'])) {
5823
                $sub_list = Display::tag('ul', $sub_list, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
5824
                $active = null;
5825
                if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
5826
                    $active = 'active';
5827
                }
5828
                $return  .= Display::tag('li', Display::div($item['data'], array('class'=>"item_data $active")).$sub_list, array('id'=>$key, 'class'=>'record li_container'));
5829
            } else {
5830
                //sections
5831
                if (isset($item['children'])) {
5832
                    $data = self::print_recursive($item['children'], $default_data, $default_content);
5833
                }
5834
                $sub_list = Display::tag('ul', $sub_list.$data, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
5835
                $return .= Display::tag('li', Display::div($item['data'], array('class'=>'item_data')).$sub_list, array('id'=>$key, 'class'=>'record li_container'));
5836
            }
5837
        }
5838
5839
        return $return;
5840
    }
5841
5842
    /**
5843
     * This function builds the action menu
5844
     * @param bool $returnContent
5845
     * @return void
5846
     */
5847
    public function build_action_menu($returnContent = false)
5848
    {
5849
        $gradebook = isset($_GET['gradebook']) ? Security :: remove_XSS($_GET['gradebook']) : null;
5850
        $return = '<div class="actions">';
5851
        $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> ';
5852
        $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>';
5853
        $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>';
5854
        $buttons = array(
5855
            array(
5856
                'title' => get_lang('SetPrerequisiteForEachItem'),
5857
                'href' => 'lp_controller.php?'.api_get_cidreq().'&action=set_previous_step_as_prerequisite&lp_id=' . $_SESSION['oLP']->lp_id,
5858
            ),
5859
            array(
5860
                'title' => get_lang('ClearAllPrerequisites'),
5861
                'href' => 'lp_controller.php?'.api_get_cidreq().'&action=clear_prerequisites&lp_id=' . $_SESSION['oLP']->lp_id,
5862
            ),
5863
        );
5864
        $return .= Display::group_button(get_lang('PrerequisitesOptions'), $buttons);
5865
        $return .= '</div>';
5866
5867
        if ($returnContent) {
5868
            return $return;
5869
        }
5870
        echo $return;
5871
    }
5872
5873
    /**
5874
     * Creates the default learning path folder
5875
     * @param array $course
5876
     * @param int $creatorId
5877
     *
5878
     * @return bool
5879
     */
5880
    public static function generate_learning_path_folder($course, $creatorId = 0)
5881
    {
5882
        // Creating learning_path folder
5883
        $dir = '/learning_path';
5884
        $filepath = api_get_path(SYS_COURSE_PATH).$course['path'] . '/document';
5885
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5886
5887
        $folder = false;
5888
        if (!is_dir($filepath.'/'.$dir)) {
5889
            $folderData = create_unexisting_directory(
5890
                $course,
5891
                $creatorId,
5892
                api_get_session_id(),
5893
                0,
5894
                0,
5895
                $filepath,
5896
                $dir,
5897
                get_lang('LearningPaths'),
5898
                0
5899
            );
5900
            if (!empty($folderData)) {
5901
                $folder = true;
5902
            }
5903
        } else {
5904
            $folder = true;
5905
        }
5906
5907
        return $folder;
5908
    }
5909
5910
    /**
5911
     * @param array $course
5912
     * @param string $lp_name
5913
     * @param int $creatorId
5914
     *
5915
     * @return array
5916
     */
5917
    public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
5918
    {
5919
        $filepath = '';
5920
        $dir = '/learning_path/';
5921
5922
        if (empty($lp_name)) {
5923
            $lp_name = $this->name;
5924
        }
5925
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5926
5927
        $folder = self::generate_learning_path_folder($course, $creatorId);
5928
        // Creating LP folder
5929
        if ($folder) {
5930
            //Limits title size
5931
            $title = api_substr(api_replace_dangerous_char($lp_name), 0 , 80);
5932
            $dir   = $dir.$title;
5933
            $filepath = api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document';
5934
            if (!is_dir($filepath.'/'.$dir)) {
5935
                $folderData = create_unexisting_directory(
5936
                    $course,
5937
                    $creatorId,
5938
                    0,
5939
                    0,
5940
                    0,
5941
                    $filepath,
5942
                    $dir,
5943
                    $lp_name
5944
                );
5945
                if (!empty($folderData)) {
5946
                    $folder = true;
5947
                }
5948
            } else {
5949
                $folder = true;
5950
            }
5951
            $dir = $dir.'/';
5952
            if ($folder) {
5953
                $filepath = api_get_path(SYS_COURSE_PATH) . $course['path'] . '/document'.$dir;
5954
            }
5955
        }
5956
        $array = array(
5957
            'dir' => $dir,
5958
            'filepath' => $filepath,
5959
            'folder' => $folder
5960
        );
5961
        return $array;
5962
    }
5963
5964
    /**
5965
     * Create a new document //still needs some finetuning
5966
     * @param array $courseInfo
5967
     * @param string $content
5968
     * @param string $title
5969
     * @param string $extension
5970
     * @param int $creatorId creator id
5971
     *
5972
     * @return string
5973
     */
5974
    public function create_document($courseInfo, $content = '', $title = '', $extension = 'html', $creatorId = 0)
5975
    {
5976
        if (!empty($courseInfo)) {
5977
            $course_id = $courseInfo['real_id'];
5978
        } else {
5979
            $course_id = api_get_course_int_id();
5980
        }
5981
        $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
5982
        $sessionId = api_get_session_id();
5983
5984
        global $charset;
5985
        $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
5986
        $dir = isset ($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
5987
        // Please, do not modify this dirname formatting.
5988
        if (strstr($dir, '..')) {
5989
            $dir = '/';
5990
        }
5991
        if (!empty($dir[0]) && $dir[0] == '.') {
5992
            $dir = substr($dir, 1);
5993
        }
5994
        if (!empty($dir[0]) && $dir[0] != '/') {
5995
            $dir = '/' . $dir;
5996
        }
5997
        if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
5998
            $dir .= '/';
5999
        }
6000
        $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document' . $dir;
6001
6002
        if (empty($_POST['dir']) && empty($_GET['dir'])) {
6003
            //Generates folder
6004
            $result = $this->generate_lp_folder($courseInfo, '', $creatorId);
6005
            $dir = $result['dir'];
6006
            $filepath = $result['filepath'];
6007
        }
6008
6009 View Code Duplication
        if (!is_dir($filepath)) {
6010
            $filepath = api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/document/';
6011
            $dir = '/';
6012
        }
6013
6014
        // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
6015
        // is already escaped twice when it gets here.
6016
6017
        $originalTitle = !empty($title) ? $title : $_POST['title'];
6018
        if (!empty($title)) {
6019
            $title = api_replace_dangerous_char(stripslashes($title));
6020
        } else {
6021
            $title = api_replace_dangerous_char(stripslashes($_POST['title']));
6022
        }
6023
6024
        $title = disable_dangerous_file($title);
6025
        $filename = $title;
6026
        $content = !empty($content) ? $content : $_POST['content_lp'];
6027
        $tmp_filename = $filename;
6028
6029
        $i = 0;
6030 View Code Duplication
        while (file_exists($filepath . $tmp_filename . '.'.$extension))
6031
            $tmp_filename = $filename . '_' . ++ $i;
6032
6033
        $filename = $tmp_filename . '.'.$extension;
6034
        if ($extension == 'html') {
6035
            $content = stripslashes($content);
6036
            $content = str_replace(
6037
                api_get_path(WEB_COURSE_PATH),
6038
                api_get_path(REL_PATH).'courses/',
6039
                $content
6040
            );
6041
6042
            // Change the path of mp3 to absolute.
6043
6044
            // The first regexp deals with :// urls.
6045
            $content = preg_replace(
6046
                "|(flashvars=\"file=)([^:/]+)/|",
6047
                "$1".api_get_path(
6048
                    REL_COURSE_PATH
6049
                ).$courseInfo['path'].'/document/',
6050
                $content
6051
            );
6052
            // The second regexp deals with audio/ urls.
6053
            $content = preg_replace(
6054
                "|(flashvars=\"file=)([^/]+)/|",
6055
                "$1".api_get_path(
6056
                    REL_COURSE_PATH
6057
                ).$courseInfo['path'].'/document/$2/',
6058
                $content
6059
            );
6060
            // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
6061
            $content = str_replace(
6062
                '</body>',
6063
                '<style type="text/css">body{}</style></body>',
6064
                $content
6065
            );
6066
        }
6067
6068
        if (!file_exists($filepath . $filename)) {
6069
            if ($fp = @ fopen($filepath . $filename, 'w')) {
6070
                fputs($fp, $content);
6071
                fclose($fp);
6072
6073
                $file_size = filesize($filepath . $filename);
6074
                $save_file_path = $dir.$filename;
6075
6076
                $document_id = add_document(
6077
                    $courseInfo,
6078
                    $save_file_path,
6079
                    'file',
6080
                    $file_size,
6081
                    $tmp_filename,
6082
                    '',
6083
                    0, //readonly
6084
                    true,
6085
                    null,
6086
                    $sessionId,
6087
                    $creatorId
6088
                );
6089
6090
                if ($document_id) {
6091
                    api_item_property_update(
6092
                        $courseInfo,
6093
                        TOOL_DOCUMENT,
6094
                        $document_id,
6095
                        'DocumentAdded',
6096
                        $creatorId,
6097
                        null,
6098
                        null,
6099
                        null,
6100
                        null,
6101
                        $sessionId
6102
                    );
6103
6104
                    $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
6105
                    $new_title = $originalTitle;
6106
6107
                    if ($new_comment || $new_title) {
6108
                        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6109
                        $ct = '';
6110
                        if ($new_comment)
6111
                            $ct .= ", comment='" . Database::escape_string($new_comment). "'";
6112
                        if ($new_title)
6113
                            $ct .= ", title='" . Database::escape_string(htmlspecialchars($new_title, ENT_QUOTES, $charset))."' ";
6114
6115
                        $sql = "UPDATE " . $tbl_doc ." SET " . substr($ct, 1)."
6116
                               WHERE c_id = ".$course_id." AND id = " . $document_id;
6117
                        Database::query($sql);
6118
                    }
6119
                }
6120
                return $document_id;
6121
            }
6122
        }
6123
    }
6124
6125
    /**
6126
     * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'
6127
     * @param 	array $_course array
6128
     * @return 	void
6129
     */
6130
    public function edit_document($_course)
6131
    {
6132
        $course_id = api_get_course_int_id();
6133
        global $_configuration;
6134
        // Please, do not modify this dirname formatting.
6135
        $dir = isset($_GET['dir']) ? $_GET['dir'] : $_POST['dir'];
6136
6137
        if (strstr($dir, '..'))
6138
            $dir = '/';
6139
6140
        if ($dir[0] == '.')
6141
            $dir = substr($dir, 1);
6142
6143
        if ($dir[0] != '/')
6144
            $dir = '/' . $dir;
6145
6146
        if ($dir[strlen($dir) - 1] != '/')
6147
            $dir .= '/';
6148
6149
        $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $dir;
6150
6151 View Code Duplication
        if (!is_dir($filepath)) {
6152
            $filepath = api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document/';
6153
            $dir = '/';
6154
        }
6155
6156
        $table_doc = Database :: get_course_table(TABLE_DOCUMENT);
6157
        if (isset($_POST['path']) && !empty($_POST['path'])) {
6158
            $document_id = intval($_POST['path']);
6159
            $sql = "SELECT path FROM " . $table_doc . "
6160
                    WHERE c_id = $course_id AND id = " . $document_id;
6161
            $res = Database::query($sql);
6162
            $row = Database :: fetch_array($res);
6163
            $content = stripslashes($_POST['content_lp']);
6164
            $file = $filepath . $row['path'];
6165
6166
            if ($fp = @ fopen($file, 'w')) {
6167
                $content = str_replace(api_get_path(WEB_COURSE_PATH), $_configuration['url_append'] . '/courses/', $content);
6168
6169
                // Change the path of mp3 to absolute.
6170
                // The first regexp deals with :// urls.
6171
                $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/', $content);
6172
                // The second regexp deals with audio/ urls.
6173
                $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1" . api_get_path(REL_COURSE_PATH) . $_course['path'] . '/document/$2/', $content);
6174
                fputs($fp, $content);
6175
                fclose($fp);
6176
6177
                $sql = "UPDATE " . $table_doc ." SET
6178
                            title='".Database::escape_string($_POST['title'])."'
6179
                        WHERE c_id = ".$course_id." AND id = " . $document_id;
6180
                Database::query($sql);
6181
            }
6182
        }
6183
    }
6184
6185
    /**
6186
     * Displays the selected item, with a panel for manipulating the item
6187
     * @param int $item_id
6188
     * @param string $msg
6189
     * @return string
6190
     */
6191
    public function display_item($item_id, $msg = null, $show_actions = true)
6192
    {
6193
        $course_id = api_get_course_int_id();
6194
        $return = '';
6195
        if (is_numeric($item_id)) {
6196
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6197
            $sql = "SELECT lp.* FROM " . $tbl_lp_item . " as lp
6198
                    WHERE c_id = ".$course_id." AND lp.id = " . intval($item_id);
6199
            $result = Database::query($sql);
6200
            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...
6201
                $_SESSION['parent_item_id'] = ($row['item_type'] == 'dokeos_chapter' || $row['item_type'] == 'dokeos_module' || $row['item_type'] == 'dir') ? $item_id : 0;
6202
6203
                // Prevents wrong parent selection for document, see Bug#1251.
6204
                if ($row['item_type'] != 'dokeos_chapter' || $row['item_type'] != 'dokeos_module') {
6205
                    $_SESSION['parent_item_id'] = $row['parent_item_id'];
6206
                }
6207
6208
                if ($show_actions) {
6209
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6210
                }
6211
                $return .= '<div style="padding:10px;">';
6212
6213
                if ($msg != '')
6214
                    $return .= $msg;
6215
6216
                $return .= '<h3>'.$row['title'].'</h3>';
6217
                switch ($row['item_type']) {
6218
                    case TOOL_QUIZ:
6219
                        if (!empty($row['path'])) {
6220
                            $exercise = new Exercise();
6221
                            $exercise->read($row['path']);
6222
                            $return .= $exercise->description.'<br />';
6223
                        }
6224
                        break;
6225
                    case TOOL_DOCUMENT:
6226
                        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6227
                        $sql_doc = "SELECT path FROM " . $tbl_doc . "
6228
                                    WHERE c_id = ".$course_id." AND id = " . intval($row['path']);
6229
                        $result = Database::query($sql_doc);
6230
                        $path_file = Database::result($result, 0, 0);
6231
                        $path_parts = pathinfo($path_file);
6232
                        // TODO: Correct the following naive comparisons, also, htm extension is missing.
6233
                        if (in_array($path_parts['extension'], array(
6234
                            'html',
6235
                            'txt',
6236
                            'png',
6237
                            'jpg',
6238
                            'JPG',
6239
                            'jpeg',
6240
                            'JPEG',
6241
                            'gif',
6242
                            'swf'
6243
                        ))) {
6244
                            $return .= $this->display_document($row['path'], true, true);
6245
                        }
6246
                        break;
6247
                }
6248
                $return .= '</div>';
6249
            }
6250
        }
6251
6252
        return $return;
6253
    }
6254
6255
    /**
6256
     * Shows the needed forms for editing a specific item
6257
     * @param int $item_id
6258
     * @return string
6259
     */
6260
    public function display_edit_item($item_id)
6261
    {
6262
        $course_id = api_get_course_int_id();
6263
        $return = '';
6264
        if (is_numeric($item_id)) {
6265
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6266
            $sql = "SELECT * FROM $tbl_lp_item
6267
                    WHERE c_id = ".$course_id." AND id = " . intval($item_id);
6268
            $res = Database::query($sql);
6269
            $row = Database::fetch_array($res);
6270
6271
            switch ($row['item_type']) {
6272
                case 'dokeos_chapter' :
6273
                case 'dir' :
6274
                case 'asset' :
6275 View Code Duplication
                case 'sco' :
6276
                    if (isset ($_GET['view']) && $_GET['view'] == 'build') {
6277
                        $return .= $this->display_manipulate($item_id, $row['item_type']);
6278
                        $return .= $this->display_item_form($row['item_type'], get_lang('EditCurrentChapter') . ' :', 'edit', $item_id, $row);
6279
                    } else {
6280
                        $return .= $this->display_item_small_form($row['item_type'], get_lang('EditCurrentChapter') . ' :', $row);
6281
                    }
6282
                    break;
6283
                case TOOL_DOCUMENT :
6284
                    $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6285
                    $sql = "SELECT lp.*, doc.path as dir
6286
                            FROM " . $tbl_lp_item . " as lp
6287
                            LEFT JOIN " . $tbl_doc . " as doc
6288
                            ON doc.id = lp.path
6289
                            WHERE
6290
                                lp.c_id = $course_id AND
6291
                                doc.c_id = $course_id AND
6292
                                lp.id = " . intval($item_id);
6293
                    $res_step = Database::query($sql);
6294
                    $row_step = Database :: fetch_array($res_step);
6295
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6296
                    var_dump($item_id, $row_step);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($item_id, $row_step); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
6297
                    $return .= $this->display_document_form('edit', $item_id, $row_step);
6298
                    break;
6299
                case TOOL_LINK :
6300
                    $link_id = (string) $row['path'];
6301
                    if (ctype_digit($link_id)) {
6302
                        $tbl_link = Database :: get_course_table(TABLE_LINK);
6303
                        $sql_select = 'SELECT url FROM ' . $tbl_link . '
6304
                                       WHERE c_id = '.$course_id.' AND id = ' . intval($link_id);
6305
                        $res_link = Database::query($sql_select);
6306
                        $row_link = Database :: fetch_array($res_link);
6307
                        if (is_array($row_link)) {
6308
                            $row['url'] = $row_link['url'];
6309
                        }
6310
                    }
6311
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6312
                    $return .= $this->display_link_form('edit', $item_id, $row);
6313
                    break;
6314 View Code Duplication
                case 'dokeos_module' :
6315
                    if (isset ($_GET['view']) && $_GET['view'] == 'build') {
6316
                        $return .= $this->display_manipulate($item_id, $row['item_type']);
6317
                        $return .= $this->display_item_form($row['item_type'], get_lang('EditCurrentModule') . ' :', 'edit', $item_id, $row);
6318
                    } else {
6319
                        $return .= $this->display_item_small_form($row['item_type'], get_lang('EditCurrentModule') . ' :', $row);
6320
                    }
6321
                    break;
6322 View Code Duplication
                case TOOL_QUIZ :
6323
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6324
                    $return .= $this->display_quiz_form('edit', $item_id, $row);
6325
                    break;
6326
                case TOOL_HOTPOTATOES :
6327
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6328
                    $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
6329
                    break;
6330 View Code Duplication
                case TOOL_STUDENTPUBLICATION :
6331
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6332
                    $return .= $this->display_student_publication_form('edit', $item_id, $row);
6333
                    break;
6334
                case TOOL_FORUM :
6335
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6336
                    $return .= $this->display_forum_form('edit', $item_id, $row);
6337
                    break;
6338 View Code Duplication
                case TOOL_THREAD :
6339
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
6340
                    $return .= $this->display_thread_form('edit', $item_id, $row);
6341
                    break;
6342
            }
6343
        }
6344
6345
        return $return;
6346
    }
6347
6348
    /**
6349
     * Function that displays a list with al the resources that
6350
     * could be added to the learning path
6351
     * @return string
6352
     */
6353
    public function display_resources()
6354
    {
6355
        $course_code = api_get_course_id();
6356
6357
        // Get all the docs.
6358
        $documents = $this->get_documents(true);
6359
6360
        // Get all the exercises.
6361
        $exercises = $this->get_exercises();
6362
6363
        // Get all the links.
6364
        $links = $this->get_links();
6365
6366
        // Get al the student publications.
6367
        $works = $this->get_student_publications();
6368
6369
        // Get al the forums.
6370
        $forums = $this->get_forums(null, $course_code);
6371
6372
        $finish = $this->getFinalItemForm();
6373
6374
        $headers = array(
6375
            Display::return_icon('folder_document.png', get_lang('Documents'), array(), ICON_SIZE_BIG),
6376
            Display::return_icon('quiz.png',  get_lang('Quiz'), array(), ICON_SIZE_BIG),
6377
            Display::return_icon('links.png', get_lang('Links'), array(), ICON_SIZE_BIG),
6378
            Display::return_icon('works.png', get_lang('Works'), array(), ICON_SIZE_BIG),
6379
            Display::return_icon('forum.png', get_lang('Forums'), array(), ICON_SIZE_BIG),
6380
            Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), array(), ICON_SIZE_BIG),
6381
            Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
6382
        );
6383
6384
        echo Display::display_normal_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'));
6385
        $chapter = $_SESSION['oLP']->display_item_form('chapter', get_lang('EnterDataNewChapter'), 'add_item');
6386
        echo Display::tabs(
6387
            $headers,
6388
            array($documents, $exercises, $links, $works, $forums, $chapter, $finish), 'resource_tab'
6389
        );
6390
6391
        return true;
6392
    }
6393
6394
    /**
6395
     * Returns the extension of a document
6396
     * @param string filename
6397
     * @return string Extension (part after the last dot)
6398
     */
6399
    public function get_extension($filename)
6400
    {
6401
        $explode = explode('.', $filename);
6402
        return $explode[count($explode) - 1];
6403
    }
6404
6405
    /**
6406
     * Displays a document by id
6407
     *
6408
     * @param int $id
6409
     * @return string
6410
     */
6411
    public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
6412
    {
6413
        $_course = api_get_course_info();
6414
        $course_id = api_get_course_int_id();
6415
        $return = '';
6416
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
6417
        $sql_doc = "SELECT * FROM " . $tbl_doc . "
6418
                    WHERE c_id = ".$course_id." AND id = " . $id;
6419
        $res_doc = Database::query($sql_doc);
6420
        $row_doc = Database :: fetch_array($res_doc);
6421
6422
        // TODO: Add a path filter.
6423
        if ($iframe) {
6424
            $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>';
6425
        } else {
6426
            $return .= file_get_contents(api_get_path(SYS_COURSE_PATH) . $_course['path'] . '/document' . $row_doc['path']);
6427
        }
6428
6429
        return $return;
6430
    }
6431
6432
    /**
6433
     * Return HTML form to add/edit a quiz
6434
     * @param	string	Action (add/edit)
6435
     * @param	integer	Item ID if already exists
6436
     * @param	mixed	Extra information (quiz ID if integer)
6437
     * @return	string	HTML form
6438
     */
6439
    public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
6440
    {
6441
        $course_id = api_get_course_int_id();
6442
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6443
        $tbl_quiz = Database :: get_course_table(TABLE_QUIZ_TEST);
6444
6445 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6446
            $item_title = $extra_info['title'];
6447
            $item_description = $extra_info['description'];
6448
        } elseif (is_numeric($extra_info)) {
6449
            $sql = "SELECT title, description
6450
                    FROM " . $tbl_quiz . "
6451
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
6452
6453
            $result = Database::query($sql);
6454
            $row = Database::fetch_array($result);
6455
            $item_title = $row['title'];
6456
            $item_description = $row['description'];
6457
        } else {
6458
            $item_title = '';
6459
            $item_description = '';
6460
        }
6461
        $item_title			= Security::remove_XSS($item_title);
6462
        $item_description 	= Security::remove_XSS($item_description);
6463
6464
        $legend = '<legend>';
6465 View Code Duplication
        if ($id != 0 && is_array($extra_info))
6466
            $parent = $extra_info['parent_item_id'];
6467
        else
6468
            $parent = 0;
6469
6470
        $sql = "SELECT * FROM " . $tbl_lp_item . "
6471
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
6472
6473
        $result = Database::query($sql);
6474
        $arrLP = array ();
6475 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6476
            $arrLP[] = array (
6477
                'id' => $row['id'],
6478
                'item_type' => $row['item_type'],
6479
                'title' => $row['title'],
6480
                'path' => $row['path'],
6481
                'description' => $row['description'],
6482
                'parent_item_id' => $row['parent_item_id'],
6483
                'previous_item_id' => $row['previous_item_id'],
6484
                'next_item_id' => $row['next_item_id'],
6485
                'display_order' => $row['display_order'],
6486
                'max_score' => $row['max_score'],
6487
                'min_score' => $row['min_score'],
6488
                'mastery_score' => $row['mastery_score'],
6489
                'prerequisite' => $row['prerequisite'],
6490
                'max_time_allowed' => $row['max_time_allowed']
6491
            );
6492
        }
6493
6494
        $this->tree_array($arrLP);
6495
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
6496
        unset ($this->arrMenu);
6497
6498
        if ($action == 'add') {
6499
            $legend .= get_lang('CreateTheExercise') . '&nbsp;:';
6500
        } elseif ($action == 'move') {
6501
            $legend .= get_lang('MoveTheCurrentExercise') . '&nbsp;:';
6502
        } else {
6503
            $legend .= get_lang('EditCurrentExecice') . '&nbsp;:';
6504
        }
6505
6506 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
6507
            $legend .= Display :: return_warning_message(get_lang('Warning') . ' ! ' . get_lang('WarningEditingDocument'));
6508
        }
6509
6510
        $legend .= '</legend>';
6511
        $return = '';
6512
        $return .= '<div class="sectioncomment">';
6513
6514
        $return .= '<form method="POST">';
6515
        $return .= $legend;
6516
        $return .= '<table class="lp_form">';
6517
6518 View Code Duplication
        if ($action != 'move') {
6519
            $return .= '<tr>';
6520
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . '</label></td>';
6521
            $return .= '<td class="input"><input id="idTitle" name="title" size="44" type="text" value="' . $item_title . '" /></td>';
6522
            $return .= '</tr>';
6523
        }
6524
6525
        $return .= '<tr>';
6526
6527
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . '</label></td>';
6528
        $return .= '<td class="input">';
6529
6530
        // Select for Parent item, root or chapter
6531
        $return .= '<select id="idParent" style="width:100%;" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
6532
6533
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
6534
6535
        $arrHide = array (
6536
            $id
6537
        );
6538 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6539
            if ($action != 'add') {
6540
                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)) {
6541
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6542
                } else {
6543
                    $arrHide[] = $arrLP[$i]['id'];
6544
                }
6545
            } else {
6546
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
6547
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6548
            }
6549
        }
6550
        if (is_array($arrLP)) {
6551
            reset($arrLP);
6552
        }
6553
6554
        $return .= '</select>';
6555
        $return .= '</td>';
6556
        $return .= '</tr>';
6557
        $return .= '<tr>';
6558
6559
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . '</label></td>';
6560
        $return .= '<td class="input">';
6561
6562
        $return .= '<select class="learnpath_item_form" style="width:100%;" id="previous" name="previous" size="1">';
6563
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
6564 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6565
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
6566
                if (is_array($extra_info)) {
6567
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
6568
                        $selected = 'selected="selected" ';
6569
                    }
6570
                } elseif ($action == 'add') {
6571
                    $selected = 'selected="selected" ';
6572
                } else {
6573
                    $selected = '';
6574
                }
6575
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' . get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
6576
            }
6577
        }
6578
        $return .= '</select>';
6579
6580
        $return .= '</td>';
6581
        $return .= '</tr>';
6582
        if ($action != 'move') {
6583
            $id_prerequisite = 0;
6584
            if (is_array($arrLP)) {
6585
                foreach ($arrLP as $key => $value) {
6586
                    if ($value['id'] == $id) {
6587
                        $id_prerequisite = $value['prerequisite'];
6588
                        break;
6589
                    }
6590
                }
6591
            }
6592
            $arrHide = array ();
6593
            for ($i = 0; $i < count($arrLP); $i++) {
6594
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
6595
                    if (is_array($extra_info)) {
6596
                        if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
6597
                            $s_selected_position = $arrLP[$i]['id'];
6598
                        }
6599
                    } elseif ($action == 'add') {
6600
                        $s_selected_position = 0;
6601
                    }
6602
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
6603
                }
6604
            }
6605
            /*// Commented the prerequisites, only visible in edit (exercise).
6606
            $return .= '<tr>';
6607
            $return .= '<td class="label"><label for="idPrerequisites">'.get_lang('LearnpathPrerequisites').'</label></td>';
6608
            $return .= '<td class="input"><select name="prerequisites" id="prerequisites" class="learnpath_item_form"><option value="0">'.get_lang('NoPrerequisites').'</option>';
6609
6610
                foreach($arrHide as $key => $value){
6611
                    if($key==$s_selected_position && $action == 'add'){
6612
                        $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
6613
                    }
6614
                    elseif($key==$id_prerequisite && $action == 'edit'){
6615
                        $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
6616
                    }
6617
                    else{
6618
                        $return .= '<option value="'.$key.'">'.$value['value'].'</option>';
6619
                    }
6620
                }
6621
6622
            $return .= "</select></td>";
6623
            */
6624
            $return .= '</tr>';
6625
            /*$return .= '<tr>';
6626
            $return .= '<td class="label"><label for="maxTimeAllowed">' . get_lang('MaxTimeAllowed') . '</label></td>';
6627
            $return .= '<td class="input"><input name="maxTimeAllowed" style="width:98%;" id="maxTimeAllowed" value="' . $extra_info['max_time_allowed'] . '" /></td>';
6628
6629
            // Remove temporarily the test description.
6630
            //$return .= '<td class="label"><label for="idDescription">'.get_lang('Description').' :</label></td>';
6631
            //$return .= '<td class="input"><textarea id="idDescription" name="description" rows="4">' . $item_description . '</textarea></td>';
6632
6633
            $return .= '</tr>'; */
6634
        }
6635
6636
        $return .= '<tr>';
6637
        if ($action == 'add') {
6638
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit">' . get_lang('AddExercise') . '</button></td>';
6639
        } else {
6640
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit">' . get_lang('EditCurrentExecice') . '</button></td>';
6641
        }
6642
6643
        $return .= '</tr>';
6644
        $return .= '</table>';
6645
6646 View Code Duplication
        if ($action == 'move') {
6647
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
6648
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
6649
        }
6650
6651 View Code Duplication
        if (is_numeric($extra_info)) {
6652
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
6653
        } elseif (is_array($extra_info)) {
6654
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
6655
        }
6656
6657
        $return .= '<input name="type" type="hidden" value="' . TOOL_QUIZ . '" />';
6658
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
6659
6660
        $return .= '</form>';
6661
        $return .= '</div>';
6662
6663
        return $return;
6664
    }
6665
6666
    /**
6667
     * Addition of Hotpotatoes tests
6668
     * @param	string	Action
6669
     * @param	integer	Internal ID of the item
6670
     * @param	mixed	Extra information - can be an array with title and description indexes
6671
     * @return  string	HTML structure to display the hotpotatoes addition formular
6672
     */
6673
    public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
6674
    {
6675
        $course_id = api_get_course_int_id();
6676
        $uploadPath = DIR_HOTPOTATOES; //defined in main_api
6677
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6678
6679
        if ($id != 0 && is_array($extra_info)) {
6680
            $item_title = stripslashes($extra_info['title']);
6681
            $item_description = stripslashes($extra_info['description']);
6682
        } elseif (is_numeric($extra_info)) {
6683
            $TBL_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
6684
6685
            $sql = "SELECT * FROM " . $TBL_DOCUMENT . "
6686
                    WHERE
6687
                        c_id = ".$course_id." AND
6688
                        path LIKE '" . $uploadPath . "/%/%htm%' AND
6689
                        id = " . (int) $extra_info . "
6690
                    ORDER BY id ASC";
6691
6692
            $res_hot = Database::query($sql);
6693
            $row = Database::fetch_array($res_hot);
6694
6695
            $item_title = $row['title'];
6696
            $item_description = $row['description'];
6697
6698
            if (!empty ($row['comment'])) {
6699
                $item_title = $row['comment'];
6700
            }
6701
        } else {
6702
            $item_title = '';
6703
            $item_description = '';
6704
        }
6705
6706 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6707
            $parent = $extra_info['parent_item_id'];
6708
        } else {
6709
            $parent = 0;
6710
        }
6711
6712
        $sql = "SELECT * FROM $tbl_lp_item
6713
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
6714
        $result = Database::query($sql);
6715
        $arrLP = array ();
6716 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6717
            $arrLP[] = array (
6718
                'id' => $row['id'],
6719
                'item_type' => $row['item_type'],
6720
                'title' => $row['title'],
6721
                'path' => $row['path'],
6722
                'description' => $row['description'],
6723
                'parent_item_id' => $row['parent_item_id'],
6724
                'previous_item_id' => $row['previous_item_id'],
6725
                'next_item_id' => $row['next_item_id'],
6726
                'display_order' => $row['display_order'],
6727
                'max_score' => $row['max_score'],
6728
                'min_score' => $row['min_score'],
6729
                'mastery_score' => $row['mastery_score'],
6730
                'prerequisite' => $row['prerequisite'],
6731
                'max_time_allowed' => $row['max_time_allowed']
6732
            );
6733
        }
6734
6735
        $legend = '<legend>';
6736
        if ($action == 'add')
6737
            $legend .= get_lang('CreateTheExercise');
6738
        elseif ($action == 'move') $legend .= get_lang('MoveTheCurrentExercise');
6739
        else
6740
            $legend .= get_lang('EditCurrentExecice');
6741 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
6742
            $legend .= Display :: return_warning_message(get_lang('Warning') . ' ! ' . get_lang('WarningEditingDocument'));
6743
        }
6744
        $legend .= '</legend>';
6745
6746
        $return = '<form method="POST">';
6747
        $return .= $legend;
6748
        $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
6749
        $return .= '<tr>';
6750
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . ' :</label></td>';
6751
        $return .= '<td class="input">';
6752
        $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
6753
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
6754
        $arrHide = array (
6755
            $id
6756
        );
6757
6758
        if (count($arrLP) > 0) {
6759 View Code Duplication
            for ($i = 0; $i < count($arrLP); $i++) {
6760
                if ($action != 'add') {
6761
                    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)) {
6762
                        $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6763
                    } else {
6764
                        $arrHide[] = $arrLP[$i]['id'];
6765
                    }
6766
                } else {
6767
                    if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
6768
                        $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6769
                }
6770
            }
6771
6772
            reset($arrLP);
6773
        }
6774
6775
        $return .= '</select>';
6776
        $return .= '</td>';
6777
        $return .= '</tr>';
6778
        $return .= '<tr>';
6779
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . ' :</label></td>';
6780
        $return .= '<td class="input">';
6781
        $return .= '<select id="previous" name="previous" size="1">';
6782
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
6783
6784 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6785
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
6786
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
6787
                    $selected = 'selected="selected" ';
6788
                elseif ($action == 'add') $selected = 'selected="selected" ';
6789
                else
6790
                    $selected = '';
6791
6792
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' . get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
6793
            }
6794
        }
6795
6796
        $return .= '</select>';
6797
        $return .= '</td>';
6798
        $return .= '</tr>';
6799
6800
        if ($action != 'move') {
6801
            $return .= '<tr>';
6802
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . ' :</label></td>';
6803
            $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="' . $item_title . '" /></td>';
6804
            $return .= '</tr>';
6805
            $id_prerequisite = 0;
6806 View Code Duplication
            if (is_array($arrLP) && count($arrLP) > 0) {
6807
                foreach ($arrLP as $key => $value) {
6808
                    if ($value['id'] == $id) {
6809
                        $id_prerequisite = $value['prerequisite'];
6810
                        break;
6811
                    }
6812
                }
6813
6814
                $arrHide = array ();
6815
                for ($i = 0; $i < count($arrLP); $i++) {
6816
                    if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
6817
                        if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
6818
                            $s_selected_position = $arrLP[$i]['id'];
6819
                        elseif ($action == 'add') $s_selected_position = 0;
6820
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
6821
6822
                    }
6823
                }
6824
            }
6825
        }
6826
6827
        $return .= '<tr>';
6828
        $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">' . get_lang('SaveHotpotatoes') . '</button></td>';
6829
        $return .= '</tr>';
6830
        $return .= '</table>';
6831
6832 View Code Duplication
        if ($action == 'move') {
6833
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
6834
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
6835
        }
6836
6837 View Code Duplication
        if (is_numeric($extra_info)) {
6838
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
6839
        } elseif (is_array($extra_info)) {
6840
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
6841
        }
6842
        $return .= '<input name="type" type="hidden" value="' . TOOL_HOTPOTATOES . '" />';
6843
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
6844
        $return .= '</form>';
6845
6846
        return $return;
6847
    }
6848
6849
    /**
6850
     * Return the form to display the forum edit/add option
6851
     * @param	string	Action (add/edit)
6852
     * @param	integer	ID of the lp_item if already exists
6853
     * @param	mixed	Forum ID or title
6854
     * @return	string	HTML form
6855
     */
6856
    public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
6857
    {
6858
        $course_id = api_get_course_int_id();
6859
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
6860
        $tbl_forum = Database :: get_course_table(TABLE_FORUM);
6861
6862 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6863
            $item_title = stripslashes($extra_info['title']);
6864
        } elseif (is_numeric($extra_info)) {
6865
            $sql = "SELECT forum_title as title, forum_comment as comment
6866
                    FROM " . $tbl_forum . "
6867
                    WHERE c_id = ".$course_id." AND forum_id = " . $extra_info;
6868
6869
            $result = Database::query($sql);
6870
            $row = Database :: fetch_array($result);
6871
6872
            $item_title = $row['title'];
6873
            $item_description = $row['comment'];
6874
        } else {
6875
            $item_title = '';
6876
            $item_description = '';
6877
        }
6878
6879
        $legend = '<legend>';
6880
6881 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
6882
            $parent = $extra_info['parent_item_id'];
6883
        } else {
6884
            $parent = 0;
6885
        }
6886
6887
        $sql = "SELECT * FROM " . $tbl_lp_item . "
6888
                WHERE
6889
                    c_id = ".$course_id." AND
6890
                    lp_id = " . $this->lp_id;
6891
        $result = Database::query($sql);
6892
        $arrLP = array();
6893
6894 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
6895
            $arrLP[] = array (
6896
                'id' => $row['id'],
6897
                'item_type' => $row['item_type'],
6898
                'title' => $row['title'],
6899
                'path' => $row['path'],
6900
                'description' => $row['description'],
6901
                'parent_item_id' => $row['parent_item_id'],
6902
                'previous_item_id' => $row['previous_item_id'],
6903
                'next_item_id' => $row['next_item_id'],
6904
                'display_order' => $row['display_order'],
6905
                'max_score' => $row['max_score'],
6906
                'min_score' => $row['min_score'],
6907
                'mastery_score' => $row['mastery_score'],
6908
                'prerequisite' => $row['prerequisite']
6909
            );
6910
        }
6911
6912
        $this->tree_array($arrLP);
6913
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
6914
        unset($this->arrMenu);
6915
6916
        if ($action == 'add')
6917
            $legend .= get_lang('CreateTheForum') . '&nbsp;:';
6918
        elseif ($action == 'move') $legend .= get_lang('MoveTheCurrentForum') . '&nbsp;:';
6919
        else
6920
            $legend .= get_lang('EditCurrentForum') . '&nbsp;:';
6921
6922
        $legend .= '</legend>';
6923
        $return = '<div class="sectioncomment">';
6924
        $return .= '<form method="POST">';
6925
        $return .= $legend;
6926
        $return .= '<table class="lp_form">';
6927
6928 View Code Duplication
        if ($action != 'move') {
6929
            $return .= '<tr>';
6930
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . '</label></td>';
6931
            $return .= '<td class="input"><input id="idTitle" size="44" name="title" type="text" value="' . $item_title . '" class="learnpath_item_form" /></td>';
6932
            $return .= '</tr>';
6933
        }
6934
6935
        $return .= '<tr>';
6936
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . '</label></td>';
6937
        $return .= '<td class="input">';
6938
        $return .= '<select id="idParent" style="width:100%;" name="parent" onChange="javascript: load_cbo(this.value);" class="learnpath_item_form" size="1">';
6939
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
6940
        $arrHide = array(
6941
            $id
6942
        );
6943
6944
        //$parent_item_id = $_SESSION['parent_item_id'];
6945 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6946
            if ($action != 'add') {
6947
                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)) {
6948
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6949
                } else {
6950
                    $arrHide[] = $arrLP[$i]['id'];
6951
                }
6952
            } else {
6953
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
6954
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
6955
            }
6956
        }
6957
        if (is_array($arrLP)) {
6958
            reset($arrLP);
6959
        }
6960
6961
        $return .= '</select>';
6962
        $return .= '</td>';
6963
        $return .= '</tr>';
6964
        $return .= '<tr>';
6965
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . '</label></td>';
6966
        $return .= '<td class="input">';
6967
        $return .= '<select id="previous" name="previous" style="width:100%;" size="1" class="learnpath_item_form">';
6968
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
6969
6970 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
6971
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
6972
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
6973
                    $selected = 'selected="selected" ';
6974
                elseif ($action == 'add') $selected = 'selected="selected" ';
6975
                else
6976
                    $selected = '';
6977
6978
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' .
6979
                    get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
6980
            }
6981
        }
6982
6983
        $return .= '</select>';
6984
        $return .= '</td>';
6985
        $return .= '</tr>';
6986
        if ($action != 'move') {
6987
            $return .= '<tr>';
6988
            $return .= '</tr>';
6989
            $id_prerequisite = 0;
6990
            if (is_array($arrLP)) {
6991
                foreach ($arrLP as $key => $value) {
6992
                    if ($value['id'] == $id) {
6993
                        $id_prerequisite = $value['prerequisite'];
6994
                        break;
6995
                    }
6996
                }
6997
            }
6998
6999
            $arrHide = array();
7000
            for ($i = 0; $i < count($arrLP); $i++) {
7001
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7002
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7003
                        $s_selected_position = $arrLP[$i]['id'];
7004
                    elseif ($action == 'add') $s_selected_position = 0;
7005
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7006
                }
7007
            }
7008
            $return .= '</tr>';
7009
        }
7010
        $return .= '<tr>';
7011
7012
        if ($action == 'add') {
7013
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit"> ' . get_lang('AddForumToCourse') . ' </button></td>';
7014
        } else {
7015
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit"> ' . get_lang('EditCurrentForum') . ' </button></td>';
7016
        }
7017
        $return .= '</tr>';
7018
        $return .= '</table>';
7019
7020 View Code Duplication
        if ($action == 'move') {
7021
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
7022
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
7023
        }
7024
7025 View Code Duplication
        if (is_numeric($extra_info)) {
7026
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
7027
        } elseif (is_array($extra_info)) {
7028
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
7029
        }
7030
        $return .= '<input name="type" type="hidden" value="' . TOOL_FORUM . '" />';
7031
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
7032
        $return .= '</form>';
7033
        $return .= '</div>';
7034
7035
        return $return;
7036
    }
7037
7038
    /**
7039
     * Return HTML form to add/edit forum threads
7040
     * @param	string	Action (add/edit)
7041
     * @param	integer	Item ID if already exists in learning path
7042
     * @param	mixed	Extra information (thread ID if integer)
7043
     * @return 	string	HTML form
7044
     */
7045
    public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
7046
    {
7047
        $course_id = api_get_course_int_id();
7048
        if (empty($course_id)) {
7049
            return null;
7050
        }
7051
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7052
        $tbl_forum = Database :: get_course_table(TABLE_FORUM_THREAD);
7053
7054
        if ($id != 0 && is_array($extra_info)) {
7055
            $item_title = stripslashes($extra_info['title']);
7056 View Code Duplication
        } elseif (is_numeric($extra_info)) {
7057
            $sql = "SELECT thread_title as title FROM $tbl_forum
7058
                    WHERE c_id = $course_id AND thread_id = " . $extra_info;
7059
7060
            $result = Database::query($sql);
7061
            $row = Database :: fetch_array($result);
7062
7063
            $item_title = $row['title'];
7064
            $item_description = '';
7065
        } else {
7066
            $item_title = '';
7067
            $item_description = '';
7068
        }
7069
7070
        $return = null;
7071
7072 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7073
            $parent = $extra_info['parent_item_id'];
7074
        } else {
7075
            $parent = 0;
7076
        }
7077
7078
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7079
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7080
7081
        $result = Database::query($sql);
7082
7083
        $arrLP = array ();
7084
7085 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7086
            $arrLP[] = array (
7087
                'id' => $row['id'],
7088
                'item_type' => $row['item_type'],
7089
                'title' => $row['title'],
7090
                'path' => $row['path'],
7091
                'description' => $row['description'],
7092
                'parent_item_id' => $row['parent_item_id'],
7093
                'previous_item_id' => $row['previous_item_id'],
7094
                'next_item_id' => $row['next_item_id'],
7095
                'display_order' => $row['display_order'],
7096
                'max_score' => $row['max_score'],
7097
                'min_score' => $row['min_score'],
7098
                'mastery_score' => $row['mastery_score'],
7099
                'prerequisite' => $row['prerequisite']
7100
            );
7101
        }
7102
7103
        $this->tree_array($arrLP);
7104
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7105
        unset ($this->arrMenu);
7106
7107
        $return .= '<form method="POST">';
7108
        if ($action == 'add')
7109
            $return .= '<legend>' . get_lang('CreateTheForum') . '</legend>';
7110
        elseif ($action == 'move') $return .= '<p class="lp_title">' . get_lang('MoveTheCurrentForum') . '&nbsp;:</p>';
7111
        else
7112
            $return .= '<legend>' . get_lang('EditCurrentForum') . '</legend>';
7113
7114
        $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
7115
        $return .= '<tr>';
7116
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . '</label></td>';
7117
        $return .= '<td class="input">';
7118
        $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
7119
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
7120
        $arrHide = array (
7121
            $id
7122
        );
7123
7124 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7125
            if ($action != 'add') {
7126
                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)) {
7127
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
7128
                } else {
7129
                    $arrHide[] = $arrLP[$i]['id'];
7130
                }
7131
            } else {
7132
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
7133
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
7134
            }
7135
        }
7136
7137
        if ($arrLP != null) {
7138
            reset($arrLP);
7139
        }
7140
7141
        $return .= '</select>';
7142
        $return .= '</td>';
7143
        $return .= '</tr>';
7144
        $return .= '<tr>';
7145
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . '</label></td>';
7146
        $return .= '<td class="input">';
7147
        $return .= '<select id="previous" name="previous" size="1">';
7148
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
7149 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7150
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7151
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7152
                    $selected = 'selected="selected" ';
7153
                elseif ($action == 'add') $selected = 'selected="selected" ';
7154
                else
7155
                    $selected = '';
7156
7157
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' . get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
7158
            }
7159
        }
7160
        $return .= '</select>';
7161
        $return .= '</td>';
7162
        $return .= '</tr>';
7163
        if ($action != 'move') {
7164
            $return .= '<tr>';
7165
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . '</label></td>';
7166
            $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="' . $item_title . '" /></td>';
7167
            $return .= '</tr>';
7168
            $return .= '<tr>';
7169
            $return .= '</tr>';
7170
7171
            $id_prerequisite = 0;
7172
            if ($arrLP != null) {
7173
                foreach ($arrLP as $key => $value) {
7174
                    if ($value['id'] == $id) {
7175
                        $id_prerequisite = $value['prerequisite'];
7176
                        break;
7177
                    }
7178
                }
7179
            }
7180
7181
            $arrHide = array();
7182
            for ($i = 0; $i < count($arrLP); $i++) {
7183
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7184
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7185
                        $s_selected_position = $arrLP[$i]['id'];
7186
                    elseif ($action == 'add') $s_selected_position = 0;
7187
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7188
7189
                }
7190
            }
7191
7192
            $return .= '<tr>';
7193
            $return .= '<td class="label"><label for="idPrerequisites">' . get_lang('LearnpathPrerequisites') . '</label></td>';
7194
            $return .= '<td class="input"><select name="prerequisites" id="prerequisites"><option value="0">' . get_lang('NoPrerequisites') . '</option>';
7195
7196
            foreach ($arrHide as $key => $value) {
7197
                if ($key == $s_selected_position && $action == 'add') {
7198
                    $return .= '<option value="' . $key . '" selected="selected">' . $value['value'] . '</option>';
7199
                }
7200
                elseif ($key == $id_prerequisite && $action == 'edit') {
7201
                    $return .= '<option value="' . $key . '" selected="selected">' . $value['value'] . '</option>';
7202
                } else {
7203
                    $return .= '<option value="' . $key . '">' . $value['value'] . '</option>';
7204
                }
7205
            }
7206
            $return .= "</select></td>";
7207
            $return .= '</tr>';
7208
7209
        }
7210
        $return .= '<tr>';
7211
        $return .= '<td></td><td>
7212
                    <button class="save" name="submit_button" type="submit" value="'.get_lang('Ok').'" />'.get_lang('Ok').'</button></td>';
7213
        $return .= '</tr>';
7214
        $return .= '</table>';
7215
7216 View Code Duplication
        if ($action == 'move') {
7217
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
7218
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
7219
        }
7220
7221 View Code Duplication
        if (is_numeric($extra_info)) {
7222
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
7223
        }
7224
        elseif (is_array($extra_info)) {
7225
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
7226
        }
7227
7228
        $return .= '<input name="type" type="hidden" value="' . TOOL_THREAD . '" />';
7229
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
7230
        $return .= '</form>';
7231
        $return .= '</div>';
7232
7233
        return $return;
7234
    }
7235
7236
    /**
7237
     * Return the HTML form to display an item (generally a section/module item)
7238
     * @param	string	Item type (module/dokeos_module)
7239
     * @param	string	Title (optional, only when creating)
7240
     * @param	string	Action ('add'/'edit')
7241
     * @param	integer	lp_item ID
7242
     * @param	mixed	Extra info
7243
     * @return	string 	HTML form
7244
     */
7245
    public function display_item_form($item_type, $title = '', $action = 'add_item', $id = 0, $extra_info = 'new')
7246
    {
7247
        $course_id = api_get_course_int_id();
7248
        $_course = api_get_course_info();
7249
7250
        global $charset;
7251
7252
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7253
7254
        if ($id != 0 && is_array($extra_info)) {
7255
            $item_title 		= $extra_info['title'];
7256
            $item_description 	= $extra_info['description'];
7257
            $item_path = api_get_path(WEB_COURSE_PATH) . $_course['path'] . '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
7258
            $item_path_fck = '/scorm/' . $this->path . '/' . stripslashes($extra_info['path']);
7259
        } else {
7260
            $item_title = '';
7261
            $item_description = '';
7262
            $item_path_fck = '';
7263
        }
7264
7265 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7266
            $parent = $extra_info['parent_item_id'];
7267
        } else {
7268
            $parent = 0;
7269
        }
7270
7271
        $id  = intval($id);
7272
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7273
                WHERE
7274
                    c_id = ".$course_id." AND
7275
                    lp_id = " . $this->lp_id . " AND
7276
                    id != $id";
7277
7278
        if ($item_type == 'module')
7279
            $sql .= " AND parent_item_id = 0";
7280
7281
        $result = Database::query($sql);
7282
        $arrLP = array ();
7283
7284 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7285
            $arrLP[] = array(
7286
                'id' => $row['id'],
7287
                'item_type' => $row['item_type'],
7288
                'title' => $row['title'],
7289
                'path' => $row['path'],
7290
                'description' => $row['description'],
7291
                'parent_item_id' => $row['parent_item_id'],
7292
                'previous_item_id' => $row['previous_item_id'],
7293
                'next_item_id' => $row['next_item_id'],
7294
                'max_score' => $row['max_score'],
7295
                'min_score' => $row['min_score'],
7296
                'mastery_score' => $row['mastery_score'],
7297
                'prerequisite' => $row['prerequisite'],
7298
                'display_order' => $row['display_order']
7299
            );
7300
        }
7301
7302
        $this->tree_array($arrLP);
7303
7304
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7305
7306
        unset ($this->arrMenu);
7307
7308
        $gradebook = isset($_GET['gradebook']) ? Security :: remove_XSS($_GET['gradebook']) : null;
7309
7310
        $url = api_get_self() . '?' .api_get_cidreq().'&gradeboook='.$gradebook.'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
7311
7312
        $form = new FormValidator('form', 'POST',  $url);
7313
7314
        $defaults['title'] = api_html_entity_decode($item_title, ENT_QUOTES, $charset);
7315
        $defaults['description'] = $item_description;
7316
7317
        $form->addElement('header', $title);
7318
7319
        //$arrHide = array($id);
7320
        $arrHide[0]['value'] = Security :: remove_XSS($this->name);
7321
        $arrHide[0]['padding'] = 3;
7322
        $charset = api_get_system_encoding();
7323
7324
        if ($item_type != 'module' && $item_type != 'dokeos_module') {
7325 View Code Duplication
            for ($i = 0; $i < count($arrLP); $i++) {
7326
                if ($action != 'add') {
7327
                    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)) {
7328
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7329
                        $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
7330
                        if ($parent == $arrLP[$i]['id']) {
7331
                            $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7332
                        }
7333
                    }
7334
                } else {
7335
                    if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
7336
                        $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7337
                        $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
7338
                        if ($parent == $arrLP[$i]['id']) {
7339
                            $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7340
                        }
7341
                    }
7342
                }
7343
            }
7344
7345
            if ($action != 'move') {
7346
                $form->addElement('text', 'title', get_lang('Title'));
7347
                $form->applyFilter('title', 'html_filter');
7348
                $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
7349
            } else {
7350
                $form->addElement('hidden', 'title');
7351
            }
7352
7353
            $parent_select = $form->addElement('select', 'parent', get_lang('Parent'), '', array('id' => 'idParent', 'onchange' => "javascript: load_cbo(this.value);"));
7354
7355
            foreach ($arrHide as $key => $value) {
7356
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7357
            }
7358
            if (!empty($s_selected_parent)) {
7359
                $parent_select->setSelected($s_selected_parent);
7360
            }
7361
        }
7362
        if (is_array($arrLP)) {
7363
            reset($arrLP);
7364
        }
7365
7366
        $arrHide = array();
7367
7368
        // POSITION
7369 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7370
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7371
                //this is the same!
7372
                if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
7373
                    $s_selected_position = $arrLP[$i]['id'];
7374
                } elseif ($action == 'add') {
7375
                    $s_selected_position = $arrLP[$i]['id'];
7376
                }
7377
7378
                $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
7379
            }
7380
        }
7381
7382
        $position = $form->addElement('select', 'previous', get_lang('Position'), '', array('id' => 'previous'));
7383
        $padding = isset($value['padding']) ? $value['padding'] : 0;
7384
        $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:' . $padding . 'px;"');
7385
7386
        foreach ($arrHide as $key => $value) {
7387
            $position->addOption($value['value'] . '"', $key, 'style="padding-left:' . $padding . 'px;"');
7388
        }
7389
7390
        if (!empty ($s_selected_position)) {
7391
            $position->setSelected($s_selected_position);
7392
        }
7393
7394
        if (is_array($arrLP)) {
7395
            reset($arrLP);
7396
        }
7397
7398
        $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
7399
7400
        if ($item_type == 'module' || $item_type == 'dokeos_module') {
7401
            $form->addElement('hidden', 'parent', '0');
7402
        }
7403
        //fix in order to use the tab
7404
        if ($item_type == 'chapter') {
7405
            $form->addElement('hidden', 'type', 'chapter');
7406
        }
7407
7408
        $extension = null;
7409
        if (!empty($item_path)) {
7410
            $extension = pathinfo($item_path, PATHINFO_EXTENSION);
7411
        }
7412
7413
        //assets can't be modified
7414
7415
        //$item_type == 'asset' ||
7416
        if (( $item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
7417
7418
            if ($item_type == 'sco') {
7419
                $form->addElement('html', '<script type="text/javascript">alert("' . get_lang('WarningWhenEditingScorm') . '")</script>');
7420
            }
7421
            $renderer = $form->defaultRenderer();
7422
            $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
7423
7424
            $relative_prefix = '';
7425
7426
            $editor_config = array( 'ToolbarSet' 			=> 'LearningPathDocuments',
7427
                'Width' 				=> '100%',
7428
                'Height' 				=> '500',
7429
                'FullPage' 				=> true,
7430
                'CreateDocumentDir' 	=> $relative_prefix,
7431
                'CreateDocumentWebDir' 	=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/scorm/',
7432
                'BaseHref' 				=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().$item_path_fck
7433
            );
7434
7435
            $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
7436
            $content_path = (api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck);
7437
            //$defaults['content_lp'] = file_get_contents($item_path);
7438
            $defaults['content_lp'] = file_get_contents($content_path);
7439
        }
7440
7441
        $form->addElement('hidden', 'type', 'dokeos_' . $item_type);
7442
        $form->addElement('hidden', 'post_time', time());
7443
        $form->setDefaults($defaults);
7444
        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...
7445
    }
7446
7447
    /**
7448
     * Returns the form to update or create a document
7449
     * @param	string	Action (add/edit)
7450
     * @param	integer	ID of the lp_item (if already exists)
7451
     * @param	mixed	Integer if document ID, string if info ('new')
7452
     * @return	string	HTML form
7453
     */
7454
    public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
7455
    {
7456
        $course_id = api_get_course_int_id();
7457
        $_course = api_get_course_info();
7458
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7459
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
7460
7461
        $no_display_edit_textarea = false;
7462
        $item_description = '';
7463
        //If action==edit document
7464
        //We don't display the document form if it's not an editable document (html or txt file)
7465
        if ($action == "edit") {
7466
            if (is_array($extra_info)) {
7467
                $path_parts = pathinfo($extra_info['dir']);
7468
                if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
7469
                    $no_display_edit_textarea = true;
7470
                }
7471
            }
7472
        }
7473
        $no_display_add = false;
7474
7475
        // If action==add an existing document
7476
        // We don't display the document form if it's not an editable document (html or txt file).
7477
        if ($action == "add") {
7478
            if (is_numeric($extra_info)) {
7479
                $sql_doc = "SELECT path FROM " . $tbl_doc . "
7480
                            WHERE c_id = ".$course_id." AND id = " . intval($extra_info);
7481
                $result = Database::query($sql_doc);
7482
                $path_file = Database :: result($result, 0, 0);
7483
                $path_parts = pathinfo($path_file);
7484
                if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
7485
                    $no_display_add = true;
7486
                }
7487
            }
7488
        }
7489
        if ($id != 0 && is_array($extra_info)) {
7490
            $item_title = stripslashes($extra_info['title']);
7491
            $item_description = stripslashes($extra_info['description']);
7492
            $item_terms = stripslashes($extra_info['terms']);
7493 View Code Duplication
            if (empty ($item_title)) {
7494
                $path_parts = pathinfo($extra_info['path']);
7495
                $item_title = stripslashes($path_parts['filename']);
7496
            }
7497
        } elseif (is_numeric($extra_info)) {
7498
            $sql_doc = "SELECT path, title FROM " . $tbl_doc . "
7499
                        WHERE
7500
                            c_id = ".$course_id." AND
7501
                            id = " . intval($extra_info);
7502
7503
            $result = Database::query($sql_doc);
7504
            $row 	= Database::fetch_array($result);
7505
            $item_title = $row['title'];
7506
            $item_title = str_replace('_', ' ', $item_title);
7507 View Code Duplication
            if (empty ($item_title)) {
7508
                $path_parts = pathinfo($row['path']);
7509
                $item_title = stripslashes($path_parts['filename']);
7510
            }
7511
        } else {
7512
            $item_title = '';
7513
            $item_description = '';
7514
        }
7515
        $return = '<legend>';
7516
7517 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7518
            $parent = $extra_info['parent_item_id'];
7519
        } else {
7520
            $parent = 0;
7521
        }
7522
7523
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7524
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7525
7526
        $result = Database::query($sql);
7527
        $arrLP = array ();
7528 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7529
            $arrLP[] = array(
7530
                'id' => $row['id'],
7531
                'item_type' => $row['item_type'],
7532
                'title' => $row['title'],
7533
                'path' => $row['path'],
7534
                'description' => $row['description'],
7535
                'parent_item_id' => $row['parent_item_id'],
7536
                'previous_item_id' => $row['previous_item_id'],
7537
                'next_item_id' => $row['next_item_id'],
7538
                'display_order' => $row['display_order'],
7539
                'max_score' => $row['max_score'],
7540
                'min_score' => $row['min_score'],
7541
                'mastery_score' => $row['mastery_score'],
7542
                'prerequisite' => $row['prerequisite']
7543
            );
7544
        }
7545
7546
        $this->tree_array($arrLP);
7547
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7548
        unset ($this->arrMenu);
7549
7550
        if ($action == 'add') {
7551
            $return .= get_lang('CreateTheDocument');
7552
        } elseif ($action == 'move') {
7553
            $return .= get_lang('MoveTheCurrentDocument');
7554
        } else {
7555
            $return .= get_lang('EditTheCurrentDocument');
7556
        }
7557
7558
        $return .= '</legend>';
7559
7560 View Code Duplication
        if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
7561
            $return .= Display :: return_warning_message('<strong>' . get_lang('Warning') . ' !</strong><br />' . get_lang('WarningEditingDocument'), false);
7562
        }
7563
        $form = new FormValidator('form', 'POST', api_get_self() . '?' .$_SERVER['QUERY_STRING'], '', array('enctype'=> "multipart/form-data"));
7564
        $defaults['title'] = Security :: remove_XSS($item_title);
7565
        if (empty($item_title)) {
7566
            $defaults['title'] = Security::remove_XSS($item_title);
7567
        }
7568
        $defaults['description'] = $item_description;
7569
        $form->addElement('html', $return);
7570
        if ($action != 'move') {
7571
            $form->addElement('text', 'title', get_lang('Title'), array('id' => 'idTitle', 'class' => 'col-md-4'));
7572
            $form->applyFilter('title', 'html_filter');
7573
        }
7574
7575
        $arrHide[0]['value'] = $this->name;
7576
        $arrHide[0]['padding'] = 3;
7577
7578 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7579
            if ($action != 'add') {
7580
                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)) {
7581
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7582
                    $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
7583
                    if ($parent == $arrLP[$i]['id']) {
7584
                        $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7585
                    }
7586
                }
7587
            } else {
7588
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir') {
7589
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7590
                    $arrHide[$arrLP[$i]['id']]['padding'] = 3 + $arrLP[$i]['depth'] * 10;
7591
                    if ($parent == $arrLP[$i]['id']) {
7592
                        $s_selected_parent = $arrHide[$arrLP[$i]['id']];
7593
                    }
7594
                }
7595
            }
7596
        }
7597
7598
        $parent_select = $form->addElement('select', 'parent', get_lang('Parent'), '', 'class="form-control" id="idParent" " onchange="javascript: load_cbo(this.value);"');
7599
        $my_count=0;
7600
        foreach ($arrHide as $key => $value) {
7601
            if ($my_count!=0) {
7602
                // The LP name is also the first section and is not in the same charset like the other sections.
7603
                $value['value'] = Security :: remove_XSS($value['value']);
7604
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7605
            } else {
7606
                $value['value'] = Security :: remove_XSS($value['value']);
7607
                $parent_select->addOption($value['value'], $key, 'style="padding-left:' . $value['padding'] . 'px;"');
7608
            }
7609
            $my_count++;
7610
        }
7611
7612
        if (!empty($id)) {
7613
            $parent_select->setSelected($parent);
7614
        } else {
7615
            $parent_item_id = isset($_SESSION['parent_item_id']) ? $_SESSION['parent_item_id'] : 0 ;
7616
            $parent_select->setSelected($parent_item_id);
7617
        }
7618
7619
        if (is_array($arrLP)) {
7620
            reset($arrLP);
7621
        }
7622
7623
        $arrHide = array();
7624
        $s_selected_position = null;
7625
7626
        //POSITION
7627 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7628
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7629
                if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'])
7630
                    $s_selected_position = $arrLP[$i]['id'];
7631
                elseif ($action == 'add') $s_selected_position = $arrLP[$i]['id'];
7632
                $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After') . ' "' . $arrLP[$i]['title'] . '"';
7633
            }
7634
        }
7635
7636
        $position = $form->addElement('select', 'previous', get_lang('Position'), '', 'id="previous" class="form-control"');
7637
        $position->addOption(get_lang('FirstPosition'), 0);
7638
7639
        foreach ($arrHide as $key => $value) {
7640
            $padding = isset($value['padding']) ? $value['padding']: 0;
7641
            $position->addOption($value['value'], $key, 'style="padding-left:' . $padding . 'px;"');
7642
        }
7643
        $position->setSelected($s_selected_position);
7644
7645
        if (is_array($arrLP)) {
7646
            reset($arrLP);
7647
        }
7648
7649
        if ($action != 'move') {
7650
            $id_prerequisite = 0;
7651
            if (is_array($arrLP)) {
7652
                foreach ($arrLP as $key => $value) {
7653
                    if ($value['id'] == $id) {
7654
                        $id_prerequisite = $value['prerequisite'];
7655
                        break;
7656
                    }
7657
                }
7658
            }
7659
7660
            $arrHide = array();
7661
7662
            for ($i = 0; $i < count($arrLP); $i++) {
7663
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7664
                    if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'])
7665
                        $s_selected_position = $arrLP[$i]['id'];
7666
                    elseif ($action == 'add') $s_selected_position = $arrLP[$i]['id'];
7667
7668
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7669
7670
                }
7671
            }
7672
7673
            if (!$no_display_add) {
7674
                $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
7675
                $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
7676
                if (($extra_info == 'new' || $item_type == TOOL_DOCUMENT || $edit == 'true')) {
7677
                    if (isset ($_POST['content']))
7678
                        $content = stripslashes($_POST['content']);
7679
                    elseif (is_array($extra_info)) {
7680
                        //If it's an html document or a text file
7681
                        if (!$no_display_edit_textarea) {
7682
                            $content = $this->display_document($extra_info['path'], false, false);
7683
                        }
7684
                    } elseif (is_numeric($extra_info))
7685
                        $content = $this->display_document($extra_info, false, false);
7686
                    else
7687
                        $content = '';
7688
7689
                    if (!$no_display_edit_textarea) {
7690
                        // We need to calculate here some specific settings for the online editor.
7691
                        // The calculated settings work for documents in the Documents tool
7692
                        // (on the root or in subfolders).
7693
                        // For documents in native scorm packages it is unclear whether the
7694
                        // online editor should be activated or not.
7695
7696
                        // A new document, it is in the root of the repository.
7697
                        $relative_path 	 = '';
7698
                        $relative_prefix = '';
7699
7700
                        if (is_array($extra_info) && $extra_info != 'new') {
7701
                            // The document already exists. Whe have to determine its relative path towards the repository root.
7702
                            $relative_path = explode('/', $extra_info['dir']);
7703
                            $cnt = count($relative_path) - 2;
7704
                            if ($cnt < 0) {
7705
                                $cnt = 0;
7706
                            }
7707
                            $relative_prefix = str_repeat('../', $cnt);
7708
                            $relative_path 	 = array_slice($relative_path, 1, $cnt);
7709
                            $relative_path 	 = implode('/', $relative_path);
7710
                            if (strlen($relative_path) > 0) {
7711
                                $relative_path = $relative_path . '/';
7712
                            }
7713
                        } else {
7714
                            $result = $this->generate_lp_folder($_course);
7715
                            $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
7716
                            $relative_prefix = '../../';
7717
                        }
7718
7719
                        $editor_config = array(
7720
                            'ToolbarSet'=> 'LearningPathDocuments',
7721
                            'Width' 				=> '100%',
7722
                            'Height' 				=> '500',
7723
                            'FullPage' 				=> true,
7724
                            'CreateDocumentDir' 	=> $relative_prefix,
7725
                            'CreateDocumentWebDir' 	=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/document/',
7726
                            'BaseHref' 				=> api_get_path(WEB_COURSE_PATH) . api_get_course_path().'/document/'.$relative_path
7727
                        );
7728
7729
                        if ($_GET['action'] == 'add_item') {
7730
                            $class = 'add';
7731
                            $text = get_lang('LPCreateDocument');
7732
                        } else {
7733
                            if ($_GET['action'] == 'edit_item') {
7734
                                $class = 'save';
7735
                                $text = get_lang('SaveDocument');
7736
                            }
7737
                        }
7738
7739
                        $form->addButtonSave($text, 'submit_button');
7740
                        $renderer = $form->defaultRenderer();
7741
                        $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
7742
                        $form->addElement('html', '<div class="editor-lp">');
7743
                        $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
7744
                        $form->addElement('html', '</div>');
7745
                        $defaults['content_lp'] = $content;
7746
                    }
7747
                } elseif (is_numeric($extra_info)) {
7748
                    $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7749
7750
                    $return = $this->display_document($extra_info, true, true, true);
7751
                    $form->addElement('html', $return);
7752
                }
7753
            }
7754
        }
7755
7756
        if ($action == 'move') {
7757
            $form->addElement('hidden', 'title', $item_title);
7758
            $form->addElement('hidden', 'description', $item_description);
7759
        }
7760
        if (is_numeric($extra_info)) {
7761
            $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7762
            $form->addElement('hidden', 'path', $extra_info);
7763
        } elseif (is_array($extra_info)) {
7764
            $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
7765
            $form->addElement('hidden', 'path', $extra_info['path']);
7766
        }
7767
        $form->addElement('hidden', 'type', TOOL_DOCUMENT);
7768
        $form->addElement('hidden', 'post_time', time());
7769
        $form->setDefaults($defaults);
7770
7771
        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...
7772
    }
7773
7774
    /**
7775
     * Return HTML form to add/edit a link item
7776
     * @param string	$action (add/edit)
7777
     * @param integer	$id Item ID if exists
7778
     * @param mixed		$extra_info
7779
     * @return	string	HTML form
7780
     */
7781
    public function display_link_form($action = 'add', $id = 0, $extra_info = '')
7782
    {
7783
        $course_id = api_get_course_int_id();
7784
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7785
        $tbl_link = Database :: get_course_table(TABLE_LINK);
7786
7787
        if ($id != 0 && is_array($extra_info)) {
7788
            $item_title = stripslashes($extra_info['title']);
7789
            $item_description = stripslashes($extra_info['description']);
7790
            $item_url = stripslashes($extra_info['url']);
7791
        } elseif (is_numeric($extra_info)) {
7792
            $extra_info = intval($extra_info);
7793
            $sql = "SELECT title, description, url FROM " . $tbl_link . "
7794
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
7795
            $result = Database::query($sql);
7796
            $row = Database :: fetch_array($result);
7797
            $item_title       = $row['title'];
7798
            $item_description = $row['description'];
7799
            $item_url = $row['url'];
7800
        } else {
7801
            $item_title = '';
7802
            $item_description = '';
7803
            $item_url = '';
7804
        }
7805
7806
        $legend = '<legend>';
7807
7808 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
7809
            $parent = $extra_info['parent_item_id'];
7810
        } else {
7811
            $parent = 0;
7812
        }
7813
7814
        $sql = "SELECT * FROM " . $tbl_lp_item . "
7815
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
7816
        $result = Database::query($sql);
7817
        $arrLP = array();
7818
7819 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
7820
            $arrLP[] = array(
7821
                'id' => $row['id'],
7822
                'item_type' => $row['item_type'],
7823
                'title' => $row['title'],
7824
                'path' => $row['path'],
7825
                'description' => $row['description'],
7826
                'parent_item_id' => $row['parent_item_id'],
7827
                'previous_item_id' => $row['previous_item_id'],
7828
                'next_item_id' => $row['next_item_id'],
7829
                'display_order' => $row['display_order'],
7830
                'max_score' => $row['max_score'],
7831
                'min_score' => $row['min_score'],
7832
                'mastery_score' => $row['mastery_score'],
7833
                'prerequisite' => $row['prerequisite']
7834
            );
7835
        }
7836
7837
        $this->tree_array($arrLP);
7838
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
7839
        unset ($this->arrMenu);
7840
7841
        if ($action == 'add')
7842
            $legend .= get_lang('CreateTheLink') . '&nbsp;:';
7843
        elseif ($action == 'move') $legend .= get_lang('MoveCurrentLink') . '&nbsp;:';
7844
        else
7845
            $legend .= get_lang('EditCurrentLink') . '&nbsp;:';
7846
7847
        $legend .= '</legend>';
7848
7849
        $return = '<div class="sectioncomment">';
7850
        $return .= '<form method="POST">';
7851
        $return .= $legend;
7852
        $return .= '<table>';
7853
7854 View Code Duplication
        if ($action != 'move') {
7855
            $return .= '<tr>';
7856
            $return .= '<td class="label"><label for="idTitle">' . get_lang('Title') . '</label></td>';
7857
            $return .= '<td class="input"><input id="idTitle" name="title" size="44" type="text" value="' . $item_title . '" class="learnpath_item_form"/></td>';
7858
            $return .= '</tr>';
7859
        }
7860
7861
        $return .= '<tr>';
7862
        $return .= '<td class="label"><label for="idParent">' . get_lang('Parent') . '</label></td>';
7863
        $return .= '<td class="input">';
7864
        $return .= '<select id="idParent" style="width:100%;" name="parent" onChange="javascript: load_cbo(this.value);" class="learnpath_item_form" size="1">';
7865
        $return .= '<option class="top" value="0">' . $this->name . '</option>';
7866
        $arrHide = array(
7867
            $id
7868
        );
7869
7870
        $parent_item_id = $_SESSION['parent_item_id'];
7871
7872 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7873
            if ($action != 'add') {
7874
                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)) {
7875
                    $return .= '<option ' . (($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
7876
                } else {
7877
                    $arrHide[] = $arrLP[$i]['id'];
7878
                }
7879
            } else {
7880
                if ($arrLP[$i]['item_type'] == 'dokeos_module' || $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir')
7881
                    $return .= '<option ' . (($parent_item_id == $arrLP[$i]['id']) ? 'selected="selected" ' : '') . 'style="padding-left:' . ($arrLP[$i]['depth'] * 10) . 'px;" value="' . $arrLP[$i]['id'] . '">' . $arrLP[$i]['title'] . '</option>';
7882
            }
7883
        }
7884
7885
        if (is_array($arrLP)) {
7886
            reset($arrLP);
7887
        }
7888
7889
        $return .= '</select>';
7890
        $return .= '</td>';
7891
        $return .= '</tr>';
7892
        $return .= '<tr>';
7893
        $return .= '<td class="label"><label for="previous">' . get_lang('Position') . '</label></td>';
7894
        $return .= '<td class="input">';
7895
7896
        $return .= '<select id="previous" name="previous" style="width:100%;" size="1" class="learnpath_item_form">';
7897
        $return .= '<option class="top" value="0">' . get_lang('FirstPosition') . '</option>';
7898 View Code Duplication
        for ($i = 0; $i < count($arrLP); $i++) {
7899
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
7900
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7901
                    $selected = 'selected="selected" ';
7902
                elseif ($action == 'add')
7903
                    $selected = 'selected="selected" ';
7904
                else
7905
                    $selected = '';
7906
7907
                $return .= '<option ' . $selected . 'value="' . $arrLP[$i]['id'] . '">' . get_lang('After') . ' "' . $arrLP[$i]['title'] . '"</option>';
7908
            }
7909
        }
7910
        $return .= '</select>';
7911
        $return .= '</td>';
7912
        $return .= '</tr>';
7913
7914
        if ($action != 'move') {
7915
            $return .= '<tr>';
7916
            $return .= '<td class="label"><label for="idURL">' . get_lang('Url') . '</label></td>';
7917
            $return .= '<td class="input"><input' . (is_numeric($extra_info) ? ' disabled="disabled"' : '') . ' id="idURL" name="url" style="width:99%;" type="text" value="' . $item_url . '" class="learnpath_item_form" /></td>';
7918
            $return .= '</tr>';
7919
            $id_prerequisite = 0;
7920
            if (is_array($arrLP)) {
7921
                foreach ($arrLP as $key => $value) {
7922
                    if ($value['id'] == $id) {
7923
                        $id_prerequisite = $value['prerequisite'];
7924
                        break;
7925
                    }
7926
                }
7927
            }
7928
7929
            $arrHide = array();
7930
            for ($i = 0; $i < count($arrLP); $i++) {
7931
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
7932
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
7933
                        $s_selected_position = $arrLP[$i]['id'];
7934
                    elseif ($action == 'add') $s_selected_position = 0;
7935
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
7936
7937
                }
7938
            }
7939
            $return .= '</tr>';
7940
        }
7941
7942
        $return .= '<tr>';
7943
        if ($action == 'add') {
7944
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit">' . get_lang('AddLinkToCourse') . '</button></td>';
7945
        } else {
7946
            $return .= '<td>&nbsp;</td><td><button class="save" name="submit_button" type="submit">' . get_lang('EditCurrentLink') . '</button></td>';
7947
        }
7948
        $return .= '</tr>';
7949
        $return .= '</table>';
7950
7951 View Code Duplication
        if ($action == 'move') {
7952
            $return .= '<input name="title" type="hidden" value="' . $item_title . '" />';
7953
            $return .= '<input name="description" type="hidden" value="' . $item_description . '" />';
7954
        }
7955
7956 View Code Duplication
        if (is_numeric($extra_info)) {
7957
            $return .= '<input name="path" type="hidden" value="' . $extra_info . '" />';
7958
        } elseif (is_array($extra_info)) {
7959
            $return .= '<input name="path" type="hidden" value="' . $extra_info['path'] . '" />';
7960
        }
7961
        $return .= '<input name="type" type="hidden" value="' . TOOL_LINK . '" />';
7962
        $return .= '<input name="post_time" type="hidden" value="' . time() . '" />';
7963
        $return .= '</form>';
7964
        $return .= '</div>';
7965
7966
        return $return;
7967
    }
7968
7969
    /**
7970
     * Return HTML form to add/edit a student publication (work)
7971
     * @param	string	Action (add/edit)
7972
     * @param	integer	Item ID if already exists
7973
     * @param	mixed	Extra info (work ID if integer)
7974
     * @return	string	HTML form
7975
     */
7976
    public function display_student_publication_form($action = 'add', $id = 0, $extra_info = '')
7977
    {
7978
        $course_id = api_get_course_int_id();
7979
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
7980
        $tbl_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
7981
7982
        if ($id != 0 && is_array($extra_info)) {
7983
            $item_title = stripslashes($extra_info['title']);
7984
            $item_description = stripslashes($extra_info['description']);
7985
        } elseif (is_numeric($extra_info)) {
7986
            $extra_info = intval($extra_info);
7987
            $sql = "SELECT title, description
7988
                    FROM " . $tbl_publication . "
7989
                    WHERE c_id = ".$course_id." AND id = " . $extra_info;
7990
7991
            $result = Database::query($sql);
7992
            $row = Database :: fetch_array($result);
7993
7994
            $item_title = $row['title'];
7995
        } else {
7996
            $item_title = get_lang('Student_publication');
7997
        }
7998
7999 View Code Duplication
        if ($id != 0 && is_array($extra_info)) {
8000
            $parent = $extra_info['parent_item_id'];
8001
        } else {
8002
            $parent = 0;
8003
        }
8004
8005
        $sql = "SELECT * FROM " . $tbl_lp_item . "
8006
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
8007
8008
        $result = Database::query($sql);
8009
        $arrLP = array();
8010 View Code Duplication
        while ($row = Database :: fetch_array($result)) {
8011
            $arrLP[] = array (
8012
                'id' => $row['id'],
8013
                'item_type' => $row['item_type'],
8014
                'title' => $row['title'],
8015
                'path' => $row['path'],
8016
                'description' => $row['description'],
8017
                'parent_item_id' => $row['parent_item_id'],
8018
                'previous_item_id' => $row['previous_item_id'],
8019
                'next_item_id' => $row['next_item_id'],
8020
                'display_order' => $row['display_order'],
8021
                'max_score' => $row['max_score'],
8022
                'min_score' => $row['min_score'],
8023
                'mastery_score' => $row['mastery_score'],
8024
                'prerequisite' => $row['prerequisite']
8025
            );
8026
        }
8027
8028
        $this->tree_array($arrLP);
8029
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
8030
        unset ($this->arrMenu);
8031
8032
        $form = new FormValidator('frm_student_publication', 'post', '#');
8033
8034
        if ($action == 'add') {
8035
            $form->addHeader(get_lang('Student_publication'));
8036
        } elseif ($action == 'move') {
8037
            $form->addHeader(get_lang('MoveCurrentStudentPublication'));
8038
        } else {
8039
            $form->addHeader(get_lang('EditCurrentStudentPublication'));
8040
        }
8041
8042
        if ($action != 'move') {
8043
            $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form', 'id' => 'idTitle']);
8044
        }
8045
8046
        $parentSelect = $form->addSelect(
8047
            'parent',
8048
            get_lang('Parent'),
8049
            ['0' => $this->name],
8050
            [
8051
                'onchange' => 'javascript: load_cbo(this.value);',
8052
                'class' => 'learnpath_item_form',
8053
                'id' => 'idParent'
8054
            ]
8055
        );
8056
8057
        $arrHide = array (
8058
            $id
8059
        );
8060
8061
        for ($i = 0; $i < count($arrLP); $i++) {
8062
            if ($action != 'add') {
8063
                if (
8064
                    (
8065
                        $arrLP[$i]['item_type'] == 'dokeos_module' ||
8066
                        $arrLP[$i]['item_type'] == 'dokeos_chapter' ||
8067
                        $arrLP[$i]['item_type'] == 'dir'
8068
                    ) &&
8069
                    !in_array($arrLP[$i]['id'], $arrHide) &&
8070
                    !in_array($arrLP[$i]['parent_item_id'], $arrHide)
8071
                ) {
8072
                    $parentSelect->addOption(
8073
                        $arrLP[$i]['title'],
8074
                        $arrLP[$i]['id'],
8075
                        ['style' => 'padding-left: ' . (($arrLP[$i]['depth'] * 10) + 20) . 'px;']
8076
                    );
8077
8078
                    if ($parent == $arrLP[$i]['id']) {
8079
                        $parentSelect->setSelected($arrLP[$i]['id']);
8080
                    }
8081
                } else {
8082
                    $arrHide[] = $arrLP[$i]['id'];
8083
                }
8084
            } else {
8085
                if (
8086
                    $arrLP[$i]['item_type'] == 'dokeos_module' ||
8087
                    $arrLP[$i]['item_type'] == 'dokeos_chapter' || $arrLP[$i]['item_type'] == 'dir'
8088
                ) {
8089
                    $parentSelect->addOption(
8090
                        $arrLP[$i]['title'],
8091
                        $arrLP[$i]['id'],
8092
                        ['style' => 'padding-left: ' . (($arrLP[$i]['depth'] * 10) + 20) . 'px;']
8093
                    );
8094
8095
                    if ($parent == $arrLP[$i]['id']) {
8096
                        $parentSelect->setSelected($arrLP[$i]['id']);
8097
                    }
8098
                }
8099
            }
8100
        }
8101
8102
        if (is_array($arrLP)) {
8103
            reset($arrLP);
8104
        }
8105
8106
        $previousSelect = $form->addSelect(
8107
            'previous',
8108
            get_lang('Position'),
8109
            ['0' => get_lang('FirstPosition')],
8110
            ['id' => 'previous', 'class' => 'learnpath_item_form']
8111
        );
8112
8113
        for ($i = 0; $i < count($arrLP); $i++) {
8114
            if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
8115
                $previousSelect->addOption(
8116
                    get_lang('After') . ' "' . $arrLP[$i]['title'] . '"',
8117
                    $arrLP[$i]['id']
8118
                );
8119
8120
                if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
8121
                    $previousSelect->setSelected($arrLP[$i]['id']);
8122
                } elseif ($action == 'add') {
8123
                    $previousSelect->setSelected($arrLP[$i]['id']);
8124
                }
8125
            }
8126
        }
8127
8128 View Code Duplication
        if ($action != 'move') {
8129
            $id_prerequisite = 0;
8130
            if (is_array($arrLP)) {
8131
                foreach ($arrLP as $key => $value) {
8132
                    if ($value['id'] == $id) {
8133
                        $id_prerequisite = $value['prerequisite'];
8134
                        break;
8135
                    }
8136
                }
8137
            }
8138
            $arrHide = array ();
8139
            for ($i = 0; $i < count($arrLP); $i++) {
8140
                if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dokeos_chapter') {
8141
                    if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
8142
                        $s_selected_position = $arrLP[$i]['id'];
8143
                    elseif ($action == 'add') $s_selected_position = 0;
8144
                    $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
8145
8146
                }
8147
            }
8148
        }
8149
8150
        if ($action == 'add') {
8151
            $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
8152
        } else {
8153
            $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
8154
        }
8155
8156
        if ($action == 'move') {
8157
            $form->addHidden('title', $item_title);
8158
            $form->addHidden('description', $item_description);
8159
        }
8160
8161
        if (is_numeric($extra_info)) {
8162
            $form->addHidden('path', $extra_info);
8163
        } elseif (is_array($extra_info)) {
8164
            $form->addHidden('path', $extra_info['path']);
8165
        }
8166
8167
        $form->addHidden('type', TOOL_STUDENTPUBLICATION);
8168
        $form->addHidden('post_time', time());
8169
        $form->setDefaults(['title' => $item_title]);
8170
8171
        $return = '<div class="sectioncomment">';
8172
        $return .= $form->returnForm();
8173
        $return .= '</div>';
8174
8175
        return $return;
8176
    }
8177
8178
    /**
8179
     * Displays the menu for manipulating a step
8180
     *
8181
     * @param $item_id
8182
     * @param string $item_type
8183
     * @return string
8184
     */
8185
    public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
8186
    {
8187
        $_course = api_get_course_info();
8188
        $course_id = api_get_course_int_id();
8189
        $course_code = api_get_course_id();
8190
8191
        $return = '<div class="actions">';
8192
8193
        switch ($item_type) {
8194
            case 'dokeos_chapter' :
8195
            case 'chapter' :
8196
                // Commented the message cause should not show it.
8197
                //$lang = get_lang('TitleManipulateChapter');
8198
                break;
8199
8200
            case 'dokeos_module' :
8201
            case 'module' :
8202
                // Commented the message cause should not show it.
8203
                //$lang = get_lang('TitleManipulateModule');
8204
                break;
8205
8206
            case TOOL_DOCUMENT :
8207
                // Commented the message cause should not show it.
8208
                //$lang = get_lang('TitleManipulateDocument');
8209
                break;
8210
8211
            case TOOL_LINK :
8212
            case 'link' :
8213
                // Commented the message cause should not show it.
8214
                //$lang = get_lang('TitleManipulateLink');
8215
                break;
8216
8217
            case TOOL_QUIZ :
8218
                // Commented the message cause should not show it.
8219
                //$lang = get_lang('TitleManipulateQuiz');
8220
                break;
8221
8222
            case TOOL_STUDENTPUBLICATION :
8223
                // Commented the message cause should not show it.
8224
                //$lang = get_lang('TitleManipulateStudentPublication');
8225
                break;
8226
        }
8227
8228
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8229
        $item_id = intval($item_id);
8230
        $sql = "SELECT * FROM " . $tbl_lp_item . " as lp
8231
                WHERE lp.c_id = ".$course_id." AND lp.id = " . $item_id;
8232
        $result = Database::query($sql);
8233
        $row = Database::fetch_assoc($result);
8234
8235
        $audio_player = null;
8236
        // We display an audio player if needed.
8237
        if (!empty($row['audio'])) {
8238
            $audio_player .= '<div class="lp_mediaplayer" id="container">
8239
                              <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
8240
                              </div>';
8241
            $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
8242
            $audio_player .= '<script>
8243
                                var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
8244
                                s1.addParam("allowscriptaccess","always");
8245
                                s1.addParam("flashvars","file=../../courses/' . $_course['path'] . '/document/audio/' . $row['audio'] . '&autostart=true");
8246
                                s1.write("container");
8247
                            </script>';
8248
        }
8249
8250
        $url = api_get_self().'?cidReq='.Security::remove_XSS($_GET['cidReq']).'&view=build&id='.$item_id .'&lp_id='.$this->lp_id;
8251
8252
        $return .= Display::url(
8253
            Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL),
8254
            $url.'&action=edit_item&path_item=' . $row['path']
8255
        );
8256
8257
        $return .= Display::url(
8258
            Display::return_icon('move.png', get_lang('Move'), array(), ICON_SIZE_SMALL),
8259
            $url.'&action=move_item'
8260
        );
8261
8262
        // Commented for now as prerequisites cannot be added to chapters.
8263
        if ($item_type != 'dokeos_chapter' && $item_type != 'chapter') {
8264
            $return .= Display::url(
8265
                Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_SMALL),
8266
                $url.'&action=edit_item_prereq'
8267
            );
8268
        }
8269
        $return .= Display::url(
8270
            Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL),
8271
            $url.'&action=delete_item'
8272
        );
8273
8274 View Code Duplication
        if ($item_type == TOOL_HOTPOTATOES ) {
8275
            $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
8276
            $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
8277
        }
8278
8279 View Code Duplication
        if ($item_type == TOOL_DOCUMENT ) {
8280
            $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
8281
            $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
8282
        }
8283
8284
        $return .= '</div>';
8285
8286
        if (!empty($audio_player)) {
8287
            $return .= '<br />'.$audio_player;
8288
        }
8289
8290
        return $return;
8291
    }
8292
8293
    /**
8294
     * Creates the javascript needed for filling up the checkboxes without page reload
8295
     * @return string
8296
     */
8297
    public function get_js_dropdown_array()
8298
    {
8299
        $course_id = api_get_course_int_id();
8300
        $return = 'var child_name = new Array();' . "\n";
8301
        $return .= 'var child_value = new Array();' . "\n\n";
8302
        $return .= 'child_name[0] = new Array();' . "\n";
8303
        $return .= 'child_value[0] = new Array();' . "\n\n";
8304
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8305
        $sql_zero = "SELECT * FROM " . $tbl_lp_item . "
8306
                    WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id . " AND parent_item_id = 0
8307
                    ORDER BY display_order ASC";
8308
        $res_zero = Database::query($sql_zero);
8309
        $i = 0;
8310
8311
        while ($row_zero = Database :: fetch_array($res_zero)) {
8312
            if ($row_zero['item_type'] == TOOL_QUIZ) {
8313
                $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
8314
            }
8315
            $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
8316
            $return .= 'child_name[0][' . $i . '] = '.$js_var.' ;' . "\n";
8317
            $return .= 'child_value[0][' . $i++ . '] = "' . $row_zero['id'] . '";' . "\n";
8318
        }
8319
        $return .= "\n";
8320
        $sql = "SELECT * FROM " . $tbl_lp_item . "
8321
                WHERE c_id = ".$course_id." AND lp_id = " . $this->lp_id;
8322
        $res = Database::query($sql);
8323
        while ($row = Database :: fetch_array($res)) {
8324
            $sql_parent = "SELECT * FROM " . $tbl_lp_item . "
8325
                           WHERE
8326
                                c_id = ".$course_id." AND
8327
                                parent_item_id = " . $row['id'] . "
8328
                           ORDER BY display_order ASC";
8329
            $res_parent = Database::query($sql_parent);
8330
            $i = 0;
8331
            $return .= 'child_name[' . $row['id'] . '] = new Array();' . "\n";
8332
            $return .= 'child_value[' . $row['id'] . '] = new Array();' . "\n\n";
8333
8334
            while ($row_parent = Database :: fetch_array($res_parent)) {
8335
                $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
8336
                $return .= 'child_name[' . $row['id'] . '][' . $i . '] =   '.$js_var.' ;' . "\n";
8337
                $return .= 'child_value[' . $row['id'] . '][' . $i++ . '] = "' . $row_parent['id'] . '";' . "\n";
8338
            }
8339
            $return .= "\n";
8340
        }
8341
8342
        return $return;
8343
    }
8344
8345
    /**
8346
     * Display the form to allow moving an item
8347
     * @param	integer		Item ID
8348
     * @return	string		HTML form
8349
     */
8350
    public function display_move_item($item_id)
8351
    {
8352
        $course_id = api_get_course_int_id();
8353
        $return = '';
8354
8355
        if (is_numeric($item_id)) {
8356
            $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8357
8358
            $sql = "SELECT * FROM " . $tbl_lp_item . "
8359
                    WHERE c_id = ".$course_id." AND id = " . $item_id;
8360
8361
            $res = Database::query($sql);
8362
            $row = Database :: fetch_array($res);
8363
8364
            switch ($row['item_type']) {
8365
                case 'dokeos_chapter' :
8366
                case 'dir' :
8367
                case 'asset' :
8368
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8369
                    $return .= $this->display_item_form($row['item_type'], get_lang('MoveCurrentChapter'), 'move', $item_id, $row);
8370
                    break;
8371
                case 'dokeos_module' :
8372
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8373
                    $return .= $this->display_item_form($row['item_type'], 'Move th current module:', 'move', $item_id, $row);
8374
                    break;
8375
                case TOOL_DOCUMENT :
8376
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8377
                    $return .= $this->display_document_form('move', $item_id, $row);
8378
                    break;
8379 View Code Duplication
                case TOOL_LINK :
8380
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8381
                    $return .= $this->display_link_form('move', $item_id, $row);
8382
                    break;
8383 View Code Duplication
                case TOOL_HOTPOTATOES :
8384
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8385
                    $return .= $this->display_link_form('move', $item_id, $row);
8386
                    break;
8387 View Code Duplication
                case TOOL_QUIZ :
8388
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8389
                    $return .= $this->display_quiz_form('move', $item_id, $row);
8390
                    break;
8391 View Code Duplication
                case TOOL_STUDENTPUBLICATION :
8392
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8393
                    $return .= $this->display_student_publication_form('move', $item_id, $row);
8394
                    break;
8395
                case TOOL_FORUM :
8396
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8397
                    $return .= $this->display_forum_form('move', $item_id, $row);
8398
                    break;
8399 View Code Duplication
                case TOOL_THREAD :
8400
                    $return .= $this->display_manipulate($item_id, $row['item_type']);
8401
                    $return .= $this->display_forum_form('move', $item_id, $row);
8402
                    break;
8403
            }
8404
        }
8405
8406
        return $return;
8407
    }
8408
8409
    /**
8410
     * Displays a basic form on the overview page for changing the item title and the item description.
8411
     * @param string $item_type
8412
     * @param string $title
8413
     * @param array $data
8414
     * @return string
8415
     */
8416
    public function display_item_small_form($item_type, $title = '', $data = array())
8417
    {
8418
        $url = api_get_self() . '?' .api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
8419
        $form = new FormValidator('small_form', 'post', $url);
8420
        $form->addElement('header', $title);
8421
        $form->addElement('text', 'title', get_lang('Title'));
8422
        $form->addButtonSave(get_lang('Save'), 'submit_button');
8423
        $form->addElement('hidden', 'id', $data['id']);
8424
        $form->addElement('hidden', 'parent', $data['parent_item_id']);
8425
        $form->addElement('hidden', 'previous', $data['previous_item_id']);
8426
        $form->setDefaults(array('title' => $data['title']));
8427
8428
        return $form->toHtml();
8429
    }
8430
8431
    /**
8432
     * Return HTML form to allow prerequisites selection
8433
     * @todo use FormValidator
8434
     * @param	integer Item ID
8435
     * @return	string	HTML form
8436
     */
8437
    public function display_item_prerequisites_form($item_id)
8438
    {
8439
        $course_id = api_get_course_int_id();
8440
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
8441
        $item_id = intval($item_id);
8442
        /* Current prerequisite */
8443
        $sql = "SELECT * FROM $tbl_lp_item
8444
                WHERE c_id = $course_id AND id = " . $item_id;
8445
        $result = Database::query($sql);
8446
        $row    = Database::fetch_array($result);
8447
        $prerequisiteId = $row['prerequisite'];
8448
        $return = '<legend>';
8449
        $return .= get_lang('AddEditPrerequisites');
8450
        $return .= '</legend>';
8451
        $return .= '<form method="POST">';
8452
        $return .= '<table class="data_table">';
8453
        $return .= '<tr>';
8454
        $return .= '<th height="24">' . get_lang('LearnpathPrerequisites') . '</th>';
8455
        $return .= '<th width="70" >' . get_lang('Minimum') . '</th>';
8456
        $return .= '<th width="70">' . get_lang('Maximum') . '</th>';
8457
        $return .= '</tr>';
8458
8459
        // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
8460
        $return .= '<tr >';
8461
        $return .= '<td colspan="3" class="radio">';
8462
        $return .= '<input checked="checked" id="idNone" name="prerequisites"  style="margin-left:0px; margin-right:10px;" type="radio" />';
8463
        $return .= '<label for="idNone">' . get_lang('None') . '</label>';
8464
        $return .= '</tr>';
8465
8466
        $sql = "SELECT * FROM $tbl_lp_item
8467
                WHERE c_id = $course_id AND lp_id = " . $this->lp_id;
8468
        $result = Database::query($sql);
8469
        $arrLP = array();
8470
8471
        $selectedMinScore = array();
8472
        $selectedMaxScore = array();
8473
        while ($row = Database :: fetch_array($result)) {
8474
            if ($row['id'] == $item_id) {
8475
                $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
8476
                $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
8477
            }
8478
            $arrLP[] = array(
8479
                'id' => $row['id'],
8480
                'item_type' => $row['item_type'],
8481
                'title' => $row['title'],
8482
                'ref' => $row['ref'],
8483
                'description' => $row['description'],
8484
                'parent_item_id' => $row['parent_item_id'],
8485
                'previous_item_id' => $row['previous_item_id'],
8486
                'next_item_id' => $row['next_item_id'],
8487
                'max_score' => $row['max_score'],
8488
                'min_score' => $row['min_score'],
8489
                'mastery_score' => $row['mastery_score'],
8490
                'prerequisite' => $row['prerequisite'],
8491
                'next_item_id' => $row['next_item_id'],
8492
                'display_order' => $row['display_order'],
8493
                'prerequisite_min_score' => $row['prerequisite_min_score'],
8494
                'prerequisite_max_score' => $row['prerequisite_max_score'],
8495
            );
8496
        }
8497
8498
        $this->tree_array($arrLP);
8499
        $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
8500
        unset($this->arrMenu);
8501
8502
        for ($i = 0; $i < count($arrLP); $i++) {
8503
            $item = $arrLP[$i];
8504
8505
            if ($item['id'] == $item_id) {
8506
                break;
8507
            }
8508
8509
            $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
8510
            $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']]: 0;
8511
8512
            $return .= '<tr>';
8513
            $return .= '<td class="radio"' . (($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '') . '>';
8514
            $return .= '<label for="id' . $item['id'] . '">';
8515
            $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'] . '" />';
8516
            $icon_name = str_replace(' ', '', $item['item_type']);
8517
8518
            if (file_exists('../img/lp_' . $icon_name . '.png')) {
8519
                $return .= Display::return_icon('lp_' . $icon_name . '.png');
8520
            } else {
8521
                if (file_exists('../img/lp_' . $icon_name . '.gif')) {
8522
                    $return .= Display::return_icon('lp_' . $icon_name . '.gif');
8523
                } else {
8524
                    $return .= Display::return_icon('folder_document.gif', '', array('style'=>'margin-right:5px;'));
8525
                }
8526
            }
8527
8528
            $return .=  $item['title'] . '</label>';
8529
            $return .= '</td>';
8530
8531
            if ($item['item_type'] == TOOL_QUIZ) {
8532
                // lets update max_score Quiz information depending of the Quiz Advanced properties
8533
                $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
8534
                $tmp_obj_exercice = new Exercise();
8535
                $tmp_obj_exercice->read($tmp_obj_lp_item->path);
8536
                $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
8537
8538
                $tmp_obj_lp_item->update_in_bdd();
8539
                $item['max_score'] = $tmp_obj_lp_item->max_score;
8540
8541
                $return .= '<td class="exercise">';
8542
                $return .= '<input size="4" maxlength="3" name="min_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMinScoreValue. '" />';
8543
                $return .= '</td>';
8544
                $return .= '<td class="exercise">';
8545
                $return .= '<input size="4" maxlength="3" name="max_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMaxScoreValue . '" />';
8546
                $return .= '</td>';
8547
            }
8548
8549
            if ($item['item_type'] == TOOL_HOTPOTATOES) {
8550
                $return .= '<td class="exercise">';
8551
                $return .= '<center><input size="4" maxlength="3" name="min_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'" value="' . $selectedMinScoreValue . '" /></center>';
8552
                $return .= '</td>';
8553
                $return .= '<td class="exercise"">';
8554
                $return .= '<center><input size="4" maxlength="3" name="max_' . $item['id'] . '" type="number" min="0" step="any" max="'.$item['max_score'].'"  value="'.$selectedMaxScoreValue . '" /></center>';
8555
                $return .= '</td>';
8556
            }
8557
            $return .= '</tr>';
8558
        }
8559
        $return .= '<tr>';
8560
        $return .= '</tr>';
8561
        $return .= '</table>';
8562
        $return .= '<div style="padding-top:3px;">';
8563
        $return .= '<button class="btn btn-primary" name="submit_button" type="submit">' . get_lang('ModifyPrerequisites') . '</button>';
8564
        $return .= '</form>';
8565
8566
        return $return;
8567
    }
8568
8569
    /**
8570
     * Return HTML list to allow prerequisites selection for lp
8571
     * @param	integer Item ID
8572
     * @return	string	HTML form
8573
     */
8574
    public function display_lp_prerequisites_list()
8575
    {
8576
        $course_id = api_get_course_int_id();
8577
        $lp_id = $this->lp_id;
8578
        $tbl_lp = Database :: get_course_table(TABLE_LP_MAIN);
8579
8580
        // get current prerequisite
8581
        $sql = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $lp_id ";
8582
        $result = Database::query($sql);
8583
        $row = Database :: fetch_array($result);
8584
        $prerequisiteId = $row['prerequisite'];
8585
        $session_id = api_get_session_id();
8586
        $session_condition = api_get_session_condition($session_id);
8587
        $sql = "SELECT * FROM $tbl_lp
8588
                WHERE c_id = $course_id $session_condition
8589
                ORDER BY display_order ";
8590
        $rs = Database::query($sql);
8591
        $return = '';
8592
        $return .= '<select name="prerequisites" class="form-control">';
8593
        $return .= '<option value="0">'.get_lang('None').'</option>';
8594
        if (Database::num_rows($rs) > 0) {
8595
            while ($row = Database::fetch_array($rs)) {
8596
                if ($row['id'] == $lp_id) {
8597
                    continue;
8598
                }
8599
                $return .= '<option value="'.$row['id'].'" '.(($row['id']==$prerequisiteId)?' selected ' : '').'>'.$row['name'].'</option>';
8600
            }
8601
        }
8602
        $return .= '</select>';
8603
8604
        return $return;
8605
    }
8606
8607
    /**
8608
     * Creates a list with all the documents in it
8609
     * @param bool $showInvisibleFiles
8610
     * @return string
8611
     */
8612
    public function get_documents($showInvisibleFiles = false)
8613
    {
8614
        $course_info = api_get_course_info();
8615
        $sessionId = api_get_session_id();
8616
8617
        $document_tree = DocumentManager::get_document_preview(
8618
            $course_info,
8619
            $this->lp_id,
8620
            null,
8621
            $sessionId,
8622
            true,
8623
            null,
8624
            null,
8625
            $showInvisibleFiles,
8626
            true
8627
        );
8628
8629
        return $document_tree;
8630
    }
8631
8632
    /**
8633
     * Creates a list with all the exercises (quiz) in it
8634
     * @return string
8635
     */
8636
    public function get_exercises()
8637
    {
8638
        $course_id = api_get_course_int_id();
8639
8640
        // New for hotpotatoes.
8641
        $uploadPath = DIR_HOTPOTATOES; //defined in main_api
8642
        $tbl_doc = Database :: get_course_table(TABLE_DOCUMENT);
8643
        $tbl_quiz = Database :: get_course_table(TABLE_QUIZ_TEST);
8644
8645
        $session_id = api_get_session_id();
8646
        $condition_session = api_get_session_condition($session_id);
8647
8648
        $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
8649
8650
        $activeCondition = " active <> -1 ";
8651
        if ($setting) {
8652
            $activeCondition = " active = 1 ";
8653
        }
8654
8655
        $sql_quiz = "SELECT * FROM $tbl_quiz
8656
                     WHERE c_id = $course_id AND $activeCondition $condition_session
8657
                     ORDER BY title ASC";
8658
8659
        $sql_hot  = "SELECT * FROM $tbl_doc
8660
                     WHERE c_id = $course_id AND path LIKE '" . $uploadPath . "/%/%htm%'  $condition_session
8661
                     ORDER BY id ASC";
8662
8663
        $res_quiz = Database::query($sql_quiz);
8664
        $res_hot  = Database::query($sql_hot);
8665
8666
        $return = '<ul class="lp_resource">';
8667
        $return .= '<li class="lp_resource_element">';
8668
        $return .= Display::return_icon('new_test_small.gif');
8669
        $return .= '<a href="' . api_get_path(WEB_CODE_PATH) . 'exercice/exercise_admin.php?'.api_get_cidreq().'&lp_id=' . $this->lp_id . '">' .
8670
            get_lang('NewExercise') . '</a>';
8671
        $return .= '</li>';
8672
8673
        // Display hotpotatoes
8674
        while ($row_hot = Database :: fetch_array($res_hot)) {
8675
            $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
8676
8677
            $return .= '<a class="moved" href="#">';
8678
            $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8679
            $return .= '</a> ';
8680
8681
            $return .= Display::return_icon('hotpotatoes_s.png');
8682
            $return .= '<a href="' . api_get_self() . '?' . api_get_cidreq().'&action=add_item&type=' . TOOL_HOTPOTATOES . '&file=' . $row_hot['id'] . '&lp_id=' . $this->lp_id . '">'.
8683
                ((!empty ($row_hot['comment'])) ? $row_hot['comment'] : Security :: remove_XSS($row_hot['title'])) . '</a>';
8684
            $return .= '</li>';
8685
        }
8686
8687
        while ($row_quiz = Database :: fetch_array($res_quiz)) {
8688
            $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$row_quiz['title'].'" >';
8689
            $return .= '<a class="moved" href="#">';
8690
            $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8691
            $return .= '</a> ';
8692
            $return .= Display::return_icon('quizz_small.gif', '', array(), ICON_SIZE_TINY);
8693
            $return .= '<a href="' . api_get_self() . '?'.api_get_cidreq().'&action=add_item&type=' . TOOL_QUIZ . '&file=' . $row_quiz['id'] . '&lp_id=' . $this->lp_id . '">' .
8694
                Security :: remove_XSS(cut($row_quiz['title'], 80)).
8695
                '</a>';
8696
            $return .= '</li>';
8697
        }
8698
8699
        $return .= '</ul>';
8700
8701
        return $return;
8702
    }
8703
8704
    /**
8705
     * Creates a list with all the links in it
8706
     * @return string
8707
     */
8708
    public function get_links()
8709
    {
8710
        $selfUrl = api_get_self();
8711
        $courseIdReq = api_get_cidreq();
8712
        $course = api_get_course_info();
8713
        $course_id = $course['real_id'];
8714
        $tbl_link = Database::get_course_table(TABLE_LINK);
8715
        $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
8716
        $moveEverywhereIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8717
8718
        $session_id = api_get_session_id();
8719
        $condition_session = api_get_session_condition($session_id, true, null, "link.session_id");
8720
8721
        $sql = "SELECT link.id as link_id,
8722
                    link.title as link_title,
8723
                    link.category_id as category_id,
8724
                    link_category.category_title as category_title
8725
                FROM $tbl_link as link
8726
                LEFT JOIN $linkCategoryTable as link_category
8727
                ON link.category_id = link_category.id
8728
                WHERE link.c_id = ".$course_id." $condition_session
8729
                ORDER BY link_category.category_title ASC, link.title ASC";
8730
        $links = Database::query($sql);
8731
8732
        $categorizedLinks = array();
8733
        $categories = array();
8734
8735
        while ($link = Database :: fetch_array($links)) {
8736
            if (!$link['category_id']) {
8737
                $link['category_title'] = get_lang('Uncategorized');
8738
            }
8739
            $categories[$link['category_id']] = $link['category_title'];
8740
            $categorizedLinks[$link['category_id']][$link['link_id']] = $link['link_title'];
8741
        }
8742
8743
        $linksHtmlCode =
8744
            '<script>
8745
            function toggle_tool(tool, id){
8746
                if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
8747
                    document.getElementById(tool+"_"+id+"_content").style.display = "block";
8748
                    document.getElementById(tool+"_"+id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
8749
                } else {
8750
                    document.getElementById(tool+"_"+id+"_content").style.display = "none";
8751
                    document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
8752
                }
8753
            }
8754
        </script>
8755
8756
        <ul class="lp_resource">
8757
            <li class="lp_resource_element">
8758
                '.Display::return_icon('linksnew.gif').'
8759
                <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
8760
                get_lang('LinkAdd').'
8761
                </a>
8762
            </li>';
8763
8764
        foreach ($categorizedLinks as $categoryId => $links) {
8765
            $linkNodes = null;
8766
            foreach ($links as $key => $title) {
8767
                if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2)  {
8768
                    $linkNodes .=
8769
                        '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
8770
                        <a class="moved" href="#">'.
8771
                        $moveEverywhereIcon.
8772
                        '</a>
8773
                        '.Display::return_icon('lp_link.png').'
8774
                        <a href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
8775
                        TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
8776
                        Security::remove_XSS($title).
8777
                        '</a>
8778
                    </li>';
8779
                }
8780
            }
8781
            $linksHtmlCode .=
8782
                '<li>
8783
                <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
8784
                    <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
8785
                    align="absbottom" />
8786
                </a>
8787
                <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
8788
            </li>
8789
            <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
8790
        }
8791
        $linksHtmlCode .= '</ul>';
8792
8793
        return $linksHtmlCode;
8794
    }
8795
8796
    /**
8797
     * Creates a list with all the student publications in it
8798
     * @return unknown
8799
     */
8800
    public function get_student_publications()
8801
    {
8802
        $return = '<div class="lp_resource" >';
8803
        $return .= '<div class="lp_resource_element">';
8804
        $return .= Display::return_icon('works_small.gif', '', array(), ICON_SIZE_TINY);
8805
        $return .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&action=add_item&type=' . TOOL_STUDENTPUBLICATION . '&lp_id=' . $this->lp_id . '">' . get_lang('AddAssignmentPage') . '</a>';
8806
        $return .= '</div>';
8807
        $return .= '</div>';
8808
        return $return;
8809
    }
8810
8811
    /**
8812
     * Creates a list with all the forums in it
8813
     * @return string
8814
     */
8815
    public function get_forums()
8816
    {
8817
        require_once '../forum/forumfunction.inc.php';
8818
        require_once '../forum/forumconfig.inc.php';
8819
8820
        $a_forums = get_forums();
8821
        $return = '<ul class="lp_resource">';
8822
8823
        //First add link
8824
        $return .= '<li class="lp_resource_element">';
8825
        $return .= Display::return_icon('forum_new_small.gif');
8826
        $return .= Display::url(
8827
            get_lang('CreateANewForum'),
8828
            api_get_path(WEB_CODE_PATH) . 'forum/index.php?' . api_get_cidreq() . '&' . http_build_query([
8829
                'action' => 'add',
8830
                'content' => 'forum',
8831
                'lp_id' => $this->lp_id
8832
            ]),
8833
            ['title' => get_lang('CreateANewForum')]
8834
        );
8835
        $return .= '</li>';
8836
8837
        $return .= '<script>
8838
                    function toggle_forum(forum_id){
8839
                        if(document.getElementById("forum_"+forum_id+"_content").style.display == "none"){
8840
                            document.getElementById("forum_"+forum_id+"_content").style.display = "block";
8841
                            document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
8842
                        } else {
8843
                            document.getElementById("forum_"+forum_id+"_content").style.display = "none";
8844
                            document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('add.gif').'";
8845
                        }
8846
                    }
8847
                </script>';
8848
8849
        foreach ($a_forums as $forum) {
8850
            if (!empty($forum['forum_id'])) {
8851
                $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
8852
                $return .= '<a class="moved" href="#">';
8853
                $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8854
                $return .= ' </a>';
8855
                $return .= Display::return_icon('lp_forum.png', '', array(), ICON_SIZE_TINY);
8856
                $return .= '<a style="cursor:hand" onclick="javascript: toggle_forum(' . $forum['forum_id'] . ')" style="vertical-align:middle">
8857
                                <img src="' . Display::returnIconPath('add.gif').'" id="forum_' . $forum['forum_id'] . '_opener" align="absbottom" />
8858
                            </a>
8859
                            <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">' .
8860
                    Security :: remove_XSS($forum['forum_title']) . '</a>';
8861
8862
                $return .= '</li>';
8863
8864
                $return .= '<div style="display:none" id="forum_' . $forum['forum_id'] . '_content">';
8865
                $a_threads = get_threads($forum['forum_id']);
8866
                if (is_array($a_threads)) {
8867
                    foreach ($a_threads as $thread) {
8868
                        $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
8869
                        $return .= '&nbsp;<a class="moved" href="#">';
8870
                        $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
8871
                        $return .= ' </a>';
8872
                        $return .= Display::return_icon('forumthread.png', get_lang('Thread'), array(), ICON_SIZE_TINY);
8873
                        $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 . '">' .
8874
                            Security :: remove_XSS($thread['thread_title']) . '</a>';
8875
                        $return .= '</li>';
8876
                    }
8877
                }
8878
                $return .= '</div>';
8879
            }
8880
        }
8881
        $return .= '</ul>';
8882
8883
        return $return;
8884
    }
8885
8886
    /**
8887
     * // TODO: The output encoding should be equal to the system encoding.
8888
     *
8889
     * Exports the learning path as a SCORM package. This is the main function that
8890
     * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
8891
     * whole thing and returns the zip.
8892
     *
8893
     * This method needs to be called in PHP5, as it will fail with non-adequate
8894
     * XML package (like the ones for PHP4), and it is *not* a static method, so
8895
     * you need to call it on a learnpath object.
8896
     * @TODO The method might be redefined later on in the scorm class itself to avoid
8897
     * creating a SCORM structure if there is one already. However, if the initial SCORM
8898
     * path has been modified, it should use the generic method here below.
8899
     * @TODO link this function with the export_lp() function in the same class
8900
     * @param	string	Optional name of zip file. If none, title of learnpath is
8901
     * 					domesticated and trailed with ".zip"
8902
     * @return	string	Returns the zip package string, or null if error
8903
     */
8904
    public function scorm_export()
8905
    {
8906
        $_course = api_get_course_info();
8907
        $course_id = $_course['real_id'];
8908
8909
        // Remove memory and time limits as much as possible as this might be a long process...
8910
        if (function_exists('ini_set')) {
8911
            api_set_memory_limit('128M');
8912
            ini_set('max_execution_time', 600);
8913
        }
8914
8915
        // Create the zip handler (this will remain available throughout the method).
8916
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
8917
        $sys_course_path = api_get_path(SYS_COURSE_PATH);
8918
        $temp_dir_short = uniqid();
8919
        $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
8920
        $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
8921
        $zip_folder = new PclZip($temp_zip_file);
8922
        $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
8923
        $root_path = $main_path = api_get_path(SYS_PATH);
8924
        $files_cleanup = array();
8925
8926
        // Place to temporarily stash the zip file.
8927
        // create the temp dir if it doesn't exist
8928
        // or do a cleanup before creating the zip file.
8929
        if (!is_dir($temp_zip_dir)) {
8930
            mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
8931
        } else {
8932
            // Cleanup: Check the temp dir for old files and delete them.
8933
            $handle = opendir($temp_zip_dir);
8934
            while (false !== ($file = readdir($handle))) {
8935
                if ($file != '.' && $file != '..') {
8936
                    unlink("$temp_zip_dir/$file");
8937
                }
8938
            }
8939
            closedir($handle);
8940
        }
8941
        $zip_files = $zip_files_abs = $zip_files_dist = array();
8942
        if (is_dir($current_course_path.'/scorm/'.$this->path) && is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')) {
8943
            // Remove the possible . at the end of the path.
8944
            $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
8945
            $dest_path_to_scorm_folder = str_replace('//','/',$temp_zip_dir.'/scorm/'.$dest_path_to_lp);
8946
            mkdir($dest_path_to_scorm_folder, api_get_permissions_for_new_directories(), true);
8947
            $zip_files_dist = copyr($current_course_path.'/scorm/'.$this->path, $dest_path_to_scorm_folder, array('imsmanifest'), $zip_files);
8948
        }
8949
8950
        // Build a dummy imsmanifest structure.
8951
        // Do not add to the zip yet (we still need it).
8952
        // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
8953
        // Aggregation Model official document, section "2.3 Content Packaging".
8954
        // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
8955
        $xmldoc = new DOMDocument('1.0');
8956
        $root = $xmldoc->createElement('manifest');
8957
        $root->setAttribute('identifier', 'SingleCourseManifest');
8958
        $root->setAttribute('version', '1.1');
8959
        $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
8960
        $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
8961
        $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
8962
        $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');
8963
        // Build mandatory sub-root container elements.
8964
        $metadata = $xmldoc->createElement('metadata');
8965
        $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
8966
        $metadata->appendChild($md_schema);
8967
        $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
8968
        $metadata->appendChild($md_schemaversion);
8969
        $root->appendChild($metadata);
8970
8971
        $organizations = $xmldoc->createElement('organizations');
8972
        $resources = $xmldoc->createElement('resources');
8973
8974
        // Build the only organization we will use in building our learnpaths.
8975
        $organizations->setAttribute('default', 'chamilo_scorm_export');
8976
        $organization = $xmldoc->createElement('organization');
8977
        $organization->setAttribute('identifier', 'chamilo_scorm_export');
8978
        // To set the title of the SCORM entity (=organization), we take the name given
8979
        // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
8980
        // learning path charset) as it is the encoding that defines how it is stored
8981
        // in the database. Then we convert it to HTML entities again as the "&" character
8982
        // alone is not authorized in XML (must be &amp;).
8983
        // The title is then decoded twice when extracting (see scorm::parse_manifest).
8984
        $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
8985
        $organization->appendChild($org_title);
8986
8987
        $folder_name = 'document';
8988
8989
        // Removes the learning_path/scorm_folder path when exporting see #4841
8990
        $path_to_remove = null;
8991
        $result = $this->generate_lp_folder($_course);
8992
8993
        if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
8994
            $path_to_remove = 'document'.$result['dir'];
8995
            $path_to_replace = $folder_name.'/';
8996
        }
8997
8998
        //Fixes chamilo scorm exports
8999
        if ($this->ref == 'chamilo_scorm_export') {
9000
            $path_to_remove = 'scorm/'.$this->path.'/document/';
9001
        }
9002
9003
        // For each element, add it to the imsmanifest structure, then add it to the zip.
9004
        // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
9005
        $link_updates = array();
9006
        $links_to_create = array();
9007
        foreach ($this->items as $index => $item) {
9008
            if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) {
9009
                // Get included documents from this item.
9010
                if ($item->type == 'sco') {
9011
                    $inc_docs = $item->get_resources_from_source(
9012
                        null,
9013
                        api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/' . 'scorm/' . $this->path . '/' . $item->get_path()
9014
                    );
9015
                } else {
9016
                    $inc_docs = $item->get_resources_from_source();
9017
                }
9018
                // Give a child element <item> to the <organization> element.
9019
                $my_item_id = $item->get_id();
9020
                $my_item = $xmldoc->createElement('item');
9021
                $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
9022
                $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
9023
                $my_item->setAttribute('isvisible', 'true');
9024
                // Give a child element <title> to the <item> element.
9025
                $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9026
                $my_item->appendChild($my_title);
9027
                // Give a child element <adlcp:prerequisites> to the <item> element.
9028
                $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $this->get_scorm_prereq_string($my_item_id));
9029
                $my_prereqs->setAttribute('type', 'aicc_script');
9030
                $my_item->appendChild($my_prereqs);
9031
                // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
9032
                //$xmldoc->createElement('adlcp:maxtimeallowed','');
9033
                // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
9034
                //$xmldoc->createElement('adlcp:timelimitaction','');
9035
                // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
9036
                //$xmldoc->createElement('adlcp:datafromlms','');
9037
                // Give a child element <adlcp:masteryscore> to the <item> element.
9038
                $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9039
                $my_item->appendChild($my_masteryscore);
9040
9041
                // Attach this item to the organization element or hits parent if there is one.
9042
                if (!empty($item->parent) && $item->parent != 0) {
9043
                    $children = $organization->childNodes;
9044
                    $possible_parent = &$this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
9045
                    if (is_object($possible_parent)) {
9046
                        $possible_parent->appendChild($my_item);
9047 View Code Duplication
                    } else {
9048
                        if ($this->debug > 0) { error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found'); }
9049
                    }
9050
                } else {
9051
                    if ($this->debug > 0) { error_log('No parent'); }
9052
                    $organization->appendChild($my_item);
9053
                }
9054
9055
                // Get the path of the file(s) from the course directory root.
9056
                $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
9057
9058
                if (!empty($path_to_remove)) {
9059
                    //From docs
9060
                    $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
9061
9062
                    //From quiz
9063
                    if ($this->ref == 'chamilo_scorm_export') {
9064
                        $path_to_remove = 'scorm/'.$this->path.'/';
9065
                        $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
9066
                    }
9067
                } else {
9068
                    $my_xml_file_path = $my_file_path;
9069
                }
9070
9071
                $my_sub_dir = dirname($my_file_path);
9072
                $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9073
                $my_xml_sub_dir = $my_sub_dir;
9074
                // Give a <resource> child to the <resources> element
9075
                $my_resource = $xmldoc->createElement('resource');
9076
                $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9077
                $my_resource->setAttribute('type', 'webcontent');
9078
                $my_resource->setAttribute('href', $my_xml_file_path);
9079
                // adlcp:scormtype can be either 'sco' or 'asset'.
9080
                if ($item->type == 'sco') {
9081
                    $my_resource->setAttribute('adlcp:scormtype', 'sco');
9082
                } else {
9083
                    $my_resource->setAttribute('adlcp:scormtype', 'asset');
9084
                }
9085
                // xml:base is the base directory to find the files declared in this resource.
9086
                $my_resource->setAttribute('xml:base', '');
9087
                // Give a <file> child to the <resource> element.
9088
                $my_file = $xmldoc->createElement('file');
9089
                $my_file->setAttribute('href', $my_xml_file_path);
9090
                $my_resource->appendChild($my_file);
9091
9092
                // Dependency to other files - not yet supported.
9093
                $i = 1;
9094
                foreach ($inc_docs as $doc_info) {
9095
                    if (count($doc_info) < 1 || empty($doc_info[0])) { continue; }
9096
                    $my_dep = $xmldoc->createElement('resource');
9097
                    $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
9098
                    $my_dep->setAttribute('identifier', $res_id);
9099
                    $my_dep->setAttribute('type', 'webcontent');
9100
                    $my_dep->setAttribute('adlcp:scormtype', 'asset');
9101
                    $my_dep_file = $xmldoc->createElement('file');
9102
                    // Check type of URL.
9103
                    //error_log(__LINE__.'Now dealing with '.$doc_info[0].' of type '.$doc_info[1].'-'.$doc_info[2], 0);
9104
                    if ($doc_info[1] == 'remote') {
9105
                        // Remote file. Save url as is.
9106
                        $my_dep_file->setAttribute('href', $doc_info[0]);
9107
                        $my_dep->setAttribute('xml:base', '');
9108
                    } elseif ($doc_info[1] == 'local') {
9109
                        switch ($doc_info[2]) {
9110
                            case 'url': // Local URL - save path as url for now, don't zip file.
9111
                                $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9112
                                $current_dir = dirname($abs_path);
9113
                                $current_dir = str_replace('\\', '/', $current_dir);
9114
                                $file_path = realpath($abs_path);
9115
                                $file_path = str_replace('\\', '/', $file_path);
9116
                                $my_dep_file->setAttribute('href', $file_path);
9117
                                $my_dep->setAttribute('xml:base', '');
9118
                                if (strstr($file_path, $main_path) !== false) {
9119
                                    // The calculated real path is really inside Chamilo's root path.
9120
                                    // Reduce file path to what's under the DocumentRoot.
9121
                                    $file_path = substr($file_path, strlen($root_path) - 1);
9122
                                    //echo $file_path;echo '<br /><br />';
9123
                                    //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
9124
                                    $zip_files_abs[] = $file_path;
9125
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9126
                                    $my_dep_file->setAttribute('href', $file_path);
9127
                                    $my_dep->setAttribute('xml:base', '');
9128
                                } elseif (empty($file_path)) {
9129
                                    /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9130
                                    if (strpos($document_root, -1) == '/') {
9131
                                        $document_root = substr(0, -1, $document_root);
9132
                                    }*/
9133
                                    $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
9134
                                    $file_path = str_replace('//', '/', $file_path);
9135
                                    if (file_exists($file_path)) {
9136
                                        $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9137
                                        $zip_files[] = $my_sub_dir.'/'.$file_path;
9138
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9139
                                        $my_dep_file->setAttribute('href', $file_path);
9140
                                        $my_dep->setAttribute('xml:base', '');
9141
                                    }
9142
                                }
9143
                                break;
9144
                            case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
9145
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9146
                                $my_dep->setAttribute('xml:base', '');
9147
9148
                                // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
9149
                                // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
9150
                                $abs_img_path_without_subdir = $doc_info[0];
9151
                                $relp = api_get_path(REL_PATH); // The url-append config param.
9152
                                $pos = strpos($abs_img_path_without_subdir, $relp);
9153
                                if ($pos === 0) {
9154
                                    $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir, strlen($relp));
9155
                                }
9156
                                $file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
9157
                                $file_path = str_replace('\\', '/', $file_path);
9158
                                $file_path = str_replace('//', '/', $file_path);
9159
9160
                                // Prepare the current directory path (until just under 'document') with a trailing slash.
9161
                                $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
9162
                                // Check if the current document is in that path.
9163
                                if (strstr($file_path, $cur_path) !== false) {
9164
                                    // The document is in that path, now get the relative path
9165
                                    // to the containing document.
9166
                                    $orig_file_path = dirname($cur_path.$my_file_path).'/';
9167
                                    $orig_file_path = str_replace('\\', '/', $orig_file_path);
9168
                                    $relative_path = '';
9169
                                    if (strstr($file_path, $cur_path) !== false) {
9170
                                        //$relative_path = substr($file_path, strlen($orig_file_path));
9171
                                        $relative_path = str_replace($cur_path, '', $file_path);
9172
                                        $file_path = substr($file_path, strlen($cur_path));
9173
                                    } else {
9174
                                        // This case is still a problem as it's difficult to calculate a relative path easily
9175
                                        // might still generate wrong links.
9176
                                        //$file_path = substr($file_path,strlen($cur_path));
9177
                                        // Calculate the directory path to the current file (without trailing slash).
9178
                                        $my_relative_path = dirname($file_path);
9179
                                        $my_relative_path = str_replace('\\', '/', $my_relative_path);
9180
                                        $my_relative_file = basename($file_path);
9181
                                        // Calculate the directory path to the containing file (without trailing slash).
9182
                                        $my_orig_file_path = substr($orig_file_path, 0, -1);
9183
                                        $dotdot = '';
9184
                                        $subdir = '';
9185
                                        while (strstr($my_relative_path, $my_orig_file_path) === false && (strlen($my_orig_file_path) > 1) && (strlen($my_relative_path) > 1)) {
9186
                                            $my_relative_path2 = dirname($my_relative_path);
9187
                                            $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
9188
                                            $my_orig_file_path = dirname($my_orig_file_path);
9189
                                            $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
9190
                                            $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'.$subdir;
9191
                                            $dotdot += '../';
9192
                                            $my_relative_path = $my_relative_path2;
9193
                                        }
9194
                                        $relative_path = $dotdot.$subdir.$my_relative_file;
9195
                                    }
9196
                                    // Put the current document in the zip (this array is the array
9197
                                    // that will manage documents already in the course folder - relative).
9198
                                    $zip_files[] = $file_path;
9199
                                    // Update the links to the current document in the containing document (make them relative).
9200
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $relative_path);
9201
                                    $my_dep_file->setAttribute('href', $file_path);
9202
                                    $my_dep->setAttribute('xml:base', '');
9203
                                } elseif (strstr($file_path, $main_path) !== false) {
9204
                                    // The calculated real path is really inside Chamilo's root path.
9205
                                    // Reduce file path to what's under the DocumentRoot.
9206
                                    $file_path = substr($file_path, strlen($root_path));
9207
                                    //echo $file_path;echo '<br /><br />';
9208
                                    //error_log('Reduced path: '.$file_path, 0);
9209
                                    $zip_files_abs[] = $file_path;
9210
                                    $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9211
                                    $my_dep_file->setAttribute('href', 'document/'.$file_path);
9212
                                    $my_dep->setAttribute('xml:base', '');
9213
                                } elseif (empty($file_path)) {
9214
                                    /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9215
                                    if(strpos($document_root,-1) == '/') {
9216
                                        $document_root = substr(0, -1, $document_root);
9217
                                    }*/
9218
                                    $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
9219
                                    $file_path = str_replace('//', '/', $file_path);
9220
9221
                                    $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9222
                                    $current_dir = dirname($abs_path);
9223
                                    $current_dir = str_replace('\\', '/', $current_dir);
9224
9225
                                    if (file_exists($file_path)) {
9226
                                        $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9227
                                        $zip_files[] = $my_sub_dir.'/'.$file_path;
9228
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9229
                                        $my_dep_file->setAttribute('href','document/'.$file_path);
9230
                                        $my_dep->setAttribute('xml:base', '');
9231
                                    }
9232
                                }
9233
                                break;
9234
                            case 'rel':
9235
                                // Path relative to the current document.
9236
                                // Save xml:base as current document's directory and save file in zip as subdir.file_path
9237
                                if (substr($doc_info[0], 0, 2) == '..') {
9238
                                    // Relative path going up.
9239
                                    $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9240
                                    $current_dir = str_replace('\\', '/', $current_dir);
9241
                                    $file_path = realpath($current_dir.$doc_info[0]);
9242
                                    $file_path = str_replace('\\', '/', $file_path);
9243
9244
                                    //error_log($file_path.' <-> '.$main_path,0);
9245
                                    if (strstr($file_path, $main_path) !== false) {
9246
                                        // The calculated real path is really inside Chamilo's root path.
9247
                                        // Reduce file path to what's under the DocumentRoot.
9248
                                        $file_path = substr($file_path, strlen($root_path));
9249
                                        //error_log('Reduced path: '.$file_path, 0);
9250
                                        $zip_files_abs[] = $file_path;
9251
                                        $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9252
                                        $my_dep_file->setAttribute('href', 'document/'.$file_path);
9253
                                        $my_dep->setAttribute('xml:base', '');
9254
                                    }
9255 View Code Duplication
                                } else {
9256
                                    $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
9257
                                    $my_dep_file->setAttribute('href', $doc_info[0]);
9258
                                    $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
9259
                                }
9260
                                break;
9261
                            default:
9262
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9263
                                $my_dep->setAttribute('xml:base', '');
9264
                                break;
9265
                        }
9266
                    }
9267
                    $my_dep->appendChild($my_dep_file);
9268
                    $resources->appendChild($my_dep);
9269
                    $dependency = $xmldoc->createElement('dependency');
9270
                    $dependency->setAttribute('identifierref', $res_id);
9271
                    $my_resource->appendChild($dependency);
9272
                    $i++;
9273
                }
9274
                $resources->appendChild($my_resource);
9275
                $zip_files[] = $my_file_path;
9276
            } else {
9277
9278
                // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
9279
                switch ($item->type) {
9280
                    case TOOL_LINK:
9281
                        $my_item = $xmldoc->createElement('item');
9282
                        $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
9283
                        $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
9284
                        $my_item->setAttribute('isvisible', 'true');
9285
                        // Give a child element <title> to the <item> element.
9286
                        $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9287
                        $my_item->appendChild($my_title);
9288
                        // Give a child element <adlcp:prerequisites> to the <item> element.
9289
                        $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
9290
                        $my_prereqs->setAttribute('type', 'aicc_script');
9291
                        $my_item->appendChild($my_prereqs);
9292
                        // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
9293
                        //$xmldoc->createElement('adlcp:maxtimeallowed', '');
9294
                        // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
9295
                        //$xmldoc->createElement('adlcp:timelimitaction', '');
9296
                        // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
9297
                        //$xmldoc->createElement('adlcp:datafromlms', '');
9298
                        // Give a child element <adlcp:masteryscore> to the <item> element.
9299
                        $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9300
                        $my_item->appendChild($my_masteryscore);
9301
9302
                        // Attach this item to the organization element or its parent if there is one.
9303 View Code Duplication
                        if (!empty($item->parent) && $item->parent != 0) {
9304
                            $children = $organization->childNodes;
9305
                            for ($i = 0; $i < $children->length; $i++) {
9306
                                $item_temp = $children->item($i);
9307
                                if ($item_temp -> nodeName == 'item') {
9308
                                    if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
9309
                                        $item_temp -> appendChild($my_item);
9310
                                    }
9311
                                }
9312
                            }
9313
                        } else {
9314
                            $organization->appendChild($my_item);
9315
                        }
9316
9317
                        $my_file_path = 'link_'.$item->get_id().'.html';
9318
                        $sql = 'SELECT url, title FROM '.Database :: get_course_table(TABLE_LINK).'
9319
                                WHERE c_id = '.$course_id.' AND id='.$item->path;
9320
                        $rs = Database::query($sql);
9321
                        if ($link = Database :: fetch_array($rs)) {
9322
                            $url = $link['url'];
9323
                            $title = stripslashes($link['title']);
9324
                            $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url);
9325
                            $my_xml_file_path = $my_file_path;
9326
                            $my_sub_dir = dirname($my_file_path);
9327
                            $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9328
                            $my_xml_sub_dir = $my_sub_dir;
9329
                            // Give a <resource> child to the <resources> element.
9330
                            $my_resource = $xmldoc->createElement('resource');
9331
                            $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9332
                            $my_resource->setAttribute('type', 'webcontent');
9333
                            $my_resource->setAttribute('href', $my_xml_file_path);
9334
                            // adlcp:scormtype can be either 'sco' or 'asset'.
9335
                            $my_resource->setAttribute('adlcp:scormtype', 'asset');
9336
                            // xml:base is the base directory to find the files declared in this resource.
9337
                            $my_resource->setAttribute('xml:base', '');
9338
                            // give a <file> child to the <resource> element.
9339
                            $my_file = $xmldoc->createElement('file');
9340
                            $my_file->setAttribute('href', $my_xml_file_path);
9341
                            $my_resource->appendChild($my_file);
9342
                            $resources->appendChild($my_resource);
9343
                        }
9344
                        break;
9345
                    case TOOL_QUIZ:
9346
                        $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
9347
                        $exe = new Exercise();
9348
                        $exe->read($exe_id);
9349
                        $my_item = $xmldoc->createElement('item');
9350
                        $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
9351
                        $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
9352
                        $my_item->setAttribute('isvisible', 'true');
9353
                        // Give a child element <title> to the <item> element.
9354
                        $my_title = $xmldoc->createElement('title', htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
9355
                        $my_item->appendChild($my_title);
9356
                        $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
9357
                        //$my_item->appendChild($my_max_score);
9358
                        // Give a child element <adlcp:prerequisites> to the <item> element.
9359
                        $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
9360
                        $my_prereqs->setAttribute('type','aicc_script');
9361
                        $my_item->appendChild($my_prereqs);
9362
                        // Give a child element <adlcp:masteryscore> to the <item> element.
9363
                        $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
9364
                        $my_item->appendChild($my_masteryscore);
9365
9366
                        // Attach this item to the organization element or hits parent if there is one.
9367 View Code Duplication
                        if (!empty($item->parent) && $item->parent != 0) {
9368
                            $children = $organization->childNodes;
9369
                            for ($i = 0; $i < $children->length; $i++) {
9370
                                $item_temp = $children->item($i);
9371
                                if ($item_temp -> nodeName == 'item') {
9372
                                    if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
9373
                                        $item_temp -> appendChild($my_item);
9374
                                    }
9375
                                }
9376
                            }
9377
                        } else {
9378
                            $organization->appendChild($my_item);
9379
                        }
9380
9381
                        // Get the path of the file(s) from the course directory root
9382
                        //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
9383
                        $my_file_path = 'quiz_'.$item->get_id().'.html';
9384
                        // Write the contents of the exported exercise into a (big) html file
9385
                        // to later pack it into the exported SCORM. The file will be removed afterwards.
9386
                        $contents = ScormSection::export_exercise_to_scorm($exe_id, true);
9387
                        $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
9388
                        $res = file_put_contents($tmp_file_path, $contents);
9389
                        if ($res === false) { error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0); }
9390
                        $files_cleanup[] = $tmp_file_path;
9391
                        //error_log($tmp_path); die();
9392
                        //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_QUOTES, 'UTF-8');
9393
                        $my_xml_file_path = $my_file_path;
9394
                        $my_sub_dir = dirname($my_file_path);
9395
                        $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9396
                        //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_QUOTES, 'UTF-8');
9397
                        $my_xml_sub_dir = $my_sub_dir;
9398
                        // Give a <resource> child to the <resources> element.
9399
                        $my_resource = $xmldoc->createElement('resource');
9400
                        $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9401
                        $my_resource->setAttribute('type', 'webcontent');
9402
                        $my_resource->setAttribute('href', $my_xml_file_path);
9403
                        // adlcp:scormtype can be either 'sco' or 'asset'.
9404
                        $my_resource->setAttribute('adlcp:scormtype', 'sco');
9405
                        // xml:base is the base directory to find the files declared in this resource.
9406
                        $my_resource->setAttribute('xml:base', '');
9407
                        // Give a <file> child to the <resource> element.
9408
                        $my_file = $xmldoc->createElement('file');
9409
                        $my_file->setAttribute('href', $my_xml_file_path);
9410
                        $my_resource->appendChild($my_file);
9411
9412
                        // Get included docs.
9413
                        $inc_docs = $item->get_resources_from_source(null,$tmp_file_path);
9414
                        // Dependency to other files - not yet supported.
9415
                        $i = 1;
9416
                        foreach ($inc_docs as $doc_info) {
9417
                            if (count($doc_info) < 1 || empty($doc_info[0])) { continue; }
9418
                            $my_dep = $xmldoc->createElement('resource');
9419
                            $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
9420
                            $my_dep->setAttribute('identifier', $res_id);
9421
                            $my_dep->setAttribute('type', 'webcontent');
9422
                            $my_dep->setAttribute('adlcp:scormtype', 'asset');
9423
                            $my_dep_file = $xmldoc->createElement('file');
9424
                            // Check type of URL.
9425
                            if ($doc_info[1] == 'remote') {
9426
                                // Remote file. Save url as is.
9427
                                $my_dep_file->setAttribute('href', $doc_info[0]);
9428
                                $my_dep->setAttribute('xml:base', '');
9429
                            } elseif ($doc_info[1] == 'local') {
9430
                                switch ($doc_info[2]) {
9431
                                    case 'url': // Local URL - save path as url for now, don't zip file.
9432
                                        // Save file but as local file (retrieve from URL).
9433
                                        $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
9434
                                        $current_dir = dirname($abs_path);
9435
                                        $current_dir = str_replace('\\', '/', $current_dir);
9436
                                        $file_path = realpath($abs_path);
9437
                                        $file_path = str_replace('\\', '/', $file_path);
9438
                                        $my_dep_file->setAttribute('href', 'document/'.$file_path);
9439
                                        $my_dep->setAttribute('xml:base', '');
9440 View Code Duplication
                                        if (strstr($file_path, $main_path) !== false) {
9441
                                            // The calculated real path is really inside the chamilo root path.
9442
                                            // Reduce file path to what's under the DocumentRoot.
9443
                                            $file_path = substr($file_path, strlen($root_path));
9444
                                            //echo $file_path;echo '<br /><br />';
9445
                                            //error_log('Reduced path: '.$file_path, 0);
9446
                                            $zip_files_abs[] = $file_path;
9447
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
9448
                                            $my_dep_file->setAttribute('href', 'document/'.$file_path);
9449
                                            $my_dep->setAttribute('xml:base', '');
9450
                                        } elseif (empty($file_path)) {
9451
                                            /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
9452
                                            if (strpos($document_root,-1) == '/') {
9453
                                                $document_root = substr(0, -1, $document_root);
9454
                                            }*/
9455
                                            $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
9456
                                            $file_path = str_replace('//', '/', $file_path);
9457
                                            if (file_exists($file_path)) {
9458
                                                $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
9459
                                                $zip_files[] = $my_sub_dir.'/'.$file_path;
9460
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
9461
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9462
                                                $my_dep->setAttribute('xml:base', '');
9463
                                            }
9464
                                        }
9465
                                        break;
9466
                                    case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
9467
                                        $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9468
                                        $current_dir = str_replace('\\', '/', $current_dir);
9469
                                        $file_path = realpath($doc_info[0]);
9470
                                        $file_path = str_replace('\\', '/', $file_path);
9471
                                        $my_dep_file->setAttribute('href', $file_path);
9472
                                        $my_dep->setAttribute('xml:base', '');
9473
9474 View Code Duplication
                                        if (strstr($file_path,$main_path) !== false) {
9475
                                            // The calculated real path is really inside the chamilo root path.
9476
                                            // Reduce file path to what's under the DocumentRoot.
9477
                                            $file_path = substr($file_path, strlen($root_path));
9478
                                            //echo $file_path;echo '<br /><br />';
9479
                                            //error_log('Reduced path: '.$file_path, 0);
9480
                                            $zip_files_abs[] = $file_path;
9481
                                            $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9482
                                            $my_dep_file->setAttribute('href', 'document/'.$file_path);
9483
                                            $my_dep->setAttribute('xml:base', '');
9484
                                        } elseif (empty($file_path)) {
9485
                                            /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
9486
                                            if (strpos($document_root,-1) == '/') {
9487
                                                $document_root = substr(0, -1, $document_root);
9488
                                            }*/
9489
                                            $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
9490
                                            $file_path = str_replace('//', '/', $file_path);
9491
                                            if (file_exists($file_path)) {
9492
                                                $file_path = substr($file_path,strlen($current_dir)); // We get the relative path.
9493
                                                $zip_files[] = $my_sub_dir.'/'.$file_path;
9494
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
9495
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9496
                                                $my_dep->setAttribute('xml:base', '');
9497
                                            }
9498
                                        }
9499
                                        break;
9500
                                    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
9501
                                        if (substr($doc_info[0], 0, 2) == '..') {
9502
                                            // Relative path going up.
9503
                                            $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
9504
                                            $current_dir = str_replace('\\', '/', $current_dir);
9505
                                            $file_path = realpath($current_dir.$doc_info[0]);
9506
                                            $file_path = str_replace('\\', '/', $file_path);
9507
                                            //error_log($file_path.' <-> '.$main_path, 0);
9508
                                            if (strstr($file_path, $main_path) !== false) {
9509
                                                // The calculated real path is really inside Chamilo's root path.
9510
                                                // Reduce file path to what's under the DocumentRoot.
9511
9512
                                                $file_path = substr($file_path, strlen($root_path));
9513
                                                $file_path_dest = $file_path;
9514
9515
                                                // File path is courses/CHAMILO/document/....
9516
                                                $info_file_path = explode('/', $file_path);
9517
                                                if ($info_file_path[0] == 'courses') { // Add character "/" in file path.
9518
                                                    $file_path_dest = 'document/'.$file_path;
9519
                                                }
9520
9521
                                                //error_log('Reduced path: '.$file_path, 0);
9522
                                                $zip_files_abs[] = $file_path;
9523
9524
                                                $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path_dest);
9525
                                                $my_dep_file->setAttribute('href', 'document/'.$file_path);
9526
                                                $my_dep->setAttribute('xml:base', '');
9527
                                            }
9528 View Code Duplication
                                        } else {
9529
                                            $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
9530
                                            $my_dep_file->setAttribute('href', $doc_info[0]);
9531
                                            $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
9532
                                        }
9533
                                        break;
9534
                                    default:
9535
                                        $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
9536
                                        $my_dep->setAttribute('xml:base', '');
9537
                                        break;
9538
                                }
9539
                            }
9540
                            $my_dep->appendChild($my_dep_file);
9541
                            $resources->appendChild($my_dep);
9542
                            $dependency = $xmldoc->createElement('dependency');
9543
                            $dependency->setAttribute('identifierref', $res_id);
9544
                            $my_resource->appendChild($dependency);
9545
                            $i++;
9546
                        }
9547
                        $resources->appendChild($my_resource);
9548
                        $zip_files[] = $my_file_path;
9549
                        break;
9550
                    default:
9551
                        // Get the path of the file(s) from the course directory root
9552
                        $my_file_path = 'non_exportable.html';
9553
                        //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
9554
                        $my_xml_file_path = $my_file_path;
9555
                        $my_sub_dir = dirname($my_file_path);
9556
                        $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
9557
                        //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
9558
                        $my_xml_sub_dir = $my_sub_dir;
9559
                        // Give a <resource> child to the <resources> element.
9560
                        $my_resource = $xmldoc->createElement('resource');
9561
                        $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
9562
                        $my_resource->setAttribute('type', 'webcontent');
9563
                        $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
9564
                        // adlcp:scormtype can be either 'sco' or 'asset'.
9565
                        $my_resource->setAttribute('adlcp:scormtype', 'asset');
9566
                        // xml:base is the base directory to find the files declared in this resource.
9567
                        $my_resource->setAttribute('xml:base', '');
9568
                        // Give a <file> child to the <resource> element.
9569
                        $my_file = $xmldoc->createElement('file');
9570
                        $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
9571
                        $my_resource->appendChild($my_file);
9572
                        $resources->appendChild($my_resource);
9573
                        break;
9574
                }
9575
            }
9576
        }
9577
9578
        $organizations->appendChild($organization);
9579
        $root->appendChild($organizations);
9580
        $root->appendChild($resources);
9581
        $xmldoc->appendChild($root);
9582
9583
        // TODO: Add a readme file here, with a short description and a link to the Reload player
9584
        // then add the file to the zip, then destroy the file (this is done automatically).
9585
        // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
9586
9587
        foreach ($zip_files as $file_path) {
9588
            if (empty($file_path)) {
9589
                continue;
9590
            }
9591
9592
            $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
9593
            if (!empty($path_to_remove) && !empty($path_to_replace)) {
9594
                $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
9595
            }
9596
            $this->create_path($dest_file);
9597
            @copy($sys_course_path.$_course['path'].'/'.$file_path, $dest_file);
9598
            // Check if the file needs a link update.
9599
            if (in_array($file_path, array_keys($link_updates))) {
9600
                $string = file_get_contents($dest_file);
9601
                unlink($dest_file);
9602
                foreach ($link_updates[$file_path] as $old_new) {
9603
                    // This is an ugly hack that allows .flv files to be found by the flv player that
9604
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
9605
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
9606
                    // ../../.. to return from inc/lib/flv_player to the document/main path.
9607
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
9608
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
9609 View Code Duplication
                    } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
9610
                        $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
9611
                    }
9612
                    //Fix to avoid problems with default_course_document
9613
                    if (strpos("main/default_course_document", $old_new['dest'] === false)) {
9614
                        //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
9615
                        $newDestination = $old_new['dest'];
9616
                    } else {
9617
                        $newDestination = str_replace('document/', '', $old_new['dest']);
9618
                    }
9619
                    $string = str_replace($old_new['orig'], $newDestination, $string);
9620
9621
                    //Add files inside the HTMLs
9622
                    $new_path = str_replace('/courses/', '', $old_new['orig']);
9623
                    $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
9624
                    if (file_exists($sys_course_path.$new_path)) {
9625
                        copy($sys_course_path.$new_path, $destinationFile);
9626
                    }
9627
                }
9628
                file_put_contents($dest_file, $string);
9629
            }
9630
        }
9631
9632
        foreach ($zip_files_abs as $file_path) {
9633
            if (empty($file_path)) {
9634
                continue;
9635
            }
9636
            if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
9637
                continue;
9638
            }
9639
9640
            $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
9641
            $this->create_path($dest_file);
9642
            copy($main_path.$file_path, $dest_file);
9643
            // Check if the file needs a link update.
9644
            if (in_array($file_path, array_keys($link_updates))) {
9645
                $string = file_get_contents($dest_file);
9646
                unlink($dest_file);
9647
                foreach ($link_updates[$file_path] as $old_new) {
9648
                    // This is an ugly hack that allows .flv files to be found by the flv player that
9649
                    // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
9650
                    // to find the flv to play in document/main/, so we replace main/ in the flv path by
9651
                    // ../../.. to return from inc/lib/flv_player to the document/main path.
9652 View Code Duplication
                    if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
9653
                        $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
9654
                    }
9655
                    $string = str_replace($old_new['orig'], $old_new['dest'], $string);
9656
                }
9657
                file_put_contents($dest_file, $string);
9658
            }
9659
        }
9660
9661
        if (is_array($links_to_create)) {
9662
            foreach ($links_to_create as $file => $link) {
9663
                $file_content = '<!DOCTYPE html><head>
9664
                                <meta charset="'.api_get_language_isocode().'" />
9665
                                <title>'.$link['title'].'</title>
9666
                                </head>
9667
                                <body dir="'.api_get_text_direction().'">
9668
                                <div style="text-align:center">
9669
                                <a href="'.$link['url'].'">'.$link['title'].'</a></div>
9670
                                </body>
9671
                                </html>';
9672
                file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
9673
            }
9674
        }
9675
9676
        // Add non exportable message explanation.
9677
        $lang_not_exportable = get_lang('ThisItemIsNotExportable');
9678
        $file_content = '<!DOCTYPE html><head>
9679
                        <meta charset="'.api_get_language_isocode().'" />
9680
                        <title>'.$lang_not_exportable.'</title>
9681
                        <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
9682
                        </head>
9683
                        <body dir="'.api_get_text_direction().'">';
9684
        $file_content .=
9685
            <<<EOD
9686
                    <style>
9687
            .error-message {
9688
                font-family: arial, verdana, helvetica, sans-serif;
9689
                border-width: 1px;
9690
                border-style: solid;
9691
                left: 50%;
9692
                margin: 10px auto;
9693
                min-height: 30px;
9694
                padding: 5px;
9695
                right: 50%;
9696
                width: 500px;
9697
                background-color: #FFD1D1;
9698
                border-color: #FF0000;
9699
                color: #000;
9700
            }
9701
        </style>
9702
    <body>
9703
        <div class="error-message">
9704
            $lang_not_exportable
9705
        </div>
9706
    </body>
9707
</html>
9708
EOD;
9709
        if (!is_dir($archive_path.$temp_dir_short.'/document')) {
9710
            @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
9711
        }
9712
        file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
9713
9714
        // Add the extra files that go along with a SCORM package.
9715
        $main_code_path = api_get_path(SYS_CODE_PATH).'newscorm/packaging/';
9716
        $extra_files = scandir($main_code_path);
9717
        foreach ($extra_files as $extra_file) {
9718
            if (strpos($extra_file, '.') === 0)
9719
                continue;
9720
            else {
9721
                $dest_file = $archive_path . $temp_dir_short . '/' . $extra_file;
9722
                $this->create_path($dest_file);
9723
                copy($main_code_path.$extra_file, $dest_file);
9724
            }
9725
        }
9726
9727
        // Finalize the imsmanifest structure, add to the zip, then return the zip.
9728
9729
        $manifest = @$xmldoc->saveXML();
9730
        $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
9731
        file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
9732
        $zip_folder->add($archive_path.'/'.$temp_dir_short, PCLZIP_OPT_REMOVE_PATH, $archive_path.'/'.$temp_dir_short.'/');
9733
9734
        // Clean possible temporary files.
9735
        foreach ($files_cleanup as $file) {
9736
            $res = unlink($file);
9737
            if ($res === false) {
9738
                error_log(
9739
                    'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
9740
                    0
9741
                );
9742
            }
9743
        }
9744
        $name = api_replace_dangerous_char($this->get_name()).'.zip';
9745
        DocumentManager::file_send_for_download($temp_zip_file, true, $name);
9746
    }
9747
9748
    /**
9749
     * @param int $lp_id
9750
     * @return bool
9751
     */
9752
    public function scorm_export_to_pdf($lp_id)
9753
    {
9754
        $lp_id = intval($lp_id);
9755
        $files_to_export = array();
9756
        $course_data = api_get_course_info($this->cc);
9757
        if (!empty($course_data)) {
9758
            $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
9759
9760
            $list = self::get_flat_ordered_items_list($lp_id);
9761
            if (!empty($list)) {
9762
                foreach ($list as $item_id) {
9763
                    $item = $this->items[$item_id];
9764
                    switch ($item->type) {
9765
                        case 'document':
9766
                            //Getting documents from a LP with chamilo documents
9767
                            $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
9768
                            // Try loading document from the base course.
9769
                            if (empty($file_data) && !empty($sessionId)) {
9770
                                $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc, false, 0);
9771
                            }
9772
                            $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
9773
                            if (file_exists($file_path)) {
9774
                                $files_to_export[] = array('title'=>$item->get_title(),'path'=>$file_path);
9775
                            }
9776
                            break;
9777
                        case 'asset': //commes from a scorm package generated by chamilo
9778
                        case 'sco':
9779
                            $file_path = $scorm_path.'/'.$item->path;
9780
                            if (file_exists($file_path)) {
9781
                                $files_to_export[] = array('title'=>$item->get_title(), 'path' => $file_path);
9782
                            }
9783
                            break;
9784
                        case 'dokeos_chapter':
9785
                        case 'dir':
9786
                        case 'chapter':
9787
                            $files_to_export[] = array('title'=> $item->get_title(), 'path'=>null);
9788
                            break;
9789
                    }
9790
                }
9791
            }
9792
            $pdf = new PDF();
9793
            $result = $pdf->html_to_pdf($files_to_export, $this->name, $this->cc, true);
9794
            return $result;
9795
        }
9796
9797
        return false;
9798
    }
9799
9800
    /**
9801
     * Temp function to be moved in main_api or the best place around for this.
9802
     * Creates a file path if it doesn't exist
9803
     * @param string $path
9804
     */
9805
    public function create_path($path)
9806
    {
9807
        $path_bits = explode('/', dirname($path));
9808
9809
        // IS_WINDOWS_OS has been defined in main_api.lib.php
9810
        $path_built = IS_WINDOWS_OS ? '' : '/';
9811
9812
        foreach ($path_bits as $bit) {
9813
            if (!empty ($bit)) {
9814
                $new_path = $path_built . $bit;
9815
                if (is_dir($new_path)) {
9816
                    $path_built = $new_path . '/';
9817
                } else {
9818
                    mkdir($new_path, api_get_permissions_for_new_directories());
9819
                    $path_built = $new_path . '/';
9820
                }
9821
            }
9822
        }
9823
    }
9824
9825
    /**
9826
     * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
9827
     * @return	boolean	The results of the unlink function, or false if there was no image to start with
9828
     */
9829
    public function delete_lp_image()
9830
    {
9831
        $img = $this->get_preview_image();
9832
        if ($img != '') {
9833
            $del_file = $this->get_preview_image_path(null, 'sys');
9834
            if (isset($del_file) && file_exists($del_file)) {
9835
                $del_file_2 = $this->get_preview_image_path(64, 'sys');
9836
                if (file_exists($del_file_2)) {
9837
                    unlink($del_file_2);
9838
                }
9839
                $this->set_preview_image('');
9840
                return @unlink($del_file);
9841
            }
9842
        }
9843
        return false;
9844
    }
9845
9846
    /**
9847
     * Uploads an author image to the upload/learning_path/images directory
9848
     * @param	array	The image array, coming from the $_FILES superglobal
9849
     * @return	boolean	True on success, false on error
9850
     */
9851
    public function upload_image($image_array)
9852
    {
9853
        $image_moved = false;
9854
        if (!empty ($image_array['name'])) {
9855
            $upload_ok = process_uploaded_file($image_array);
9856
            $has_attachment = true;
9857
        } else {
9858
            $image_moved = true;
9859
        }
9860
9861
        if ($upload_ok) {
9862
            if ($has_attachment) {
9863
                $courseDir = api_get_course_path() . '/upload/learning_path/images';
9864
                $sys_course_path = api_get_path(SYS_COURSE_PATH);
9865
                $updir = $sys_course_path . $courseDir;
9866
                // Try to add an extension to the file if it hasn't one.
9867
                $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
9868
9869
                if (!filter_extension($new_file_name)) {
9870
                    //Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
9871
                    $image_moved = false;
9872
                } else {
9873
                    $file_extension = explode('.', $image_array['name']);
9874
                    $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
9875
                    $filename = uniqid('');
9876
                    $new_file_name = $filename.'.'.$file_extension;
9877
                    $new_path = $updir.'/'.$new_file_name;
9878
9879
                    // Resize the image.
9880
                    $temp = new Image($image_array['tmp_name']);
9881
                    $temp->resize(104);
9882
                    $result = $temp->send_image($new_path);
9883
9884
                    // Storing the image filename.
9885
                    if ($result) {
9886
                        $image_moved = true;
9887
                        $this->set_preview_image($new_file_name);
9888
9889
                        //Resize to 64px to use on course homepage
9890
                        $temp->resize(64);
9891
                        $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
9892
                        return true;
9893
                    }
9894
                }
9895
            }
9896
        }
9897
9898
        return false;
9899
    }
9900
9901
    /**
9902
     * @param int $lp_id
9903
     * @param string $status
9904
     */
9905
    public function set_autolaunch($lp_id, $status)
9906
    {
9907
        $course_id = api_get_course_int_id();
9908
        $lp_id   = intval($lp_id);
9909
        $status  = intval($status);
9910
        $lp_table = Database::get_course_table(TABLE_LP_MAIN);
9911
9912
        // Setting everything to autolaunch = 0
9913
        $attributes['autolaunch'] = 0;
9914
        $where = array('session_id = ? AND c_id = ? '=> array(api_get_session_id(), $course_id));
9915
        Database::update($lp_table, $attributes, $where);
9916
        if ($status == 1) {
9917
            //Setting my lp_id to autolaunch = 1
9918
            $attributes['autolaunch'] = 1;
9919
            $where = array('id = ? AND session_id = ? AND c_id = ?'=> array($lp_id, api_get_session_id(), $course_id));
9920
            Database::update($lp_table, $attributes, $where );
9921
        }
9922
    }
9923
9924
    /**
9925
     * Gets previous_item_id for the next element of the lp_item table
9926
     * @author Isaac flores paz
9927
     * @return	integer	Previous item ID
9928
     */
9929
    public function select_previous_item_id()
9930
    {
9931
        $course_id = api_get_course_int_id();
9932
        if ($this->debug > 0) {
9933
            error_log('New LP - In learnpath::select_previous_item_id()', 0);
9934
        }
9935
        $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
9936
9937
        // Get the max order of the items
9938
        $sql_max_order = "SELECT max(display_order) AS display_order FROM $table_lp_item
9939
    	                  WHERE c_id = $course_id AND lp_id = '" . $this->lp_id . "'";
9940
        $rs_max_order = Database::query($sql_max_order);
9941
        $row_max_order = Database::fetch_object($rs_max_order);
9942
        $max_order = $row_max_order->display_order;
9943
        // Get the previous item ID
9944
        $sql = "SELECT id as previous FROM $table_lp_item
9945
                WHERE c_id = $course_id AND lp_id = '" . $this->lp_id . "' AND display_order = '".$max_order."' ";
9946
        $rs_max = Database::query($sql);
9947
        $row_max = Database::fetch_object($rs_max);
9948
9949
        // Return the previous item ID
9950
        return $row_max->previous;
9951
    }
9952
9953
    /**
9954
     * Copies an LP
9955
     */
9956
    public function copy()
9957
    {
9958
        $main_path = api_get_path(SYS_CODE_PATH);
9959
        require_once $main_path.'coursecopy/classes/CourseBuilder.class.php';
9960
        require_once $main_path.'coursecopy/classes/CourseArchiver.class.php';
9961
        require_once $main_path.'coursecopy/classes/CourseRestorer.class.php';
9962
        require_once $main_path.'coursecopy/classes/CourseSelectForm.class.php';
9963
9964
        //Course builder
9965
        $cb = new CourseBuilder();
9966
9967
        //Setting tools that will be copied
9968
        $cb->set_tools_to_build(array('learnpaths'));
9969
9970
        //Setting elements that will be copied
9971
        $cb->set_tools_specific_id_list(
9972
            array('learnpaths' => array($this->lp_id))
9973
        );
9974
9975
        $course = $cb->build();
9976
9977
        //Course restorer
9978
        $course_restorer = new CourseRestorer($course);
9979
        $course_restorer->set_add_text_in_items(true);
9980
        $course_restorer->set_tool_copy_settings(array('learnpaths' => array('reset_dates' => true)));
9981
        $course_restorer->restore(api_get_course_id(), api_get_session_id(), false, false);
9982
    }
9983
9984
    public function verify_document_size($s)
9985
    {
9986
        $post_max = ini_get('post_max_size');
9987 View Code Duplication
        if (substr($post_max, -1, 1) == 'M') {
9988
            $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
9989
        } elseif (substr($post_max, -1, 1) == 'G') {
9990
            $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
9991
        }
9992
        $upl_max = ini_get('upload_max_filesize');
9993 View Code Duplication
        if (substr($upl_max, -1, 1) == 'M') {
9994
            $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
9995
        } elseif (substr($upl_max, -1, 1) == 'G') {
9996
            $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
9997
        }
9998
        $documents_total_space = DocumentManager::documents_total_space();
9999
        $course_max_space = DocumentManager::get_course_quota();
10000
        $total_size = filesize($s) + $documents_total_space;
10001
        if (filesize($s)>$post_max || filesize($s)>$upl_max  || $total_size>$course_max_space ){
10002
            return true;
10003
        } else{
10004
            return false;
10005
        }
10006
    }
10007
10008
    /**
10009
     * Clear LP prerequisites
10010
     */
10011
    public function clear_prerequisites()
10012
    {
10013
        $course_id = $this->get_course_int_id();
10014
        if ($this->debug > 0) {
10015
            error_log('New LP - In learnpath::clear_prerequisites()', 0);
10016
        }
10017
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
10018
        $lp_id = $this->get_id();
10019
        //Cleaning prerequisites
10020
        $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
10021
                WHERE c_id = ".$course_id." AND lp_id = '$lp_id'";
10022
        Database::query($sql);
10023
10024
        //Cleaning mastery score for exercises
10025
        $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
10026
                WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND item_type = 'quiz'";
10027
        Database::query($sql);
10028
    }
10029
10030
    public function set_previous_step_as_prerequisite_for_all_items()
10031
    {
10032
        $tbl_lp_item = Database :: get_course_table(TABLE_LP_ITEM);
10033
        $course_id = $this->get_course_int_id();
10034
        $lp_id = $this->get_id();
10035
10036
        if (!empty($this->items)) {
10037
            $previous_item_id = null;
10038
            $previous_item_max = 0;
10039
            $previous_item_type = null;
10040
            $last_item_not_chapter = null;
10041
            $last_item_not_chapter_type = null;
10042
            $last_item_not_chapter_max = null;
10043
            foreach ($this->items as $item) {
10044
                // if there was a previous item... (otherwise jump to set it)
10045
                if (!empty($previous_item_id)) {
10046
                    $current_item_id = $item->get_id(); //save current id
10047
                    if (!in_array($item->get_type(), array('dokeos_chapter', 'chapter'))) {
10048
                        // Current item is not a folder, so it qualifies to get a prerequisites
10049
                        if ($last_item_not_chapter_type == 'quiz') {
10050
                            // if previous is quiz, mark its max score as default score to be achieved
10051
                            $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_chapter_max'
10052
                                    WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$last_item_not_chapter'";
10053
                            Database::query($sql);
10054
                        }
10055
                        // now simply update the prerequisite to set it to the last non-chapter item
10056
                        $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_chapter'
10057
                                WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$current_item_id'";
10058
                        Database::query($sql);
10059
                        // record item as 'non-chapter' reference
10060
                        $last_item_not_chapter = $item->get_id();
10061
                        $last_item_not_chapter_type = $item->get_type();
10062
                        $last_item_not_chapter_max = $item->get_max();
10063
                    }
10064
                } else {
10065
                    if (!in_array($item->get_type(), array('dokeos_chapter', 'chapter'))) {
10066
                        // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
10067
                        $last_item_not_chapter = $item->get_id();
10068
                        $last_item_not_chapter_type = $item->get_type();
10069
                        $last_item_not_chapter_max = $item->get_max();
10070
                    }
10071
                }
10072
                // Saving the item as "previous item" for the next loop
10073
                $previous_item_id = $item->get_id();
10074
                $previous_item_max = $item->get_max();
10075
                $previous_item_type = $item->get_type();
10076
            }
10077
        }
10078
    }
10079
10080
    /**
10081
     * @param array $params
10082
     */
10083
    public static function createCategory($params)
10084
    {
10085
        $em = Database::getManager();
10086
        $item = new CLpCategory();
10087
        $item->setName($params['name']);
10088
        $item->setCId($params['c_id']);
10089
        $em->persist($item);
10090
        $em->flush();
10091
    }
10092
    /**
10093
     * @param array $params
10094
     */
10095
    public static function updateCategory($params)
10096
    {
10097
        $em = Database::getManager();
10098
        /** @var CLpCategory $item */
10099
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
10100
        if ($item) {
10101
            $item->setName($params['name']);
10102
            $em->merge($item);
10103
            $em->flush();
10104
        }
10105
    }
10106
10107
    /**
10108
     * @param int $id
10109
     */
10110 View Code Duplication
    public static function moveUpCategory($id)
10111
    {
10112
        $em = Database::getManager();
10113
        /** @var CLpCategory $item */
10114
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10115
        if ($item) {
10116
            $position = $item->getPosition() - 1;
10117
            $item->setPosition($position);
10118
            $em->persist($item);
10119
            $em->flush();
10120
        }
10121
    }
10122
10123
    /**
10124
     * @param int $id
10125
     */
10126 View Code Duplication
    public static function moveDownCategory($id)
10127
    {
10128
        $em = Database::getManager();
10129
        /** @var CLpCategory $item */
10130
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10131
        if ($item) {
10132
            $position = $item->getPosition() + 1;
10133
            $item->setPosition($position);
10134
            $em->persist($item);
10135
            $em->flush();
10136
        }
10137
    }
10138
10139
    /**
10140
     * @param int $courseId
10141
     * @return int|mixed
10142
     */
10143
    public static function getCountCategories($courseId)
10144
    {
10145
        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...
10146
            return 0;
10147
        }
10148
        $em = Database::getManager();
10149
        $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
10150
        $query->setParameter('id', $courseId);
10151
10152
        return $query->getSingleScalarResult();
10153
    }
10154
10155
    /**
10156
     * @param int $courseId
10157
     *
10158
     * @return mixed
10159
     */
10160 View Code Duplication
    public static function getCategories($courseId)
10161
    {
10162
        $em = Database::getManager();
10163
        //Default behaviour
10164
        /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
10165
            array('cId' => $course_id),
10166
            array('name' => 'ASC')
10167
        );*/
10168
10169
        // Using doctrine extensions
10170
        $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->getBySortableGroupsQuery(
10171
            array('cId' => $courseId)
10172
        )->getResult();
10173
10174
        return $items;
10175
    }
10176
10177
    /**
10178
     * @param int $id
10179
     *
10180
     * @return mixed
10181
     */
10182
    public static function getCategory($id)
10183
    {
10184
        $em = Database::getManager();
10185
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10186
10187
        return $item;
10188
    }
10189
10190
    /**
10191
     * @param int $courseId
10192
     * @return array
10193
     */
10194 View Code Duplication
    public static function getCategoryByCourse($courseId)
10195
    {
10196
        $em = Database::getManager();
10197
        $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(array('cId' => $courseId));
10198
10199
        return $items;
10200
    }
10201
10202
    /**
10203
     * @param int $id
10204
     *
10205
     * @return mixed
10206
     */
10207
    public static function deleteCategory($id)
10208
    {
10209
        $em = Database::getManager();
10210
        $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
10211
        if ($item) {
10212
10213
            $courseId = $item->getCId();
10214
            $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
10215
            $query->setParameter('id', $courseId);
10216
            $query->setParameter('catId', $item->getId());
10217
            $lps = $query->getResult();
10218
10219
            // Setting category = 0.
10220
            if ($lps) {
10221
                foreach ($lps as $lpItem) {
10222
                    $lpItem->setCategoryId(0);
10223
                }
10224
            }
10225
10226
            // Removing category.
10227
            $em->remove($item);
10228
            $em->flush();
10229
        }
10230
    }
10231
10232
    /**
10233
     * @param int $courseId
10234
     * @param bool $addSelectOption
10235
     *
10236
     * @return mixed
10237
     */
10238
    static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
10239
    {
10240
        $items = self::getCategoryByCourse($courseId);
10241
        $cats = array();
10242
        if ($addSelectOption) {
10243
            $cats = array(get_lang('SelectACategory'));
10244
        }
10245
10246
        if (!empty($items)) {
10247
            foreach ($items as $cat) {
10248
                $cats[$cat->getId()] = $cat->getName();
10249
            }
10250
        }
10251
10252
        return $cats;
10253
    }
10254
10255
    /**
10256
     * Return the scorm item type object with spaces replaced with _
10257
     * The return result is use to build a css classname like scorm_type_$return
10258
     * @param $in_type
10259
     * @return mixed
10260
     */
10261
    private static function format_scorm_type_item($in_type)
10262
    {
10263
        return str_replace(' ', '_', $in_type);
10264
    }
10265
10266
    /**
10267
     * @return \learnpath
10268
     */
10269
    public static function getLpFromSession($courseCode, $lp_id, $user_id)
10270
    {
10271
        $lpObject = Session::read('lpobject');
10272
        $learnPath = null;
10273
        if (isset($lpObject)) {
10274
            $learnPath = unserialize($lpObject);
10275
        }
10276
10277
        if (!is_object($learnPath)) {
10278
            $learnPath = new learnpath($courseCode, $lp_id, $user_id);
10279
        }
10280
10281
        return $learnPath;
10282
    }
10283
10284
    /**
10285
     * @param int $itemId
10286
     * @return learnpathItem|false
10287
     */
10288
    public function getItem($itemId)
10289
    {
10290
        if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
10291
            return $this->items[$itemId];
10292
        }
10293
10294
        return false;
10295
    }
10296
10297
    /**
10298
     * @return int
10299
     */
10300
    public function getCategoryId()
10301
    {
10302
        return $this->categoryId;
10303
    }
10304
10305
    /**
10306
     * @param int $categoryId
10307
     * @return bool
10308
     */
10309
    public function setCategoryId($categoryId)
10310
    {
10311
        $this->categoryId = intval($categoryId);
10312
10313
        $courseId = api_get_course_int_id();
10314
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
10315
        $lp_id = $this->get_id();
10316
        $sql = "UPDATE $lp_table SET category_id = ".$this->categoryId."
10317
                WHERE c_id = $courseId AND id = $lp_id";
10318
        Database::query($sql);
10319
10320
        return true;
10321
    }
10322
10323
    /**
10324
     * Get whether this is a learning path with the possibility to subscribe
10325
     * users or not
10326
     * @return int
10327
     */
10328
    public function getSubscribeUsers()
10329
    {
10330
        return $this->subscribeUsers;
10331
    }
10332
10333
    /**
10334
     * Set whether this is a learning path with the possibility to subscribe
10335
     * users or not
10336
     * @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...
10337
     */
10338
    public function setSubscribeUsers($value)
10339
    {
10340
        if ($this->debug > 0) {
10341
            error_log('New LP - In learnpath::set_subscribe_users()', 0);
10342
        }
10343
        $this->subscribeUsers = intval($value);;
10344
        $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
10345
        $lp_id = $this->get_id();
10346
        $sql = "UPDATE $lp_table SET subscribe_users = ".$this->subscribeUsers."
10347
                WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
10348
        Database::query($sql);
10349
10350
        return true;
10351
    }
10352
10353
    /**
10354
     * Calculate the count of stars for a user in this LP
10355
     * This calculation is based on the following rules:
10356
     * - the student gets one star when he gets to 50% of the learning path
10357
     * - the student gets a second star when the average score of all tests inside the learning path >= 50%
10358
     * - the student gets a third star when the average score of all tests inside the learning path >= 80%
10359
     * - the student gets the final star when the score for the *last* test is >= 80%
10360
     * @param int $sessionId Optional. The session ID
10361
     * @return int The count of stars
10362
     */
10363
    public function getCalculateStars($sessionId = 0)
10364
    {
10365
        $stars = 0;
10366
10367
        $progress = self::getProgress($this->lp_id, $this->user_id, $this->course_int_id, $sessionId);
10368
10369
        if ($progress >= 50) {
10370
            $stars++;
10371
        }
10372
10373
        // Calculate stars chapters evaluation
10374
        $exercisesItems = $this->getExercisesItems();
10375
10376
        if (!empty($exercisesItems)) {
10377
            $totalResult = 0;
10378
10379
            foreach ($exercisesItems as $exerciseItem) {
10380
                $exerciseResultInfo = Event::getExerciseResultsByUser(
10381
                    $this->user_id,
10382
                    $exerciseItem->path,
10383
                    $this->course_int_id,
10384
                    $sessionId,
10385
                    $this->lp_id,
10386
                    $exerciseItem->db_id
10387
                );
10388
10389
                $exerciseResultInfo = end($exerciseResultInfo);
10390
10391
                if (!$exerciseResultInfo) {
10392
                    continue;
10393
                }
10394
10395
                $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
10396
10397
                $totalResult += $exerciseResult;
10398
            }
10399
10400
            $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
10401
10402
            if ($totalExerciseAverage >= 50) {
10403
                $stars++;
10404
            }
10405
10406
            if ($totalExerciseAverage >= 80) {
10407
                $stars++;
10408
            }
10409
        }
10410
10411
        // Calculate star for final evaluation
10412
        $finalEvaluationItem = $this->getFinalEvaluationItem();
10413
10414
        if (!empty($finalEvaluationItem)) {
10415
            $evaluationResultInfo = Event::getExerciseResultsByUser(
10416
                $this->user_id,
10417
                $finalEvaluationItem->path,
10418
                $this->course_int_id,
10419
                $sessionId,
10420
                $this->lp_id,
10421
                $finalEvaluationItem->db_id
10422
            );
10423
10424
            $evaluationResultInfo = end($evaluationResultInfo);
10425
10426
            if ($evaluationResultInfo) {
10427
                $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
10428
10429
                if ($evaluationResult >= 80) {
10430
                    $stars++;
10431
                }
10432
            }
10433
        }
10434
10435
        return $stars;
10436
    }
10437
10438
    /**
10439
     * Get the items of exercise type
10440
     * @return array The items. Otherwise return false
10441
     */
10442 View Code Duplication
    public function getExercisesItems()
10443
    {
10444
        $exercises = [];
10445
10446
        foreach ($this->items as $item) {
10447
            if ($item->type != 'quiz') {
10448
                continue;
10449
            }
10450
10451
            $exercises[] = $item;
10452
        }
10453
10454
        array_pop($exercises);
10455
10456
        return $exercises;
10457
    }
10458
10459
    /**
10460
     * Get the item of exercise type (evaluation type)
10461
     * @return array The final evaluation. Otherwise return false
10462
     */
10463 View Code Duplication
    public function getFinalEvaluationItem()
10464
    {
10465
        $exercises = [];
10466
10467
        foreach ($this->items as $item) {
10468
            if ($item->type != 'quiz') {
10469
                continue;
10470
            }
10471
10472
            $exercises[] = $item;
10473
        }
10474
10475
        return array_pop($exercises);
10476
    }
10477
10478
    /**
10479
     * Calculate the total points achieved for the current user in this learning path
10480
     * @param int $sessionId Optional. The session Id
10481
     * @return int
10482
     */
10483
    public function getCalculateScore($sessionId = 0)
10484
    {
10485
        // Calculate stars chapters evaluation
10486
        $exercisesItems = $this->getExercisesItems();
10487
        $finalEvaluationItem = $this->getFinalEvaluationItem();
10488
10489
        $totalExercisesResult = 0;
10490
        $totalEvaluationResult = 0;
10491
10492
        if ($exercisesItems !== false) {
10493
            foreach ($exercisesItems as $exerciseItem) {
10494
                $exerciseResultInfo = Event::getExerciseResultsByUser(
10495
                    $this->user_id,
10496
                    $exerciseItem->path,
10497
                    $this->course_int_id,
10498
                    $sessionId,
10499
                    $this->lp_id,
10500
                    $exerciseItem->db_id
10501
                );
10502
10503
                $exerciseResultInfo = end($exerciseResultInfo);
10504
10505
                if (!$exerciseResultInfo) {
10506
                    continue;
10507
                }
10508
10509
                $totalExercisesResult += $exerciseResultInfo['exe_result'];
10510
            }
10511
        }
10512
10513
        if (!empty($finalEvaluationItem)) {
10514
            $evaluationResultInfo = Event::getExerciseResultsByUser(
10515
                $this->user_id,
10516
                $finalEvaluationItem->path,
10517
                $this->course_int_id,
10518
                $sessionId,
10519
                $this->lp_id,
10520
                $finalEvaluationItem->db_id
10521
            );
10522
10523
            $evaluationResultInfo = end($evaluationResultInfo);
10524
10525
            if ($evaluationResultInfo) {
10526
                $totalEvaluationResult += $evaluationResultInfo['exe_result'];
10527
            }
10528
        }
10529
10530
        return $totalExercisesResult + $totalEvaluationResult;
10531
    }
10532
10533
    /**
10534
     * Check if URL is not allowed to be show in a iframe
10535
     * @param string $src
10536
     *
10537
     * @return string
10538
     */
10539
    public function fixBlockedLinks($src)
10540
    {
10541
        $urlInfo = parse_url($src);
10542
        //$platformProtocol = api_get_protocol();
10543
10544
        $platformProtocol = 'https';
10545
        if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
10546
            $platformProtocol = 'http';
10547
        }
10548
10549
        $protocolFixApplied = false;
10550
        //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
10551
        $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
10552
        if ($platformProtocol != $scheme) {
10553
            $_SESSION['x_frame_source'] = $src;
10554
            $src = 'blank.php?error=x_frames_options';
10555
            $protocolFixApplied = true;
10556
        }
10557
10558
        if ($protocolFixApplied == false) {
10559
            if (strpos($src, api_get_path(WEB_CODE_PATH)) === false) {
10560
                // Check X-Frame-Options
10561
                $ch = curl_init();
10562
10563
                $options = array(
10564
                    CURLOPT_URL => $src,
10565
                    CURLOPT_RETURNTRANSFER => true,
10566
                    CURLOPT_HEADER => true,
10567
                    CURLOPT_FOLLOWLOCATION => true,
10568
                    CURLOPT_ENCODING => "",
10569
                    CURLOPT_AUTOREFERER => true,
10570
                    CURLOPT_CONNECTTIMEOUT => 120,
10571
                    CURLOPT_TIMEOUT => 120,
10572
                    CURLOPT_MAXREDIRS => 10,
10573
                );
10574
                curl_setopt_array($ch, $options);
10575
                $response = curl_exec($ch);
10576
                $httpCode = curl_getinfo($ch);
10577
                $headers = substr($response, 0, $httpCode['header_size']);
10578
10579
                $error = false;
10580
                if (stripos($headers, 'X-Frame-Options: DENY') > -1 ||
10581
                    stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
10582
                ) {
10583
                    $error = true;
10584
                }
10585
10586
                if ($error) {
10587
                    $_SESSION['x_frame_source'] = $src;
10588
                    $src = 'blank.php?error=x_frames_options';
10589
                }
10590
            }
10591
        }
10592
10593
        return $src;
10594
    }
10595
10596
    /**
10597
     * Check if this LP has a created forum in the basis course
10598
     * @return boolean
10599
     */
10600
    public function lpHasForum()
10601
    {
10602
        $forumTable = Database::get_course_table(TABLE_FORUM);
10603
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
10604
10605
        $fakeFrom = "
10606
            $forumTable f
10607
            INNER JOIN $itemProperty ip
10608
            ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
10609
        ";
10610
10611
        $resultData = Database::select(
10612
            'COUNT(f.iid) AS qty',
10613
            $fakeFrom,
10614
            [
10615
                'where' => [
10616
                    'ip.visibility != ? AND ' => 2,
10617
                    'ip.tool = ? AND ' => TOOL_FORUM,
10618
                    'f.c_id = ? AND ' => intval($this->course_int_id),
10619
                    'f.lp_id = ?' => intval($this->lp_id)
10620
                ]
10621
            ],
10622
            'first'
10623
        );
10624
10625
        if ($resultData['qty'] > 0) {
10626
            return true;
10627
        }
10628
10629
        return false;
10630
    }
10631
10632
    /**
10633
     * Get the forum for this learning path
10634
     * @return boolean
10635
     */
10636
    public function getForum($sessionId = 0)
10637
    {
10638
        $forumTable = Database::get_course_table(TABLE_FORUM);
10639
        $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
10640
10641
        $fakeFrom = "$forumTable f
10642
            INNER JOIN $itemProperty ip ";
10643
10644
        if ($this->lp_session_id == 0) {
10645
            $fakeFrom .= "
10646
                ON (
10647
                    f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
10648
                        f.session_id = ip.session_id OR ip.session_id IS NULL
10649
                    )
10650
                )
10651
            ";
10652
        } else {
10653
            $fakeFrom .= "
10654
                ON (
10655
                    f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
10656
                )
10657
            ";
10658
        }
10659
10660
        $resultData = Database::select(
10661
            'f.*',
10662
            $fakeFrom,
10663
            [
10664
                'where' => [
10665
                    'ip.visibility != ? AND ' => 2,
10666
                    'ip.tool = ? AND ' => TOOL_FORUM,
10667
                    'f.session_id = ? AND ' => $sessionId,
10668
                    'f.c_id = ? AND ' => intval($this->course_int_id),
10669
                    'f.lp_id = ?' => intval($this->lp_id)
10670
                ]
10671
            ],
10672
            'first'
10673
        );
10674
10675
        if (empty($resultData)) {
10676
            return false;
10677
        }
10678
10679
        return $resultData;
10680
    }
10681
10682
    /**
10683
     * Create a forum for this learning path
10684
     * @param type $forumCategoryId
10685
     * @return int The forum ID if was created. Otherwise return false
10686
     */
10687
    public function createForum($forumCategoryId)
10688
    {
10689
        require_once api_get_path(SYS_CODE_PATH) . '/forum/forumfunction.inc.php';
10690
10691
        $forumId = store_forum(
10692
            [
10693
                'lp_id' => $this->lp_id,
10694
                'forum_title' => $this->name,
10695
                'forum_comment' => null,
10696
                'forum_category' => intval($forumCategoryId),
10697
                'students_can_edit_group' => ['students_can_edit' => 0],
10698
                'allow_new_threads_group' => ['allow_new_threads' => 0],
10699
                'default_view_type_group' => ['default_view_type' => 'flat'],
10700
                'group_forum' => 0,
10701
                'public_private_group_forum_group' => ['public_private_group_forum' => 'public']
10702
            ],
10703
            [],
10704
            true
10705
        );
10706
10707
        return $forumId;
10708
    }
10709
10710
    private function getFinalItem()
10711
    {
10712
        if (empty($this->items)) {
10713
            return null;
10714
        }
10715
10716
        foreach ($this->items as $item) {
10717
            if ($item->type !== 'final_item') {
10718
                continue;
10719
            }
10720
10721
            return $item;
10722
        }
10723
    }
10724
10725
    private function getFinalItemTemplate()
10726
    {
10727
        $finalItem = $this->getFinalItem();
10728
10729
        if (!$finalItem) {
10730
            return file_get_contents(api_get_path(SYS_CODE_PATH) . 'newscorm/final_item_template/template.html');
10731
        }
10732
10733
        $doc = DocumentManager::get_document_data_by_id($finalItem->path, $this->cc);
10734
10735
        return file_get_contents($doc['absolute_path']);
10736
    }
10737
10738
    /**
10739
     * 
10740
     * @return html
10741
     */
10742
    public function getFinalItemForm()
10743
    {
10744
        $finalItem = $this->getFinalItem();
10745
        $title = '';
10746
        $content = '';
10747
10748
        if ($finalItem) {
10749
            $title = $finalItem->title;
10750
            $content = $this->getFinalItemTemplate();
10751
        }
10752
10753
        $courseInfo = api_get_course_info();
10754
        $result = $this->generate_lp_folder($courseInfo);
10755
        $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
10756
        $relative_prefix = '../../';
10757
10758
        $editorConfig = [
10759
            'ToolbarSet' => 'LearningPathDocuments',
10760
            'Width' => '100%',
10761
            'Height' => '500',
10762
            'FullPage' => true,
10763
            'CreateDocumentDir' => $relative_prefix,
10764
            'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/',
10765
            'BaseHref' => api_get_path(WEB_COURSE_PATH) . api_get_course_path() . '/document/' . $relative_path
10766
        ];
10767
10768
        $url = api_get_self() . '?' . api_get_cidreq() . '&' . http_build_query([
10769
            'type' => 'document',
10770
            'lp_id' => $this->lp_id
10771
        ]);
10772
10773
        $form = new FormValidator('final_item', 'POST', $url);
10774
        $form->addText('title', get_lang('Title'));
10775
        $form->addButtonSave(get_lang('LPCreateDocument'));
10776
        $renderer = $form->defaultRenderer();
10777
        $renderer->setElementTemplate('<div class="editor-lp">&nbsp;{label}{element}</div>', 'content');
10778
        $form->addHtmlEditor('content', null, null, true, $editorConfig, true);
10779
        $form->addHidden('action', 'add_final_item');
10780
        $form->addHidden('previous', $this->get_last());
10781
10782
        $form->setDefaults(['title' => $title, 'content' => $content]);
10783
10784
        if ($form->validate()) {
10785
            $values = $form->exportValues();
10786
10787
            $lastItemId = $this->get_last();
10788
10789
            if (!$finalItem) {
10790
                $documentId = $this->create_document($this->course_info, $values['content'], $values['title']);
10791
                $this->add_item(
10792
                    0,
10793
                    $lastItemId,
10794
                    'final_item',
10795
                    $documentId,
10796
                    $values['title'],
10797
                    ''
10798
                );
10799
            } else {
10800
                $this->edit_document($this->course_info);
10801
            }
10802
        }
10803
10804
        return $form->returnForm();
10805
    }
10806
}
10807
10808
if (!function_exists('trim_value')) {
10809
    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...
10810
        $value = trim($value);
10811
    }
10812
}
10813