Passed
Push — 1.11.x ( 47915c...7101db )
by Yannick
09:38
created

Cc13Resource   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 201
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 134
c 1
b 0
f 0
dl 0
loc 201
rs 9.76
wmc 33

4 Methods

Rating   Name   Duplication   Size   Complexity  
A generateData() 0 10 3
F getResourceData() 0 124 25
A storeDocuments() 0 47 3
A storeLinks() 0 12 2
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
class Cc13Resource extends Cc13Entities
5
{
6
    public function generateData($resource_type)
7
    {
8
        $data = [];
9
        if (!empty(Cc1p3Convert::$instances['instances'][$resource_type])) {
10
            foreach (Cc1p3Convert::$instances['instances'][$resource_type] as $instance) {
11
                $data[] = $this->getResourceData($instance);
12
            }
13
        }
14
15
        return $data;
16
    }
17
18
    public function storeLinks($links)
19
    {
20
        foreach ($links as $link) {
21
            $_POST['title'] = $link[1];
22
            $_POST['url'] = $link[4];
23
            $_POST['description'] = '';
24
            $_POST['category_id'] = 0;
25
            $_POST['target'] = '_blank';
26
            Link::addlinkcategory('link');
27
        }
28
29
        return true;
30
    }
31
32
    public function storeDocuments($documents, $path)
33
    {
34
        $courseInfo = api_get_course_info();
35
        $sessionId = api_get_session_id();
36
        $groupId = api_get_group_id();
37
        $documentPath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
38
39
        create_unexisting_directory(
40
            $courseInfo,
41
            api_get_user_id(),
42
            $sessionId,
43
            $groupId,
44
            null,
45
            $documentPath,
46
            '/cc1p3',
47
            'Common Cartridge folder',
48
            0
49
        );
50
51
        foreach ($documents as $document) {
52
            if ($document[2] == 'file') {
53
                $filepath = $path.DIRECTORY_SEPARATOR.$document[4];
54
                $files = [];
55
                $files['file']['name'] = $document[1];
56
                $files['file']['tmp_name'] = $filepath;
57
                $files['file']['type'] = mime_content_type($filepath);
58
                $files['file']['error'] = 0;
59
                $files['file']['size'] = filesize($filepath);
60
                $files['file']['from_file'] = true;
61
                $files['file']['move_file'] = true;
62
                $_POST['language'] = $courseInfo['language'];
63
                $_POST['cc_import'] = true;
64
65
                DocumentManager::upload_document(
66
                    $files,
67
                    '/cc1p3',
68
                    $document[1],
69
                    '',
70
                    null,
71
                    null,
72
                    true,
73
                    true
74
                );
75
            }
76
        }
77
78
        return true;
79
    }
80
81
    public function getResourceData($instance)
82
    {
83
        //var_dump($instance);
84
85
        $xpath = Cc1p3Convert::newxPath(Cc1p3Convert::$manifest, Cc1p3Convert::$namespaces);
86
        $link = '';
87
88
        if ($instance['common_cartriedge_type'] == Cc1p3Convert::CC_TYPE_WEBCONTENT || $instance['common_cartriedge_type'] == Cc1p3Convert::CC_TYPE_ASSOCIATED_CONTENT) {
89
            $resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="'.$instance['resource_indentifier'].'"]/@href');
90
            if ($resource->length > 0) {
91
                $resource = !empty($resource->item(0)->nodeValue) ? $resource->item(0)->nodeValue : '';
92
            } else {
93
                $resource = '';
94
            }
95
96
            if (empty($resource)) {
97
                unset($resource);
98
                $resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="'.$instance['resource_indentifier'].'"]/imscc:file/@href');
99
                if ($resource->length > 0) {
100
                    $resource = !empty($resource->item(0)->nodeValue) ? $resource->item(0)->nodeValue : '';
101
                } else {
102
                    $resource = '';
103
                }
104
            }
105
            if (!empty($resource)) {
106
                $link = $resource;
107
            }
108
        }
109
110
        if ($instance['common_cartriedge_type'] == Cc1p3Convert::CC_TYPE_WEBLINK) {
111
            $external_resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="'.$instance['resource_indentifier'].'"]/imscc:file/@href')->item(0)->nodeValue;
112
113
            if ($external_resource) {
114
                $resource = $this->loadXmlResource(Cc1p3Convert::$pathToManifestFolder.DIRECTORY_SEPARATOR.$external_resource);
115
116
                if (!empty($resource)) {
117
                    $xpath = Cc1p3Convert::newxPath($resource, Cc1p3Convert::$resourcens);
118
                    $resource = $xpath->query('/wl:webLink/wl:url/@href');
119
                    if ($resource->length > 0) {
120
                        $rawlink = $resource->item(0)->nodeValue;
121
                        if (!validateUrlSyntax($rawlink, 's+')) {
122
                            $changed = rawurldecode($rawlink);
123
                            if (validateUrlSyntax($changed, 's+')) {
124
                                $link = $changed;
125
                            } else {
126
                                $link = 'http://invalidurldetected/';
127
                            }
128
                        } else {
129
                            $link = htmlspecialchars(trim($rawlink), ENT_COMPAT, 'UTF-8', false);
130
                        }
131
                    }
132
                }
133
            }
134
        }
135
136
        $mod_type = 'file';
137
        $mod_options = 'objectframe';
138
        $mod_reference = $link;
139
        //detected if we are dealing with html file
140
        if (!empty($link) && ($instance['common_cartriedge_type'] == Cc1p3Convert::CC_TYPE_WEBCONTENT)) {
141
            $ext = strtolower(pathinfo($link, PATHINFO_EXTENSION));
142
            if (in_array($ext, ['html', 'htm', 'xhtml'])) {
143
                $mod_type = 'html';
144
                //extract the content of the file
145
                $rootpath = realpath(Cc1p3Convert::$pathToManifestFolder);
146
                $htmlpath = realpath($rootpath.DIRECTORY_SEPARATOR.$link);
147
                $dirpath = dirname($htmlpath);
148
                if (file_exists($htmlpath)) {
149
                    $fcontent = file_get_contents($htmlpath);
150
                    $mod_alltext = $this->prepareContent($fcontent);
151
                    $mod_reference = '';
152
                    $mod_options = '';
153
                    /**
154
                     * try to handle embedded resources
155
                     * images, linked static resources, applets, videos.
156
                     */
157
                    $doc = new DOMDocument();
158
                    $cdir = getcwd();
159
                    chdir($dirpath);
160
                    try {
161
                        $doc->loadHTML($mod_alltext);
162
                        $xpath = new DOMXPath($doc);
163
                        $attributes = ['href', 'src', 'background', 'archive', 'code'];
164
                        $qtemplate = "//*[@##][not(contains(@##,'://'))]/@##";
165
                        $query = '';
166
                        foreach ($attributes as $attrname) {
167
                            if (!empty($query)) {
168
                                $query .= " | ";
169
                            }
170
                            $query .= str_replace('##', $attrname, $qtemplate);
171
                        }
172
                        $list = $xpath->query($query);
173
                        $searches = [];
174
                        $replaces = [];
175
                        foreach ($list as $resrc) {
176
                            $rpath = $resrc->nodeValue;
177
                            $rtp = realpath($rpath);
178
                            if (($rtp !== false) && is_file($rtp)) {
179
                                //file is there - we are in business
180
                                $strip = str_replace("\\", "/", str_ireplace($rootpath, '', $rtp));
181
                                $encoded_file = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $strip);
182
                                $searches[] = $resrc->nodeValue;
183
                                $replaces[] = $encoded_file;
184
                            }
185
                        }
186
                        $mod_alltext = str_replace($searches, $replaces, $mod_alltext);
187
                    } catch (Exception $e) {
188
                        //silence the complaints
189
                    }
190
                    chdir($cdir);
191
                    $mod_alltext = self::safexml($mod_alltext);
192
                }
193
            }
194
        }
195
196
        $values = [$instance['instance'],
197
                                self::safexml($instance['title']),
198
                                $mod_type,
199
                                $mod_alltext,
200
                                $mod_reference,
201
                                $mod_options,
202
                ];
203
204
        return $values;
205
    }
206
}
207