Completed
Push — master ( b77cfe...000f93 )
by Julito
22:58 queued 11:19
created

LpItemOrderList::getListOfParents()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 10
rs 9.4285
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Responses to AJAX calls.
8
 */
9
require_once __DIR__.'/../global.inc.php';
10
api_protect_course_script(true);
11
12
$debug = false;
13
$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : '';
14
15
$courseId = api_get_course_int_id();
16
$sessionId = api_get_session_id();
17
18
if ($debug) {
19
    error_log('----------lp.ajax-------------- action '.$action);
20
}
21
22
switch ($action) {
23
    case 'get_documents':
24
        $courseInfo = api_get_course_info();
25
        $folderId = isset($_GET['folder_id']) ? $_GET['folder_id'] : null;
26
        if (empty($folderId)) {
27
            exit;
28
        }
29
        $lpId = isset($_GET['lp_id']) ? $_GET['lp_id'] : null;
30
        $url = isset($_GET['url']) ? $_GET['url'] : null;
31
32
        echo DocumentManager::get_document_preview(
33
            $courseInfo,
34
            $lpId,
35
            null,
36
            api_get_session_id(),
37
            true,
38
            null,
39
            $url,
40
            true,
41
            false,
42
            $folderId
43
        );
44
        break;
45
    case 'add_lp_item':
46
        if (api_is_allowed_to_edit(null, true)) {
47
            /** @var learnpath $learningPath */
48
            $learningPath = Session::read('oLP');
49
            if ($learningPath) {
50
                // Updating the lp.modified_on
51
                $learningPath->set_modified_on();
52
                $title = $_REQUEST['title'];
53
                if ($_REQUEST['type'] == TOOL_QUIZ) {
54
                    $title = Exercise::format_title_variable($title);
55
                }
56
57
                $parentId = isset($_REQUEST['parent_id']) ? $_REQUEST['parent_id'] : '';
58
                $previousId = isset($_REQUEST['previous_id']) ? $_REQUEST['previous_id'] : '';
59
60
                $itemId = $learningPath->add_item(
61
                    $parentId,
62
                    $previousId,
63
                    $_REQUEST['type'],
64
                    $_REQUEST['id'],
65
                    $title,
66
                    null
67
                );
68
69
                /** @var learnpath $learningPath */
70
                $learningPath = Session::read('oLP');
71
                if ($learningPath) {
72
                    echo $learningPath->returnLpItemList(null);
73
                }
74
            }
75
        }
76
        break;
77
    case 'update_lp_item_order':
78
        if (api_is_allowed_to_edit(null, true)) {
79
            $new_order = $_POST['new_order'];
80
            $sections = explode('^', $new_order);
81
            $new_array = [];
82
83
            // We have to update parent_item_id, previous_item_id, next_item_id, display_order in the database
84
            $itemList = new LpItemOrderList();
85
            foreach ($sections as $items) {
86
                if (!empty($items)) {
87
                    list($id, $parent_id) = explode('|', $items);
88
                    $item = new LpOrderItem($id, $parent_id);
89
                    $itemList->add($item);
90
                }
91
            }
92
93
            $parents = $itemList->getListOfParents();
94
            foreach ($parents as $parentId) {
95
                $sameParentLpItemList = $itemList->getItemWithSameParent($parentId);
96
                $previous_item_id = 0;
97
                for ($i = 0; $i < count($sameParentLpItemList->list); $i++) {
98
                    $item_id = $sameParentLpItemList->list[$i]->id;
99
                    // display_order
100
                    $display_order = $i + 1;
101
                    $itemList->setParametersForId($item_id, $display_order, 'display_order');
102
                    // previous_item_id
103
                    $itemList->setParametersForId($item_id, $previous_item_id, 'previous_item_id');
104
                    $previous_item_id = $item_id;
105
                    // next_item_id
106
                    $next_item_id = 0;
107
                    if ($i < count($sameParentLpItemList->list) - 1) {
108
                        $next_item_id = $sameParentLpItemList->list[$i + 1]->id;
109
                    }
110
                    $itemList->setParametersForId($item_id, $next_item_id, 'next_item_id');
111
                }
112
            }
113
114
            $table = Database::get_course_table(TABLE_LP_ITEM);
115
116
            foreach ($itemList->list as $item) {
117
                $params = [];
118
                $params['display_order'] = $item->display_order;
119
                $params['previous_item_id'] = $item->previous_item_id;
120
                $params['next_item_id'] = $item->next_item_id;
121
                $params['parent_item_id'] = $item->parent_item_id;
122
123
                Database::update(
124
                    $table,
125
                    $params,
126
                    [
127
                        'iid = ? AND c_id = ? ' => [
128
                            intval($item->id),
129
                            $courseId,
130
                        ],
131
                    ]
132
                );
133
            }
134
            echo Display::return_message(get_lang('Saved'), 'confirm');
135
        }
136
        break;
137
    case 'record_audio':
138
        if (api_is_allowed_to_edit(null, true) == false) {
139
            exit;
140
        }
141
        /** @var Learnpath $lp */
142
        $lp = Session::read('oLP');
143
        $course_info = api_get_course_info();
144
145
        $lpPathInfo = $lp->generate_lp_folder($course_info);
146
147
        if (empty($lpPathInfo)) {
148
            exit;
149
        }
150
151
        foreach (['video', 'audio'] as $type) {
152
            if (isset($_FILES["${type}-blob"])) {
153
                $fileName = $_POST["${type}-filename"];
154
                //$file = $_FILES["${type}-blob"]["tmp_name"];
155
                $file = $_FILES["${type}-blob"];
156
                $fileInfo = pathinfo($fileName);
157
158
                $file['name'] = 'rec_'.date('Y-m-d_His').'_'.uniqid().'.'.$fileInfo['extension'];
159
                $file['file'] = $file;
160
161
                $result = DocumentManager::upload_document(
162
                    $file,
163
                    '/audio',
164
                    $file['name'],
165
                    null,
166
                    0,
167
                    'overwrite',
168
                    false,
169
                    false
170
                );
171
172
                if (!empty($result) && is_array($result)) {
173
                    $newDocId = $result['id'];
174
                    $courseId = $result['c_id'];
175
176
                    $lp->set_modified_on();
177
178
                    $lpItem = new learnpathItem($_REQUEST['lp_item_id']);
179
                    $lpItem->add_audio_from_documents($newDocId);
180
                    $data = DocumentManager::get_document_data_by_id($newDocId, $course_info['code']);
181
                    echo $data['document_url'];
182
                    exit;
183
                }
184
            }
185
        }
186
187
        break;
188
    case 'get_forum_thread':
189
        $lpId = isset($_GET['lp']) ? intval($_GET['lp']) : 0;
190
        $lpItemId = isset($_GET['lp_item']) ? intval($_GET['lp_item']) : 0;
191
        $sessionId = api_get_session_id();
192
193
        if (empty($lpId) || empty($lpItemId)) {
194
            echo json_encode([
195
                'error' => true,
196
            ]);
197
198
            break;
199
        }
200
201
        $learningPath = learnpath::getLpFromSession(
202
            api_get_course_id(),
203
            $lpId,
204
            api_get_user_id()
205
        );
206
        $lpItem = $learningPath->getItem($lpItemId);
207
208
        if (empty($lpItem)) {
209
            echo json_encode([
210
                'error' => true,
211
            ]);
212
            break;
213
        }
214
215
        $lpHasForum = $learningPath->lpHasForum();
216
217
        if (!$lpHasForum) {
218
            echo json_encode([
219
                'error' => true,
220
            ]);
221
            break;
222
        }
223
224
        $forum = $learningPath->getForum($sessionId);
225
226
        if (empty($forum)) {
227
            require_once '../../forum/forumfunction.inc.php';
228
            $forumCategory = getForumCategoryByTitle(
229
                get_lang('LearningPaths'),
230
                $courseId,
231
                $sessionId
232
            );
233
234
            if (empty($forumCategory)) {
235
                $forumCategoryId = store_forumcategory(
236
                    [
237
                        'lp_id' => 0,
238
                        'forum_category_title' => get_lang('LearningPaths'),
239
                        'forum_category_comment' => null,
240
                    ],
241
                    [],
242
                    false
243
                );
244
            } else {
245
                $forumCategoryId = $forumCategory['cat_id'];
246
            }
247
248
            $forumId = $learningPath->createForum($forumCategoryId);
249
        } else {
250
            $forumId = $forum['forum_id'];
251
        }
252
253
        $lpItemHasThread = $lpItem->lpItemHasThread($courseId);
254
255
        if (!$lpItemHasThread) {
256
            echo json_encode([
257
                'error' => true,
258
            ]);
259
            break;
260
        }
261
262
        $forumThread = $lpItem->getForumThread($courseId, $sessionId);
263
        if (empty($forumThread)) {
264
            $lpItem->createForumThread($forumId);
265
            $forumThread = $lpItem->getForumThread($courseId, $sessionId);
266
        }
267
268
        $forumThreadId = $forumThread['thread_id'];
269
270
        echo json_encode([
271
            'error' => false,
272
            'forumId' => intval($forum['forum_id']),
273
            'threadId' => intval($forumThreadId),
274
        ]);
275
        break;
276
    case 'update_gamification':
277
        $lp = Session::read('oLP');
278
279
        $jsonGamification = [
280
            'stars' => 0,
281
            'score' => 0,
282
        ];
283
284
        if ($lp) {
285
            $score = $lp->getCalculateScore($sessionId);
286
            $jsonGamification['stars'] = $lp->getCalculateStars($sessionId);
287
            $jsonGamification['score'] = sprintf(get_lang('XPoints'), $score);
288
        }
289
290
        echo json_encode($jsonGamification);
291
        break;
292
    case 'check_item_position':
293
        $lp = Session::read('oLP');
294
        $lpItemId = isset($_GET['lp_item']) ? intval($_GET['lp_item']) : 0;
295
        if ($lp) {
296
            $position = $lp->isFirstOrLastItem($lpItemId);
297
            echo json_encode($position);
298
        }
299
        break;
300
    case 'get_parent_names':
301
        $newItemId = isset($_GET['new_item']) ? intval($_GET['new_item']) : 0;
302
303
        if (!$newItemId) {
304
            break;
305
        }
306
307
        /** @var \learnpath $lp */
308
        $lp = Session::read('oLP');
309
        $parentNames = $lp->getCurrentItemParentNames($newItemId);
310
        $response = '';
311
        foreach ($parentNames as $parentName) {
312
            $response .= '<p class="h5 hidden-xs hidden-md">'.$parentName.'</p>';
313
        }
314
315
        echo $response;
316
        break;
317
    case 'get_item_prerequisites':
318
        /** @var learnpath $lp */
319
        $lp = Session::read('oLP');
320
        $itemId = isset($_GET['item_id']) ? (int) $_GET['item_id'] : 0;
321
        if (empty($lp) || empty($itemId)) {
322
            exit;
323
        }
324
        $result = $lp->prerequisites_match($itemId);
325
        if ($result) {
326
            echo '1';
327
        } else {
328
            if (!empty($lp->error)) {
329
                echo $lp->error;
330
            } else {
331
                echo get_lang('LearnpathPrereqNotCompleted');
332
            }
333
        }
334
        $lp->error = '';
335
        exit;
336
337
        break;
338
    default:
339
        echo '';
340
}
341
exit;
342
343
/**
344
 * Class LpItemOrderList
345
 * Classes to create a special data structure to manipulate LP Items
346
 * used only in this file.
347
 *
348
 * @todo move in a file
349
 * @todo use PSR
350
 */
351
class LpItemOrderList
352
{
353
    public $list = [];
354
355
    public function __construct()
356
    {
357
        $this->list = [];
358
    }
359
360
    /**
361
     * @param array $list
362
     */
363
    public function add($list)
364
    {
365
        $this->list[] = $list;
366
    }
367
368
    /**
369
     * @param int $parentId
370
     *
371
     * @return LpItemOrderList
372
     */
373
    public function getItemWithSameParent($parentId)
374
    {
375
        $list = new LpItemOrderList();
376
        for ($i = 0; $i < count($this->list); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
377
            if ($this->list[$i]->parent_item_id == $parentId) {
378
                $list->add($this->list[$i]);
379
            }
380
        }
381
382
        return $list;
383
    }
384
385
    /**
386
     * @return array
387
     */
388
    public function getListOfParents()
389
    {
390
        $result = [];
391
        foreach ($this->list as $item) {
392
            if (!in_array($item->parent_item_id, $result)) {
393
                $result[] = $item->parent_item_id;
394
            }
395
        }
396
397
        return $result;
398
    }
399
400
    /**
401
     * @param int    $id
402
     * @param int    $value
403
     * @param string $parameter
404
     */
405
    public function setParametersForId($id, $value, $parameter)
406
    {
407
        for ($i = 0; $i < count($this->list); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
408
            if ($this->list[$i]->id == $id) {
409
                $this->list[$i]->$parameter = $value;
410
                break;
411
            }
412
        }
413
    }
414
}
415
416
/**
417
 * Class LpOrderItem.
418
 */
419
class LpOrderItem
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

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

Loading history...
420
{
421
    public $id = 0;
422
    public $parent_item_id = 0;
423
    public $previous_item_id = 0;
424
    public $next_item_id = 0;
425
    public $display_order = 0;
426
427
    /**
428
     * LpOrderItem constructor.
429
     *
430
     * @param int $id
431
     * @param int $parentId
432
     */
433
    public function __construct($id = 0, $parentId = 0)
434
    {
435
        $this->id = $id;
436
        $this->parent_item_id = $parentId;
437
    }
438
}
439