Passed
Push — master ( 447a4c...2f567c )
by Julito
09:40
created

generateLPFinalItemTemplateCertificateLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 1
dl 0
loc 18
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Print a learning path finish page with details.
6
 *
7
 * @author Jose Loguercio <[email protected]>
8
 *
9
 * @package chamilo.learnpath
10
 */
11
$_in_course = true;
12
13
require_once __DIR__.'/../inc/global.inc.php';
14
15
$current_course_tool = TOOL_GRADEBOOK;
16
17
// Make sure no anonymous user gets here without permission
18
api_protect_course_script(true);
19
20
// Get environment variables
21
$courseCode = api_get_course_id();
22
$courseId = api_get_course_int_id();
23
$userId = api_get_user_id();
24
$sessionId = api_get_session_id();
25
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
26
$lpId = isset($_GET['lp_id']) ? intval($_GET['lp_id']) : 0;
27
28
// This page can only be shown from inside a learning path
29
if (!$id && !$lpId) {
30
    Display::return_message(get_lang('FileNotFound'), 'warning');
31
    exit;
32
}
33
34
// Certificate and Skills Premium with Service check
35
$plugin = BuyCoursesPlugin::create();
36
$checker = $plugin->isEnabled() && $plugin->get('include_services');
37
38
if ($checker) {
39
    $userServiceSale = $plugin->getServiceSale(
40
        null,
41
        $userId,
42
        BuyCoursesPlugin::SERVICE_STATUS_COMPLETED,
43
        BuyCoursesPlugin::SERVICE_TYPE_LP_FINAL_ITEM,
44
        $lpId
45
    );
46
47
    if (empty($userServiceSale)) {
48
        // Instance a new template : No page tittle, No header, No footer
49
        $tpl = new Template(null, false, false);
50
        $url = api_get_path(WEB_PLUGIN_PATH).'buycourses/src/service_catalog.php';
51
        $content = sprintf(
52
            Display::return_message(
53
                get_lang('IfYouWantToGetTheCertificateAndOrSkillsAsociatedToThisCourseYouNeedToBuyTheCertificateServiceYouCanGoToServiceCatalogClickingHere'),
54
                'normal',
55
                false
56
            ),
57
            '<a href="'.$url.'">'.$url.'</a>'
58
        );
59
        $tpl->assign('content', $content);
60
        $tpl->display_blank_template();
61
        exit;
62
    }
63
}
64
65
// Initialize variables required for the template
66
$downloadCertificateLink = '';
67
$viewCertificateLink = '';
68
$badgeLink = '';
69
$finalItemTemplate = '';
70
71
// Check prerequisites and total completion of the learning path
72
$lp = new Learnpath($courseCode, $lpId, $userId);
73
$count = $lp->getTotalItemsCountWithoutDirs();
74
$completed = $lp->get_complete_items_count(true);
75
$currentItemId = $lp->get_current_item_id();
76
$currentItem = $lp->items[$currentItemId];
77
$currentItemStatus = $currentItem->get_status();
78
$accessGranted = false;
79
80
if (($count - $completed == 0) ||
81
    ($count - $completed == 1 && ($currentItemStatus == 'incomplete') || ($currentItemStatus == 'not attempted'))
82
) {
83
    if ($lp->prerequisites_match($currentItemId)) {
84
        $accessGranted = true;
85
    }
86
}
87
// Update the progress in DB from the items completed
88
$lp->save_last();
89
90
// unset the (heavy) lp object to free memory - we don't need it anymore
91
unset($lp);
92
unset($currentItem);
93
94
// If for some reason we consider the requirements haven't been completed yet,
95
// show a prerequisites warning
96
if ($accessGranted == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
97
    echo Display::return_message(
98
        get_lang('LearnpathPrereqNotCompleted'),
99
        'warning'
100
    );
101
    $finalItemTemplate = '';
102
} else {
103
    $catLoad = Category::load(
104
        null,
105
        null,
106
        $courseCode,
107
        null,
108
        null,
109
        $sessionId,
110
        'ORDER By id'
111
    );
112
    // If not gradebook has been defined
113
    if (empty($catLoad)) {
114
        $finalItemTemplate = generateLPFinalItemTemplate(
115
            $id,
116
            $courseCode,
117
            $sessionId,
118
            $downloadCertificateLink,
119
            $badgeLink
120
        );
121
    } else {
122
        // A gradebook was found, proceed...
123
        /** @var Category $category */
124
        $category = $catLoad[0];
125
        $categoryId = $category->get_id();
126
        $link = LinkFactory::load(
127
            null,
128
            null,
129
            $lpId,
130
            null,
131
            $courseCode,
132
            $categoryId
133
        );
134
135
        if ($link) {
136
            $cat = new Category();
137
            $catCourseCode = CourseManager::get_course_by_category($categoryId);
138
            $show_message = $cat->show_message_resource_delete($catCourseCode);
139
140
            if (false === $show_message && !api_is_allowed_to_edit() && !api_is_excluded_user_type()) {
141
                $certificate = Category::generateUserCertificate(
142
                    $categoryId,
143
                    $userId
144
                );
145
146
                if (!empty($certificate['pdf_url']) ||
147
                    !empty($certificate['badge_link'])
148
                ) {
149
                    if (is_array($certificate)) {
150
                        $downloadCertificateLink = Category::getDownloadCertificateBlock($certificate);
151
                    }
152
153
                    if (is_array($certificate) &&
154
                        isset($certificate['badge_link'])
155
                    ) {
156
                        $courseId = api_get_course_int_id();
157
                        $badgeLink = generateLPFinalItemTemplateBadgeLinks(
158
                            $userId,
159
                            $courseId,
160
                            $sessionId
161
                        );
162
                    }
163
                }
164
165
                $currentScore = Category::getCurrentScore(
166
                    $userId,
167
                    $category,
168
                    true
169
                );
170
                Category::registerCurrentScore(
171
                    $currentScore,
172
                    $userId,
173
                    $categoryId
174
                );
175
            }
176
        }
177
178
        $finalItemTemplate = generateLPFinalItemTemplate(
179
            $id,
180
            $courseCode,
181
            $sessionId,
182
            $downloadCertificateLink,
183
            $badgeLink
184
        );
185
186
        if (!$finalItemTemplate) {
187
            echo Display::return_message(get_lang('FileNotFound'), 'warning');
188
        }
189
    }
190
}
191
192
// Instance a new template : No page tittle, No header, No footer
193
$tpl = new Template(null, false, false);
194
$tpl->assign('content', $finalItemTemplate);
195
$tpl->display_blank_template();
196
197
// A few functions used only here...
198
199
/**
200
 * Return a HTML string to show as final document in learning path.
201
 *
202
 * @param int    $lpItemId
203
 * @param string $courseCode
204
 * @param int    $sessionId
205
 * @param string $downloadCertificateLink
206
 * @param string $badgeLink
207
 *
208
 * @return mixed|string
209
 */
210
function generateLPFinalItemTemplate(
211
    $lpItemId,
212
    $courseCode,
213
    $sessionId = 0,
214
    $downloadCertificateLink = '',
215
    $badgeLink = ''
216
) {
217
    $documentInfo = DocumentManager::get_document_data_by_id(
218
        $lpItemId,
219
        $courseCode,
220
        true,
221
        $sessionId
222
    );
223
224
    $finalItemTemplate = file_get_contents($documentInfo['absolute_path']);
225
    $finalItemTemplate = str_replace('((certificate))', $downloadCertificateLink, $finalItemTemplate);
226
    $finalItemTemplate = str_replace('((skill))', $badgeLink, $finalItemTemplate);
227
228
    return $finalItemTemplate;
229
}
230
231
/**
232
 * Return HTML string with badges list.
233
 *
234
 * @param int $userId
235
 * @param int $courseId
236
 * @param int $sessionId
237
 *
238
 * @return string HTML string for badges
239
 */
240
function generateLPFinalItemTemplateBadgeLinks($userId, $courseId, $sessionId = 0)
241
{
242
    $em = Database::getManager();
243
    $skillRelUser = new SkillRelUser();
244
    $userSkills = $skillRelUser->getUserSkills($userId, $courseId, $sessionId);
245
    $skillList = '';
246
    $badgeLink = '';
247
248
    if ($userSkills) {
249
        foreach ($userSkills as $userSkill) {
250
            $skill = $em->find('ChamiloCoreBundle:Skill', $userSkill['skill_id']);
251
            $skillList .= "
252
                <div class='row'>
253
                    <div class='col-md-2 col-xs-4'>
254
                        <div class='thumbnail'>
255
                          <img class='skill-badge-img' src='".Skill::getWebIconPath($skill)."' >
256
                        </div>
257
                    </div>
258
                    <div class='col-md-8 col-xs-8'>
259
                        <h5><b>".$skill->getName()."</b></h5>
260
                        ".$skill->getDescription()."
261
                    </div>
262
                    <div class='col-md-2 col-xs-12'>
263
                        <h5><b>".get_lang('ShareWithYourFriends')."</b></h5>
264
                        <a href='http://www.facebook.com/sharer.php?u=".api_get_path(WEB_PATH)."badge/".$skill->getId()."/user/".$userId."' target='_new'>
265
                            <em class='fa fa-facebook-square fa-3x text-info' aria-hidden='true'></em>
266
                        </a>
267
                        <a href='https://twitter.com/home?status=".sprintf(get_lang('IHaveObtainedSkillXOnY'), '"'.$skill->getName().'"', api_get_setting('siteName')).' - '.api_get_path(WEB_PATH).'badge/'.$skill->getId().'/user/'.$userId."' target='_new'>
268
                            <em class='fa fa-twitter-square fa-3x text-light' aria-hidden='true'></em>
269
                        </a>
270
                    </div>
271
                </div>
272
            ";
273
        }
274
        $badgeLink .= "
275
            <div class='panel panel-default'>
276
                <div class='panel-body'>
277
                    <h3 class='text-center'>".get_lang('AdditionallyYouHaveObtainedTheFollowingSkills')."</h3>
278
                    $skillList
279
                </div>
280
            </div>
281
        ";
282
    }
283
284
    return $badgeLink;
285
}
286