Passed
Pull Request — preprodparkur (#4117)
by Angel Fernando Quiroz
10:58
created

save_ticket()   F

Complexity

Conditions 11
Paths 1024

Size

Total Lines 43
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 37
nc 1024
nop 0
dl 0
loc 43
rs 3.15
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * @package chamilo.ticket
6
 */
7
require_once __DIR__.'/../inc/global.inc.php';
8
9
if (!api_is_platform_admin() && api_get_setting('ticket_allow_student_add') !== 'true') {
10
    header('Location:'.api_get_path(WEB_CODE_PATH).'ticket/tickets.php');
11
    exit;
12
}
13
14
api_block_anonymous_users();
15
$courseId = api_get_course_int_id();
16
$exerciseId = (isset($_GET['exerciseId']) && !empty($_GET['exerciseId'])) ? (int) $_GET['exerciseId'] : 0;
17
$lpId = (isset($_GET['lpId']) && !empty($_GET['lpId'])) ? (int) $_GET['lpId'] : 0;
18
19
$htmlHeadXtra[] = '<script>
20
function updateCourseList(sessionId) {
21
    var $selectCourse = $("select#course_id");
22
    $selectCourse.empty();
23
24
    $.get("'.api_get_path(WEB_AJAX_PATH).'session.ajax.php", {
25
        a: "get_courses_inside_session",
26
        session_id : sessionId
27
    }, function (courseList) {
28
        $("<option>", {
29
            value: 0,
30
            text: "'.get_lang('Select').'"
31
        }).appendTo($selectCourse);
32
33
        if (courseList.length > 0) {
34
            $.each(courseList, function (index, course) {
35
                $("<option>", {
36
                    value: course.id,
37
                    text: course.name
38
                }).appendTo($selectCourse);
39
            });
40
41
            $selectCourse.find("option[value=\''.$courseId.'\']").attr("selected",true);
42
            $selectCourse.selectpicker("refresh");
43
        }
44
    }, "json");
45
}
46
47
function updateExerciseList(courseId, sessionId) {
48
    var $selectExercise = $("select#exercise_id");
49
    $selectExercise.empty();
50
51
    $.get("'.api_get_path(WEB_AJAX_PATH).'exercise.ajax.php", {
52
        a: "get_exercise_by_course",
53
        course_id: courseId,
54
        session_id : sessionId
55
    }, function (exerciseList) {
56
        $("<option>", {
57
            value: 0,
58
            text: "' . get_lang('Select') . '"
59
        }).appendTo($selectExercise);
60
61
        if (exerciseList.length > 0) {
62
            $.each(exerciseList, function (index, exercise) {
63
                $("<option>", {
64
                    value: exercise.id,
65
                    text: exercise.text
66
                }).appendTo($selectExercise);
67
            });
68
69
            $selectExercise.find("option[value=\'' . $exerciseId . '\']").attr("selected",true);
70
        }
71
72
        $selectExercise.selectpicker("refresh");
73
    }, "json");
74
}
75
76
function updateLpList(courseId) {
77
    var $selectLp = $("select#lp_id");
78
    $selectLp.empty();
79
80
    $.get("'.api_get_path(WEB_AJAX_PATH).'lp.ajax.php", {
81
        a: "get_lp_list_by_course",
82
        course_id: courseId
83
    }, function (lpList) {
84
        $("<option>", {
85
            value: 0,
86
            text: "' . get_lang('Select') . '"
87
        }).appendTo($selectLp);
88
89
        if (lpList.length > 0) {
90
            $.each(lpList, function (index, lp) {
91
                $("<option>", {
92
                    value: lp.id,
93
                    text: lp.text
94
                }).appendTo($selectLp);
95
            });
96
97
            $selectLp.find("option[value=\'' . $lpId . '\']").attr("selected",true);
98
        }
99
100
        $selectLp.selectpicker("refresh");
101
    }, "json");
102
}
103
104
$(document).ready(function() {
105
    var $selectSession = $("select#session_id");
106
    var $selectCourse = $("select#course_id");
107
108
    $selectSession.on("change", function () {
109
        var sessionId = parseInt(this.value, 10);
110
111
        updateCourseList(sessionId);
112
        updateExerciseList(0, sessionId);
113
        updateLpList(0);
114
    });
115
116
    $selectCourse.on("change", function () {
117
        var sessionId = $selectSession.val();
118
        var courseId = parseInt(this.value, 10);
119
120
        updateExerciseList(courseId, sessionId);
121
        updateLpList(courseId);
122
    });
123
124
    var sessionId = $selectSession.val();
125
    var courseId = $selectCourse.val() ? $selectCourse.val() : '.$courseId.';
126
127
    updateCourseList(sessionId);
128
    updateExerciseList(courseId, sessionId);
129
    updateLpList(courseId);
130
});
131
132
var counter_image = 1;
133
134
function remove_image_form(element_id) {
135
    $("#" + element_id).remove();
136
    counter_image = counter_image - 1;
137
    $("#link-more-attach").css("display", "block");
138
}
139
140
function add_image_form() {
141
    // Multiple filepaths for image form
142
    var filepaths = $("#filepaths");
143
    var new_elem, input_file, link_remove, img_remove, new_filepath_id;
144
145
    if ($("#filepath_"+counter_image)) {
146
        counter_image = counter_image + 1;
147
    }  else {
148
        counter_image = counter_image;
149
    }
150
151
    new_elem = "filepath_"+counter_image;
152
153
    $("<div/>", {
154
        id: new_elem,
155
        class: "controls"
156
    }).appendTo(filepaths);
157
158
    input_file = $("<input/>", {
159
        type: "file",
160
        name: "attach_" + counter_image,
161
        size: 20
162
    });
163
164
    link_remove = $("<a/>", {
165
        onclick: "remove_image_form(\'" + new_elem + "\')",
166
        style: "cursor: pointer"
167
    });
168
169
    img_remove = $("<img/>", {
170
        src: "'.Display::returnIconPath('delete.png').'"
171
    });
172
173
    new_filepath_id = $("#filepath_" + counter_image);
174
    new_filepath_id.append(input_file, link_remove.append(img_remove));
175
176
    if (counter_image === 6) {
177
        var link_attach = $("#link-more-attach");
178
        if (link_attach) {
179
            $(link_attach).css("display", "none");
180
        }
181
    }
182
}
183
</script>';
184
185
$projectId = isset($_GET['project_id']) ? (int) $_GET['project_id'] : 0;
186
187
$types = TicketManager::get_all_tickets_categories($projectId, 'category.name ASC');
188
$htmlHeadXtra[] = '<script>
189
    var projects = '.js_array($types, 'projects', 'project_id').'
190
    var course_required = '.js_array($types, 'course_required', 'course_required').'
191
    var other_area = '.js_array($types, 'other_area', 'other_area').'
192
    var email = '.js_array($types, 'email', 'email').
193
'</script>';
194
195
/**
196
 * @param $s
197
 *
198
 * @return string
199
 */
200
function js_str($s)
201
{
202
    return '"'.addcslashes($s, "\0..\37\"\\").'"';
203
}
204
205
/**
206
 * @param $array
207
 * @param $name
208
 * @param $key
209
 *
210
 * @return string
211
 */
212
function js_array($array, $name, $key)
213
{
214
    $return = "new Array(); ";
215
    foreach ($array as $value) {
216
        $return .= $name."['".$value['category_id']."'] ='".$value[$key]."'; ";
217
    }
218
219
    return $return;
220
}
221
222
function save_ticket()
223
{
224
    $content = $_POST['content'];
225
    if (!empty($_POST['phone'])) {
226
        $content .= '<p style="color:red">&nbsp;'.get_lang('Phone').': '.Security::remove_XSS($_POST['phone']).'</p>';
227
    }
228
    $course_id = isset($_POST['course_id']) ? (int) $_POST['course_id'] : '';
229
    $sessionId = isset($_POST['session_id']) ? (int) $_POST['session_id'] : '';
230
    $category_id = isset($_POST['category_id']) ? (int) $_POST['category_id'] : '';
231
    $exercise_id = isset($_POST['exercise_id']) ? (int) $_POST['exercise_id'] : null;
232
    $lp_id = isset($_POST['lp_id']) ? (int) $_POST['lp_id'] : null;
233
234
    $project_id = (int) $_POST['project_id'];
235
    $subject = $_POST['subject'];
236
    $other_area = (int) $_POST['other_area'];
237
    $personal_email = $_POST['personal_email'];
238
    $source = (int) $_POST['source_id'];
239
    $user_id = isset($_POST['user_id']) ? (int) $_POST['user_id'] : 0;
240
    $priority = isset($_POST['priority_id']) ? (int) $_POST['priority_id'] : '';
241
    $status = isset($_POST['status_id']) ? (int) $_POST['status_id'] : '';
242
    $file_attachments = $_FILES;
243
244
    if (TicketManager::add(
245
        $category_id,
246
        $course_id,
247
        $sessionId,
248
        $project_id,
249
        $other_area,
250
        $subject,
251
        $content,
252
        $personal_email,
253
        $file_attachments,
254
        $source,
255
        $priority,
256
        $status,
257
        $user_id,
258
        $exercise_id,
259
        $lp_id
260
    )) {
261
        header('Location:'.api_get_path(WEB_CODE_PATH).'ticket/tickets.php');
262
        exit;
263
    } else {
264
        Display::addFlash(Display::return_message(get_lang('ThereWasAnErrorRegisteringTheTicket')));
265
    }
266
}
267
268
$interbreadcrumb[] = [
269
    'url' => api_get_path(WEB_CODE_PATH).'ticket/tickets.php',
270
    'name' => get_lang('MyTickets'),
271
];
272
273
$userId = api_get_user_id();
274
275
// Category List
276
$categoryList = [];
277
foreach ($types as $type) {
278
    $categoryList[$type['category_id']] = $type['name'].': '.$type['description'];
279
}
280
281
// Status List
282
$statusAttributes = [
283
    'style' => 'display: none;',
284
    'id' => 'status_id',
285
    'for' => 'status_id',
286
];
287
288
$statusList = TicketManager::getStatusList();
289
290
// Source List
291
$sourceList = [];
292
$sourceAttributes = [
293
    'style' => 'display: none;',
294
    'id' => 'source_id',
295
    'for' => 'source_id',
296
];
297
$sourceList[TicketManager::SOURCE_PLATFORM] = get_lang('SrcPlatform');
298
if (api_is_platform_admin()) {
299
    $sourceAttributes = [
300
        'id' => 'source_id',
301
        'for' => 'source_id',
302
    ];
303
    $sourceList[TicketManager::SOURCE_EMAIL] = get_lang('SrcEmail');
304
    $sourceList[TicketManager::SOURCE_PHONE] = get_lang('SrcPhone');
305
    $sourceList[TicketManager::SOURCE_PRESENTIAL] = get_lang('SrcPresential');
306
}
307
308
// Priority List
309
$priorityList = TicketManager::getPriorityList();
310
311
$projectId = isset($_GET['project_id']) ? (int) $_GET['project_id'] : 0;
312
313
$form = new FormValidator(
314
    'send_ticket',
315
    'POST',
316
    api_get_self().'?project_id='.$projectId,
317
    '',
318
    [
319
        'enctype' => 'multipart/form-data',
320
    ]
321
);
322
323
$form->addElement(
324
    'hidden',
325
    'user_id_request',
326
    '',
327
    [
328
        'id' => 'user_id_request',
329
    ]
330
);
331
332
$form->addElement(
333
    'hidden',
334
    'project_id',
335
    $projectId
336
);
337
338
$form->addElement(
339
    'hidden',
340
    'other_area',
341
    '',
342
    [
343
        'id' => 'other_area',
344
    ]
345
);
346
347
$form->addElement(
348
    'hidden',
349
    'email',
350
    '',
351
    [
352
        'id' => 'email',
353
    ]
354
);
355
356
$form->addSelect(
357
    'category_id',
358
    get_lang('Category'),
359
    $categoryList,
360
    [
361
        'id' => 'category_id',
362
        'for' => 'category_id',
363
        'style' => 'width: 562px;',
364
    ]
365
);
366
367
$form->addElement(
368
    'text',
369
    'subject',
370
    get_lang('Subject'),
371
    [
372
        'id' => 'subject',
373
    ]
374
);
375
376
$form->addHtmlEditor(
377
    'content',
378
    get_lang('Message'),
379
    false,
380
    false,
381
    [
382
        'ToolbarSet' => 'Profile',
383
        'Height' => '250',
384
    ]
385
);
386
387
if (api_is_platform_admin()) {
388
    $form->addSelectAjax(
389
        'user_id',
390
        get_lang('Assign'),
391
        null,
392
        ['url' => api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_like']
393
    );
394
}
395
396
$form->addElement(
397
    'text',
398
    'personal_email',
399
    get_lang('PersonalEmail'),
400
    [
401
        'id' => 'personal_email',
402
    ]
403
);
404
405
$form->addLabel(
406
    '',
407
    Display::div(
408
        '',
409
        [
410
            'id' => 'user_request',
411
        ]
412
    )
413
);
414
415
$form->addElement(
416
    'select',
417
    'status_id',
418
    get_lang('Status'),
419
    $statusList,
420
    $statusAttributes
421
);
422
423
$form->addElement(
424
    'select',
425
    'priority_id',
426
    get_lang('Priority'),
427
    $priorityList,
428
    [
429
        'id' => 'priority_id',
430
        'for' => 'priority_id',
431
    ]
432
);
433
434
$form->addElement(
435
    'select',
436
    'source_id',
437
    get_lang('Source'),
438
    $sourceList,
439
    $sourceAttributes
440
);
441
442
$form->addElement(
443
    'text',
444
    'phone',
445
    get_lang('Phone').' ('.get_lang('Optional').')',
446
    [
447
        'id' => 'phone',
448
    ]
449
);
450
451
$sessionList = SessionManager::get_sessions_by_user($userId);
452
453
if (api_is_platform_admin() || !empty($sessionList)) {
454
    $sessionListToSelect = [get_lang('Select')];
455
    // Course List
456
    foreach ($sessionList as $sessionInfo) {
457
        $sessionListToSelect[$sessionInfo['session_id']] = $sessionInfo['session_name'];
458
    }
459
460
    $form->addSelect('session_id', get_lang('Session'), $sessionListToSelect, ['id' => 'session_id']);
461
} else {
462
    $form->addHidden('session_id', 0);
463
}
464
465
$form->addSelect('course_id', get_lang('Course'), [], ['id' => 'course_id']);
466
467
if (api_get_configuration_value('ticket_lp_quiz_info_add')) {
468
    $form->addSelect('exercise_id', get_lang('Exercise'), [], ['id' => 'exercise_id']);
469
470
    $form->addSelect('lp_id', get_lang('LearningPath'), [], ['id' => 'lp_id']);
471
}
472
473
$courseInfo = api_get_course_info();
474
$params = [];
475
476
if (!empty($courseInfo)) {
477
    $params = [
478
        'course_id' => $courseInfo['real_id'],
479
    ];
480
481
    $sessionInfo = api_get_session_info(api_get_session_id());
482
483
    if (!empty($sessionInfo)) {
484
        $params['session_id'] = $sessionInfo['id'];
485
    }
486
487
    if (api_get_configuration_value('ticket_lp_quiz_info_add')) {
488
        if ($exerciseId !== '') {
489
            $params['exercise_id'] = $exerciseId;
490
        }
491
492
        if ($lpId !== '') {
493
            $params['lp_id'] = $lpId;
494
        }
495
    }
496
}
497
498
$form->setDefaults($params);
499
500
$form->addElement('file', 'attach_1', get_lang('FilesAttachment'));
501
$form->addLabel('', '<span id="filepaths"><div id="filepath_1"></div></span>');
502
503
$form->addLabel(
504
    '',
505
    '<span id="link-more-attach">
506
         <span class="btn btn-success" onclick="return add_image_form()">'.get_lang('AddOneMoreFile').'</span>
507
         </span>
508
         ('.sprintf(get_lang('MaximunFileSizeX'), format_file_size(api_get_setting('message_max_upload_filesize'))).')
509
    '
510
);
511
512
$form->addElement('html', '<br/>');
513
$form->addElement(
514
    'button',
515
    'compose',
516
    get_lang('SendMessage'),
517
    null,
518
    null,
519
    null,
520
    'btn btn-primary',
521
    [
522
        'id' => 'btnsubmit',
523
    ]
524
);
525
526
$form->addRule('content', get_lang('ThisFieldIsRequired'), 'required');
527
$form->addRule('category_id', get_lang('ThisFieldIsRequired'), 'required');
528
$form->addRule('subject', get_lang('ThisFieldIsRequired'), 'required');
529
530
if ($form->validate()) {
531
    save_ticket();
532
}
533
534
Display::display_header(get_lang('ComposeMessage'));
535
536
echo '<div class="actions">';
537
echo Display::url(
538
    Display::return_icon('back.png', get_lang('Tickets'), [], ICON_SIZE_MEDIUM),
539
    api_get_path(WEB_CODE_PATH).'ticket/tickets.php'
540
);
541
echo '</div>';
542
543
$form->display();
544
Display::display_footer();
545