Completed
Push — 1.10.x ( 4a4ede...319c16 )
by Yannick
163:25 queued 134:54
created

OpenofficeDocument   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 335
Duplicated Lines 17.61 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 59
loc 335
rs 10
c 0
b 0
f 0
wmc 30
lcom 1
cbo 3

7 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 9 9 5
C convert_document() 26 125 12
A _get_remote_ppt2lp_files() 0 55 4
make_lp() 0 1 ?
add_docs_to_visio() 0 1 ?
add_command_parameters() 0 1 ?
D convertCopyDocument() 24 106 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Defines the OpenofficeDocument class, which is meant as a mother class
7
 * to help in the conversion of Office documents to learning paths
8
 * @package chamilo.learnpath
9
 * @author	Eric Marguin <[email protected]>
10
 * @author Julio Montoya
11
 * @license	GNU/GPL
12
 */
13
14
/**
15
 * Defines the "OpenofficeDocument" child of class "learnpath"
16
 */
17
abstract class OpenofficeDocument extends learnpath
18
{
19
20
    public $first_item = 0;
21
    public $original_charset = 'utf-8';
22
    public $original_locale = 'en_US.UTF-8';
23
24
    /**
25
     * Class constructor. Based on the parent constructor.
26
     * @param	string	Course code
27
     * @param	integer	Learnpath ID in DB
28
     * @param	integer	User ID
29
     */
30 View Code Duplication
    public function __construct($course_code = null, $resource_id = null, $user_id = null)
31
    {
32
        if ($this->debug > 0) {
33
            error_log('In OpenofficeDocument::OpenofficeDocument()', 0);
34
        }
35
        if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
36
            parent::__construct($course_code, $resource_id, $user_id);
37
        }
38
    }
39
40
    /**
41
     * @param string $file
42
     * @param string $action_after_conversion
43
     * @return bool|int
44
     */
45
    public function convert_document($file, $action_after_conversion = 'make_lp')
46
    {
47
        $_course = api_get_course_info();
48
        $this->file_name = pathinfo($file['name'], PATHINFO_FILENAME);
49
        // Create the directory
50
        $result = $this->generate_lp_folder($_course, $this->file_name);
51
52
         // Create the directory
53
        $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
54
        ///learning_path/ppt_dirname directory
55
        $this->created_dir = substr($result['dir'], 0, strlen($result['dir']) -1);
56
        $this->file_path = $this->created_dir.'/'.api_replace_dangerous_char($file['name']);
57
58
        //var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir);
59
60
        /*
61
         * Original code
62
        global $_course, $_user, $_configuration;
63
64
        $this->file_name = (strrpos($file['name'], '.') > 0 ? substr($file['name'], 0, strrpos($file['name'], '.')) : $file['name']);
65
        $this->file_name = api_replace_dangerous_char($this->file_name, 'strict');
66
        $this->file_name = strtolower($this->file_name);
67
68
        $visio_dir = ($action_after_conversion == 'add_docs_to_visio') ? VIDEOCONF_UPLOAD_PATH : '';
69
70
        $this->file_path = $visio_dir.'/'.$this->file_name.'.'.pathinfo($file['name'], PATHINFO_EXTENSION);
71
72
        $dir_name = $visio_dir.'/'.$this->file_name;
73
74
75
        // Create the directory.
76
        $this->base_work_dir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
77
78
        $this->created_dir = create_unexisting_directory($_course, $_user['user_id'], api_get_session_id(), 0, 0, $this->base_work_dir, $dir_name);
79
80
            var_dump($this->file_name, $this->file_path, $this->base_work_dir, $this->created_dir);
81
82
        */
83
84
        $ppt2lp_host = api_get_setting('service_ppt2lp', 'host');
85
86
        if ($ppt2lp_host == 'localhost') {
87
            move_uploaded_file($file['tmp_name'], $this->base_work_dir.'/'.$this->file_path);
88
            //var_dump( $this->base_work_dir.$this->created_dir.$this->file_path);
89
            $perm = api_get_setting('permissions_for_new_files');
90
91 View Code Duplication
            if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php
92
                $converter_path = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png');
93
                $class_path = $converter_path . ';' . $converter_path . '/jodconverter-2.2.2.jar;' . $converter_path . '/jodconverter-cli-2.2.2.jar';
94
                //$cmd = 'java -cp "'.$class_path.'" DokeosConverter';
95
                $cmd = 'java -Dfile.encoding=UTF-8 -cp "' . $class_path . '" DokeosConverter';
96
            } else {
97
                $converter_path = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
98
                //$class_path = '-cp .:jodconverter-2.2.1.jar:jodconverter-cli-2.2.1.jar';
99
                $class_path = ' -Dfile.encoding=UTF-8 -cp .:jodconverter-2.2.2.jar:jodconverter-cli-2.2.2.jar';
100
                $cmd = 'cd ' . $converter_path . ' && java ' . $class_path . ' DokeosConverter';
101
            }
102
103
            $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
104
            // Call to the function implemented by child.
105
            $cmd .= $this->add_command_parameters();
106
            // To allow openoffice to manipulate docs.
107
            @chmod($this->base_work_dir, 0777);
108
            @chmod($this->base_work_dir.$this->created_dir, 0777);
109
            @chmod($this->base_work_dir.$this->file_path, 0777);
110
111
            $locale = $this->original_locale; // TODO: Improve it because we're not sure this locale is present everywhere.
112
            putenv('LC_ALL=' . $locale);
113
114
            $files = array();
115
            $return = 0;
116
            $shell = exec($cmd, $files, $return);
117
118 View Code Duplication
            if ($return != 0) { // If the java application returns an error code.
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $return of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
119
                switch ($return) {
120
                    // Can't connect to openoffice.
121
                    case 1: $this->error = get_lang('CannotConnectToOpenOffice');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
122
                        break;
123
                    // Conversion failed in openoffice.
124
                    case 2: $this->error = get_lang('OogieConversionFailed');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
125
                        break;
126
                    // Conversion can't be launch because command failed.
127
                    case 255: $this->error = get_lang('OogieUnknownError');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
128
                        break;
129
                }
130
                DocumentManager::delete_document($_course, $this->created_dir, $this->base_work_dir);
131
                return false;
132
            }
133
        } else {
134
            // get result from webservices
135
            $result = $this->_get_remote_ppt2lp_files($file);
136
            $result = unserialize($result);
137
            // Save remote images to server
138
            chmod($this->base_work_dir.$this->created_dir, api_get_permissions_for_new_directories());
139
            if (!empty($result['images'])) {
140
                foreach ($result['images'] as $image => $img_data) {
141
                    $image_path = $this->base_work_dir.$this->created_dir;
142
                    @file_put_contents($image_path . '/' . $image, base64_decode($img_data));
143
                    @chmod($image_path . '/' . $image, 0777);
144
                }
145
            }
146
147
            // files info
148
            $files = $result['files'];
149
        }
150
151
        if (!empty($files)) {
152
            // Create lp
153
            $this->lp_id = learnpath::add_lp($_course['id'], $this->file_name, '', 'guess', 'manual');
154
            // make sure we have a course code available for later
155
            $this->cc = $_course['id'];
156
157
            // Call to the function implemented by child following action_after_conversion parameter.
158
            switch ($action_after_conversion) {
159
                case 'make_lp':
160
                    $this->make_lp($files);
161
                    break;
162
                case 'add_docs_to_visio':
163
                    $this->add_docs_to_visio($files);
164
                    break;
165
            }
166
            chmod($this->base_work_dir, api_get_permissions_for_new_directories());
167
        }
168
        return $this->first_item;
169
    }
170
171
    /**
172
     * Get images files from remote host (with webservices)
173
     * @param   array current ppt file
174
     * @return  array images files
175
     */
176
    private function _get_remote_ppt2lp_files($file)
177
    {
178
        // host
179
        $ppt2lp_host = api_get_setting('service_ppt2lp', 'host');
180
        // SOAP URI (just the host)
181
        $matches = array();
182
        $uri = '';
183
        $result = preg_match('/^([a-zA-Z0-9]*):\/\/([^\/]*)\//', $ppt2lp_host, $matches);
184
        if ($result) {
185
            $uri = $matches[1] . '://' . $matches[2] . '/';
186
        } else {
187
            $uri = $ppt2lp_host;
188
        }
189
        // secret key
190
        $secret_key = sha1(api_get_setting('service_ppt2lp', 'ftp_password'));
191
192
        // client
193
        $options = array(
194
            'location' => $ppt2lp_host,
195
            'uri' => $uri,
196
            'trace' => 1,
197
            'exceptions' => true,
198
            'cache_wsdl' => WSDL_CACHE_NONE,
199
            'keep_alive' => false,
200
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
201
            'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 9,
202
        );
203
        if (substr($ppt2lp_host, 0, 5) === 'https') {
204
            $options['ssl_method'] =  SOAP_SSL_METHOD_TLS;
205
        }
206
        $client = new SoapClient(null, $options);
207
        $result = '';
208
209
        $file_data = base64_encode(file_get_contents($file['tmp_name']));
210
        $file_name = $file['name'];
211
        $service_ppt2lp_size = api_get_setting('service_ppt2lp', 'size');
212
213
        $params = array(
214
            'secret_key' => $secret_key,
215
            'file_data' => $file_data,
216
            'file_name' => $file_name,
217
            'service_ppt2lp_size' => $service_ppt2lp_size,
218
        );
219
220
        try {
221
            //error_log('['.time().'] Calling wsConvertPpt webservice on ' . $ppt2lp_host);
222
            $result = $client->__call('wsConvertPpt', array('pptData' => $params));
223
        } catch (Exception $e) {
224
            error_log('['.time().'] Chamilo SOAP call error: ' . $e->getMessage());
225
        }
226
        // Make sure we destroy the SOAP client as it may generate SSL connection
227
        // binding issue (if using SSL)
228
        unset($client);
229
        return $result;
230
    }
231
232
    abstract function make_lp();
233
234
    abstract function add_docs_to_visio();
235
236
    abstract function add_command_parameters();
237
238
    /**
239
     * Used to convert copied from document
240
     * @param string $originalPath
241
     * @param string $convertedPath
242
     * @param string $convertedTitle
243
     * @return bool
244
     */
245
    function convertCopyDocument($originalPath, $convertedPath, $convertedTitle)
246
    {
247
        $_course = api_get_course_info();
248
        $ids = array();
249
        $originalPathInfo = pathinfo($originalPath);
250
        $convertedPathInfo = pathinfo($convertedPath);
251
        $this->base_work_dir = $originalPathInfo['dirname'];
252
        $this->file_path = $originalPathInfo['basename'];
253
        $this->created_dir = $convertedPathInfo['basename'];
254
        $ppt2lpHost = api_get_setting('service_ppt2lp', 'host');
255
        $permissionFile = api_get_permissions_for_new_files();
256
        $permissionFolder = api_get_permissions_for_new_directories();
257
        if (file_exists($this->base_work_dir . '/' . $this->created_dir)) {
258
259
            return $ids;
260
        }
261
262
        if ($ppt2lpHost == 'localhost') {
263 View Code Duplication
            if (IS_WINDOWS_OS) { // IS_WINDOWS_OS has been defined in main_api.lib.php
264
                $converterPath = str_replace('/', '\\', api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png');
265
                $classPath = $converterPath . ';' . $converterPath . '/jodconverter-2.2.2.jar;' . $converterPath . '/jodconverter-cli-2.2.2.jar';
266
                $cmd = 'java -Dfile.encoding=UTF-8 -jar "' . $classPath . '/jodconverter-2.2.2.jar"';
267
            } else {
268
                $converterPath = api_get_path(SYS_PATH) . 'main/inc/lib/ppt2png';
269
                $classPath = ' -Dfile.encoding=UTF-8 -jar jodconverter-cli-2.2.2.jar';
270
                $cmd = 'cd ' . $converterPath . ' && java ' . $classPath . ' ';
271
            }
272
273
            $cmd .= ' -p ' . api_get_setting('service_ppt2lp', 'port');
274
            // Call to the function implemented by child.
275
            $cmd .= ' "' . $this->base_work_dir . '/' . $this->file_path . '"  "' . $this->base_work_dir . '/' . $this->created_dir . '"';
276
            // To allow openoffice to manipulate docs.
277
            @chmod($this->base_work_dir, $permissionFolder);
278
            @chmod($this->base_work_dir . '/' . $this->file_path, $permissionFile);
279
280
            $locale = $this->original_locale; // TODO: Improve it because we're not sure this locale is present everywhere.
281
            putenv('LC_ALL=' . $locale);
282
283
            $files = array();
284
            $return = 0;
285
            $shell = exec($cmd, $files, $return);
286
            // TODO: Chown is not working, root keep user privileges, should be www-data
287
            @chown($this->base_work_dir . '/' . $this->created_dir, 'www-data');
288
            @chmod($this->base_work_dir . '/' . $this->created_dir, $permissionFile);
289
290 View Code Duplication
            if ($return != 0) { // If the java application returns an error code.
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $return of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
291
                switch ($return) {
292
                    // Can't connect to openoffice.
293
                    case 1: $this->error = get_lang('CannotConnectToOpenOffice');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
294
                        break;
295
                    // Conversion failed in openoffice.
296
                    case 2: $this->error = get_lang('OogieConversionFailed');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
297
                        break;
298
                    // Conversion can't be launch because command failed.
299
                    case 255: $this->error = get_lang('OogieUnknownError');
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
300
                        break;
301
                }
302
                DocumentManager::delete_document($_course, $this->created_dir, $this->base_work_dir);
303
                return false;
304
            }
305
        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
306
            /*
307
             * @TODO Create method to use webservice
308
            // get result from webservices
309
            $result = $this->_get_remote_ppt2lp_files($file);
310
            $result = unserialize(base64_decode($result));
311
312
            // Save remote images to server
313
            chmod($this->base_work_dir.$this->created_dir, api_get_permissions_for_new_directories());
314
            if (!empty($result['images'])) {
315
                foreach ($result['images'] as $image => $img_data) {
316
                    $image_path = $this->base_work_dir.$this->created_dir;
317
                    @file_put_contents($image_path . '/' . $image, base64_decode($img_data));
318
                    @chmod($image_path . '/' . $image, 0777);
319
                }
320
            }
321
322
            // files info
323
            $files = $result['files'];
324
            */
325
        }
326
327
        if (file_exists($this->base_work_dir . '/' . $this->created_dir)) {
328
329
            // Register Files to Document tool
330
            $ids[] = add_document(
331
                $_course,
332
                '/' . $this->created_dir,
333
                'file',
334
                filesize($this->base_work_dir . '/' . $this->created_dir),
335
                $convertedTitle,
336
                sprintf(
337
                    get_lang('FileConvertedFromXToY'),
338
                    strtoupper($originalPathInfo['extension']),
339
                    strtoupper($convertedPathInfo['extension'])
340
                ),
341
                0,
342
                true,
343
                null,
344
                api_get_session_id()
345
            );
346
            chmod($this->base_work_dir, $permissionFolder);
347
        }
348
349
        return $ids;
350
    }
351
}
352