Cc13Resource::getResourceData()   F
last analyzed

Complexity

Conditions 23
Paths 1365

Size

Total Lines 124
Code Lines 82

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 82
dl 0
loc 124
rs 0
c 4
b 0
f 0
cc 23
nc 1365
nop 1

How to fix   Long Method    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
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['directory'].'/document';
38
39
        foreach ($documents as $document) {
40
            if ($document[2] == 'file') {
41
                $filepath = $path.DIRECTORY_SEPARATOR.$document[4];
42
                $files = [];
43
                $files['file']['name'] = $document[1];
44
                $files['file']['tmp_name'] = $filepath;
45
                $files['file']['type'] = mime_content_type($filepath);
46
                $files['file']['error'] = 0;
47
                $files['file']['size'] = filesize($filepath);
48
                $files['file']['from_file'] = true;
49
                $files['file']['move_file'] = true;
50
                $_POST['language'] = $courseInfo['language'];
51
                $_POST['cc_import'] = true;
52
53
                $destDir = dirname($document[4]);
54
                // Create the subdirectory if necessary
55
                create_unexisting_directory(
56
                    $courseInfo,
57
                    api_get_user_id(),
58
                    $sessionId,
59
                    $groupId,
60
                    null,
61
                    $documentPath,
62
                    '/commoncartridge/'.$destDir,
63
                    $destDir,
64
                    1
65
                );
66
                DocumentManager::upload_document(
67
                    $files,
68
                    '/commoncartridge/'.$destDir,
69
                    $document[1],
70
                    '',
71
                    null,
72
                    null,
73
                    true,
74
                    true
75
                );
76
            }
77
        }
78
79
        return true;
80
    }
81
82
    public function getResourceData($instance)
83
    {
84
        //var_dump($instance);
85
86
        $xpath = Cc1p3Convert::newxPath(Cc1p3Convert::$manifest, Cc1p3Convert::$namespaces);
87
        $link = '';
88
89
        if ($instance['common_cartridge_type'] == Cc1p3Convert::CC_TYPE_WEBCONTENT || $instance['common_cartridge_type'] == Cc1p3Convert::CC_TYPE_ASSOCIATED_CONTENT) {
90
            $resource = $xpath->query('/imscc:manifest/imscc:resources/imscc:resource[@identifier="'.$instance['resource_identifier'].'"]/@href');
91
            if ($resource->length > 0) {
92
                $resource = !empty($resource->item(0)->nodeValue) ? $resource->item(0)->nodeValue : '';
93
            } else {
94
                $resource = '';
95
            }
96
97
            if (empty($resource)) {
98
                unset($resource);
99
                // src has been set in CcBase::createInstances() based on the contents of <file href="...">
100
                $resource = $instance['src'];
101
            }
102
            if (!empty($resource)) {
103
                $link = $resource;
104
            }
105
        }
106
107
        if ($instance['common_cartridge_type'] == Cc1p3Convert::CC_TYPE_WEBLINK) {
108
            // src has been set in CcBase::createInstances() based on the contents of <file href="...">
109
            $external_resource = $instance['src'];
110
111
            if ($external_resource) {
112
                $resource = $this->loadXmlResource(Cc1p3Convert::$pathToManifestFolder.DIRECTORY_SEPARATOR.$external_resource);
113
114
                if (!empty($resource)) {
115
                    $xpath = Cc1p3Convert::newxPath($resource, Cc1p3Convert::$resourcens);
116
                    $resource = $xpath->query('/wl:webLink/wl:url/@href');
117
                    if ($resource->length > 0) {
118
                        $rawlink = $resource->item(0)->nodeValue;
119
                        if (!validateUrlSyntax($rawlink, 's+')) {
120
                            $changed = rawurldecode($rawlink);
121
                            if (validateUrlSyntax($changed, 's+')) {
122
                                $link = $changed;
123
                            } else {
124
                                $link = 'http://invalidurldetected/';
125
                            }
126
                        } else {
127
                            $link = htmlspecialchars(trim($rawlink), ENT_COMPAT, 'UTF-8', false);
128
                        }
129
                    }
130
                }
131
            }
132
        }
133
134
        $mod_type = 'file';
135
        $mod_options = 'objectframe';
136
        $mod_reference = $link;
137
        $mod_alltext = '';
138
        // detect if we are dealing with html file
139
        if (!empty($link) && ($instance['common_cartridge_type'] == Cc1p3Convert::CC_TYPE_WEBCONTENT)) {
140
            $ext = strtolower(pathinfo($link, PATHINFO_EXTENSION));
141
            if (in_array($ext, ['html', 'htm', 'xhtml'])) {
142
                $mod_type = 'html';
143
                //extract the content of the file and treat it
144
                $rootpath = realpath(Cc1p3Convert::$pathToManifestFolder);
145
                $htmlpath = realpath($rootpath.DIRECTORY_SEPARATOR.$link);
146
                $dirpath = dirname($htmlpath);
147
                if (file_exists($htmlpath)) {
148
                    $fcontent = file_get_contents($htmlpath);
149
                    $mod_alltext = $this->prepareContent($fcontent);
150
                    $mod_reference = '';
151
                    $mod_options = '';
152
                    /**
153
                     * try to handle embedded resources
154
                     * images, linked static resources, applets, videos.
155
                     */
156
                    $doc = new DOMDocument();
157
                    $cdir = getcwd();
158
                    chdir($dirpath);
159
                    try {
160
                        $doc->loadHTML($mod_alltext);
161
                        $xpath = new DOMXPath($doc);
162
                        $attributes = ['href', 'src', 'background', 'archive', 'code'];
163
                        $qtemplate = "//*[@##][not(contains(@##,'://'))]/@##";
164
                        $query = '';
165
                        foreach ($attributes as $attrname) {
166
                            if (!empty($query)) {
167
                                $query .= " | ";
168
                            }
169
                            $query .= str_replace('##', $attrname, $qtemplate);
170
                        }
171
                        $list = $xpath->query($query);
172
                        $searches = [];
173
                        $replaces = [];
174
                        foreach ($list as $resrc) {
175
                            $rpath = $resrc->nodeValue;
176
                            $rtp = realpath($rpath);
177
                            if (($rtp !== false) && is_file($rtp)) {
178
                                //file is there - we are in business
179
                                $strip = str_replace("\\", "/", str_ireplace($rootpath, '/', $rtp));
180
                                //$encoded_file = '$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $strip);
181
                                $encoded_file = $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 = [
197
            $instance['instance'],
198
            self::safexml($instance['title']),
199
            $mod_type,
200
            $mod_alltext,
201
            $mod_reference, // src or href
202
            $mod_options,
203
        ];
204
205
        return $values;
206
    }
207
}
208