Issues (2037)

main/lp/aicc.class.php (5 issues)

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class aicc
6
 * Defines the AICC class, which is meant to contain the aicc items (nuclear elements).
7
 *
8
 * @author Yannick Warnier <[email protected]>
9
 * @license GNU/GPL
10
 */
11
class aicc extends learnpath
12
{
13
    public $config = [];
14
    // The configuration files might be multiple and might have
15
    // funny names. We need to keep the name of that file while we
16
    // install the content.
17
    public $config_basename = '';
18
    public $config_files = [];
19
    public $config_exts = [
20
        'crs' => 0, // Course description file (mandatory)
21
        'au' => 0, // Assignable Unit file (mandatory)
22
        'des' => 0, // Descriptor file (mandatory)
23
        'cst' => 0, // Course structure file (mandatory)
24
        'ore' => 0, // Objectives relationshops file (optional)
25
        'pre' => 0, // Prerequisites file (optional)
26
        'cmp' => 0,  // Completion Requirements file (optional)
27
    ];
28
    public $aulist = [];
29
    public $au_order_list = [];
30
    public $au_order_list_new_id = [];
31
    public $deslist = [];
32
    public $cstlist = [];
33
    public $orelist = [];
34
35
    // Path between the scorm/ directory and the config files
36
    // e.g. maritime_nav/maritime_nav.
37
    // This is the path that will be used in the lp_path when importing a package.
38
    public $subdir = '';
39
    // Keeps the zipfile safe for the object's life
40
    // so that we can use it if there is no title available.
41
    public $zipname = '';
42
    // Keeps an index of the number of uses of the zipname so far.
43
    public $lastzipnameindex = 0;
44
    public $config_encoding = 'ISO-8859-1';
45
    public $debug = 0;
46
47
    /**
48
     * Class constructor. Based on the parent constructor.
49
     *
50
     * @param string $course_code
51
     * @param int    $resource_id Learnpath ID in DB
52
     * @param int    $user_id
53
     */
54
    public function __construct($course_code = null, $resource_id = null, $user_id = null)
55
    {
56
        if ($this->debug > 0) {
57
            error_log('In aicc::aicc()');
58
        }
59
        if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
60
            parent::__construct($course_code, $resource_id, $user_id);
61
        }
62
    }
63
64
    /**
65
     * Opens a resource.
66
     *
67
     * @param int Database ID of the resource
68
     */
69
    public function open($id)
70
    {
71
    }
72
73
    /**
74
     * Parses a set of AICC config files and puts everything into the $config array.
75
     *
76
     * @param string Path to the config files dir on the system.
77
     * If not defined, uses the base path of the course's scorm dir
78
     *
79
     * @return array Structured array representing the config files' contents
80
     */
81
    public function parse_config_files($dir = '')
82
    {
83
        if ($this->debug > 0) {
84
            error_log('New LP - In aicc::parse_config_files('.$dir.')', 0);
85
        }
86
        if (empty($dir)) {
87
            // Get the path of the AICC config files dir.
88
            $dir = $this->subdir;
89
        }
90
        if (is_dir($dir) && is_readable($dir)) {
91
            // Now go through all the config files one by one and parse everything into AICC objects.
92
            // The basename for the config files is stored in $this->config_basename.
93
            // Parse the Course Description File (.crs) - ini-type.
94
            $crs_file = $dir.'/'.$this->config_files['crs'];
95
            $crs_params = $this->parse_ini_file_quotes_safe($crs_file);
96
            if ($this->debug > 1) {
97
                error_log('New LP - In aicc::parse_config_files() - '.$crs_file.' has been parsed');
98
            }
99
100
            // CRS distribute crs params into the aicc object.
101
            if (!empty($crs_params['course']['course_creator'])) {
102
                $this->course_creator = Database::escape_string($crs_params['course']['course_creator']);
103
            }
104
            if (!empty($crs_params['course']['course_id'])) {
105
                $this->course_id = Database::escape_string($crs_params['course']['course_id']);
106
            }
107
            if (!empty($crs_params['course']['course_system'])) {
108
                $this->course_system = $crs_params['course']['course_system'];
109
            }
110
            if (!empty($crs_params['course']['course_title'])) {
111
                $this->course_title = Database::escape_string($crs_params['course']['course_title']);
112
            }
113
            if (!empty($crs_params['course']['course_level'])) {
114
                $this->course_level = $crs_params['course']['course_level'];
115
            }
116
            if (!empty($crs_params['course']['max_fields_cst'])) {
117
                $this->course_max_fields_cst = $crs_params['course']['max_fields_cst'];
118
            }
119
            if (!empty($crs_params['course']['max_fields_ort'])) {
120
                $this->course_max_fields_ort = $crs_params['course']['max_fields_ort'];
121
            }
122
            if (!empty($crs_params['course']['total_aus'])) {
123
                $this->course_total_aus = $crs_params['course']['total_aus'];
124
            }
125
            if (!empty($crs_params['course']['total_blocks'])) {
126
                $this->course_total_blocks = $crs_params['course']['total_blocks'];
127
            }
128
            if (!empty($crs_params['course']['total_objectives'])) {
129
                $this->course_total_objectives = $crs_params['course']['total_objectives'];
130
            }
131
            if (!empty($crs_params['course']['total_complex_objectives'])) {
132
                $this->course_total_complex_objectives = $crs_params['course']['total_complex_objectives'];
133
            }
134
            if (!empty($crs_params['course']['version'])) {
135
                $this->course_version = $crs_params['course']['version'];
136
            }
137
            if (!empty($crs_params['course_description'])) {
138
                $this->course_description = Database::escape_string($crs_params['course_description']);
139
            }
140
141
            // Parse the Descriptor File (.des) - csv-type.
142
            $des_file = $dir.'/'.$this->config_files['des'];
143
            $des_params = $this->parse_csv_file($des_file);
144
            if ($this->debug > 1) {
145
                error_log('New LP - In aicc::parse_config_files() - '.$des_file.' has been parsed', 0);
146
            }
147
            // Distribute des params into the aicc object.
148
            foreach ($des_params as $des) {
149
                // One AU in AICC is equivalent to one SCO in SCORM (scormItem class).
150
                $oDes = new aiccResource('config', $des);
151
                $this->deslist[$oDes->identifier] = $oDes;
152
            }
153
154
            // Parse the Assignable Unit File (.au) - csv-type.
155
            $au_file = $dir.'/'.$this->config_files['au'];
156
            $au_params = $this->parse_csv_file($au_file);
157
            if ($this->debug > 1) {
158
                error_log('New LP - In aicc::parse_config_files() - '.$au_file.' has been parsed', 0);
159
            }
160
            // Distribute au params into the aicc object.
161
            foreach ($au_params as $au) {
162
                $oAu = new aiccItem('config', $au);
163
                $this->aulist[$oAu->identifier] = $oAu;
164
                $this->au_order_list[] = $oAu->identifier;
165
            }
166
167
            // Parse the Course Structure File (.cst) - csv-type.
168
            $cst_file = $dir.'/'.$this->config_files['cst'];
169
            $cst_params = $this->parse_csv_file($cst_file, ',', '"', true);
170
            if ($this->debug > 1) {
171
                error_log('New LP - In aicc::parse_config_files() - '.$cst_file.' has been parsed', 0);
172
            }
173
            // Distribute cst params into the aicc object.
174
            foreach ($cst_params as $cst) {
175
                $oCst = new aiccBlock('config', $cst);
176
                $this->cstlist[$oCst->identifier] = $oCst;
177
            }
178
179
            // Parse the Objectives Relationships File (.ore) - csv-type - if exists.
180
            // TODO: Implement these objectives. For now they're just parsed.
181
            if (!empty($this->config_files['ore'])) {
182
                $ore_file = $dir.'/'.$this->config_files['ore'];
183
                $ore_params = $this->parse_csv_file($ore_file, ',', '"', true);
184
                if ($this->debug > 1) {
185
                    error_log('New LP - In aicc::parse_config_files() - '.$ore_file.' has been parsed', 0);
186
                }
187
                // Distribute ore params into the aicc object.
188
                foreach ($ore_params as $ore) {
189
                    $oOre = new aiccObjective('config', $ore);
190
                    $this->orelist[$oOre->identifier] = $oOre;
191
                }
192
            }
193
194
            // Parse the Prerequisites File (.pre) - csv-type - if exists.
195
            if (!empty($this->config_files['pre'])) {
196
                $pre_file = $dir.'/'.$this->config_files['pre'];
197
                $pre_params = $this->parse_csv_file($pre_file);
198
                if ($this->debug > 1) {
199
                    error_log('New LP - In aicc::parse_config_files() - '.$pre_file.' has been parsed', 0);
200
                }
201
                // Distribute pre params into the aicc object.
202
                foreach ($pre_params as $pre) {
203
                    // Place a constraint on the corresponding block or AU.
204
                    if (in_array(api_strtolower($pre['structure_element']), array_keys($this->cstlist))) {
205
                        // If this references a block element:
206
                        $this->cstlist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower($pre['prerequisite']);
207
                    }
208
                    if (in_array(api_strtolower($pre['structure_element']), array_keys($this->aulist))) {
209
                        // If this references a block element:
210
                        $this->aulist[api_strtolower($pre['structure_element'])]->prereq_string = api_strtolower($pre['prerequisite']);
211
                    }
212
                }
213
            }
214
215
            // Parse the Completion Requirements File (.cmp) - csv-type - if exists.
216
            // TODO: Implement this set of requirements (needs database changes).
217
            if (!empty($this->config_files['cmp'])) {
218
                $cmp_file = $dir.'/'.$this->config_files['cmp'];
219
                $cmp_params = $this->parse_csv_file($cmp_file);
220
                if ($this->debug > 1) {
221
                    error_log('New LP - In aicc::parse_config_files() - '.$cmp_file.' has been parsed', 0);
222
                }
223
                // Distribute cmp params into the aicc object.
224
                foreach ($cmp_params as $cmp) {
225
                    //$oCmp = new aiccCompletionRequirements('config', $cmp);
226
                    //$this->cmplist[$oCmp->identifier] =& $oCmp;
227
                }
228
            }
229
        }
230
231
        return $this->config;
232
    }
233
234
    /**
235
     * Import the aicc object (as a result from the parse_config_files function) into the database structure.
236
     *
237
     * @param string $course_code
238
     *
239
     * @return bool Returns -1 on error
240
     */
241
    public function import_aicc($course_code)
242
    {
243
        $courseInfo = api_get_course_info($course_code);
244
        $course_id = $courseInfo['real_id'];
245
246
        if (empty($course_id)) {
247
            return false;
248
        }
249
250
        if ($this->debug > 0) {
251
            error_log('New LP - In aicc::import_aicc('.$course_code.')', 0);
252
        }
253
254
        $new_lp = Database::get_course_table(TABLE_LP_MAIN);
255
        $new_lp_item = Database::get_course_table(TABLE_LP_ITEM);
256
        $get_max = "SELECT MAX(display_order) FROM $new_lp WHERE c_id = $course_id";
257
        $res_max = Database::query($get_max);
258
        if (Database::num_rows($res_max) < 1) {
259
            $dsp = 1;
260
        } else {
261
            $row = Database::fetch_array($res_max);
262
            $dsp = $row[0] + 1;
263
        }
264
265
        $this->config_encoding = "ISO-8859-1"; // TODO: We may apply detection for this value, see the function api_detect_encoding().
266
267
        $sql = "INSERT INTO $new_lp (c_id, lp_type, name, ref, description, path, force_commit, default_view_mod, default_encoding, js_lib, content_maker,display_order)".
268
                "VALUES ".
269
                "($course_id, 3, '".$this->course_title."', '".$this->course_id."','".$this->course_description."',".
270
                "'".$this->subdir."', 0, 'embedded', '".$this->config_encoding."',".
271
                "'aicc_api.php','".$this->course_creator."',$dsp)";
272
        if ($this->debug > 2) {
273
            error_log('New LP - In import_aicc(), inserting path: '.$sql, 0);
274
        }
275
        Database::query($sql);
276
        $lp_id = Database::insert_id();
277
        Event::addEvent(
278
            LOG_LP_CREATE,
279
            LOG_LP_ID,
280
            $lp_id.' - '.$this->course_title
281
        );
282
283
        if ($lp_id) {
284
            $sql = "UPDATE $new_lp SET id = iid  WHERE iid = $lp_id";
285
            Database::query($sql);
286
287
            $this->lp_id = $lp_id;
288
289
            api_item_property_update(
290
                $courseInfo,
291
                TOOL_LEARNPATH,
292
                $this->lp_id,
293
                'LearnpathAdded',
294
                api_get_user_id()
295
            );
296
297
            api_item_property_update(
298
                $courseInfo,
299
                TOOL_LEARNPATH,
300
                $this->lp_id,
301
                'visible',
302
                api_get_user_id()
303
            );
304
        }
305
306
        $previous = 0;
307
        foreach ($this->aulist as $identifier => $dummy) {
308
            $oAu = &$this->aulist[$identifier];
309
            //echo "Item ".$oAu->identifier;
310
            $field_add = '';
311
            $value_add = '';
312
            if (!empty($oAu->masteryscore)) {
313
                $field_add = 'mastery_score, ';
314
                $value_add = $oAu->masteryscore.',';
315
            }
316
            $title = $oAu->identifier;
317
            if (is_object($this->deslist[$identifier])) {
318
                $title = $this->deslist[$identifier]->title;
319
            }
320
            $path = $oAu->path;
321
            //$max_score = $oAu->max_score // TODO: Check if special constraint exists for this item.
322
            //$min_score = $oAu->min_score // TODO: Check if special constraint exists for this item.
323
            $parent = 0; // TODO: Deal with the parent.
324
            $previous = 0;
325
            $prereq = $oAu->prereq_string;
326
            $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,parameters) ".
327
                    "VALUES ".
328
                    "($course_id, $lp_id, 'au','".$oAu->identifier."','".$title."',".
329
                    "'$path',0,100, $value_add".
330
                    "$parent, $previous, 0, ".
331
                    "'$prereq', 0,'".(!empty($oAu->parameters) ? Database::escape_string($oAu->parameters) : '')."'".
332
                    ")";
333
            Database::query($sql_item);
334
            if ($this->debug > 1) {
335
                error_log('New LP - In aicc::import_aicc() - inserting item : '.$sql_item.' : ', 0);
336
            }
337
            $item_id = Database::insert_id();
338
339
            if ($item_id) {
340
                $sql = "UPDATE $new_lp_item SET id = iid WHERE iid = $lp_id";
341
                Database::query($sql);
342
            }
343
344
            // Now update previous item to change next_item_id.
345
            if (0 != $previous) {
346
                $upd = "UPDATE $new_lp_item SET next_item_id = $item_id WHERE c_id = $course_id AND id = $previous";
347
                Database::query($upd);
348
                // Update the previous item id.
349
            }
350
            $previous = $item_id;
351
        }
352
    }
353
354
    /**
355
     * Intermediate to import_package only to allow import from local zip files.
356
     *
357
     * @param string    Path to the zip file, from the dokeos sys root
358
     * @param string    Current path (optional)
359
     *
360
     * @return string Absolute path to the AICC description files or empty string on error
361
     */
362
    public function import_local_package($file_path, $current_dir = '')
363
    {
364
        // TODO: Prepare info as given by the $_FILES[''] vector.
365
        $file_info = [];
366
        $file_info['tmp_name'] = $file_path;
367
        $file_info['name'] = basename($file_path);
368
        // Call the normal import_package function.
369
        return $this->import_package($file_info, $current_dir);
370
    }
371
372
    /**
373
     * Imports a zip file (presumably AICC) into the Chamilo structure.
374
     *
375
     * @param string    Zip file info as given by $_FILES['userFile']
376
     *
377
     * @return string Absolute path to the AICC config files directory or empty string on error
378
     */
379
    public function import_package($zip_file_info, $current_dir = '')
380
    {
381
        if ($this->debug > 0) {
382
            error_log('In aicc::import_package('.print_r($zip_file_info, true).',"'.$current_dir.'") method', 0);
383
        }
384
        //ini_set('error_log', 'E_ALL');
385
        $maxFilledSpace = 1000000000;
386
        $zip_file_path = $zip_file_info['tmp_name'];
387
        $zip_file_name = $zip_file_info['name'];
388
389
        if ($this->debug > 0) {
390
            error_log(
391
                'New LP - aicc::import_package() - Zip file path = '.$zip_file_path.', zip file name = '.$zip_file_name,
392
                0
393
            );
394
        }
395
        $course_rel_dir = api_get_course_path().'/scorm'; // Scorm dir web path starting from /courses
396
        $course_sys_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // The absolute system path of this course.
397
        $current_dir = api_replace_dangerous_char(trim($current_dir)); // Current dir we are in, inside scorm/
398
        if ($this->debug > 0) {
399
            error_log('New LP - aicc::import_package() - Current_dir = '.$current_dir, 0);
400
        }
401
402
        //$uploaded_filename = $_FILES['userFile']['name'];
403
        // Get the name of the zip file without the extension.
404
        if ($this->debug > 0) {
405
            error_log('New LP - aicc::import_package() - Received zip file name: '.$zip_file_path, 0);
406
        }
407
        $file_info = pathinfo($zip_file_name);
408
        $filename = $file_info['basename'];
409
        $extension = $file_info['extension'];
410
        $file_base_name = str_replace('.'.$extension, '', $filename); // Filename without its extension.
411
        $this->zipname = $file_base_name; // Save for later in case we don't have a title.
412
413
        if ($this->debug > 0) {
414
            error_log('New LP - aicc::import_package() - Base file name is : '.$file_base_name, 0);
415
        }
416
        $new_dir = api_replace_dangerous_char(trim($file_base_name));
417
        $this->subdir = $new_dir;
418
        if ($this->debug > 0) {
419
            error_log('New LP - aicc::import_package() - Subdir is first set to : '.$this->subdir, 0);
420
        }
421
422
        /*
423
        if (check_name_exist($course_sys_dir.$current_dir.'/'.$new_dir)) {
424
            $dialogBox = get_lang('FileExists');
425
            $stopping_error = true;
426
        }
427
        */
428
        $zipFile = new PclZip($zip_file_path);
429
        // Check the zip content (real size and file extension).
430
        $zipContentArray = $zipFile->listContent();
431
432
        $package_type = ''; // The type of the package. Should be 'aicc' after the next few lines.
433
        $package = ''; // The basename of the config files (if 'courses.crs' => 'courses').
434
        $at_root = false; // Check if the config files are at zip root.
435
        $config_dir = ''; // The directory in which the config files are. May remain empty.
436
        $files_found = [];
437
        $subdir_isset = false;
438
        // The following loop should be stopped as soon as we found the right config files (.crs, .au, .des and .cst).
439
        $realFileSize = 0;
440
        foreach ($zipContentArray as $thisContent) {
441
            if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
442
                // If a php file is found, do not authorize (security risk).
443
                if ($this->debug > 1) {
444
                    error_log(
445
                        'New LP - aicc::import_package() - Found unauthorized file: '.$thisContent['filename']
446
                    );
447
                }
448
                Display::addFlash(
449
                    Display::return_message(get_lang('ZipNoPhp'))
450
                );
451
452
                return false;
453
            } elseif (preg_match('?.*/aicc/$?', $thisContent['filename'])) {
454
                // If a directory named 'aicc' is found, package type = aicc, but continue,
455
                // because we need to find the right AICC files;
456
                if ($this->debug > 1) {
457
                    error_log('New LP - aicc::import_package() - Found aicc directory: '.$thisContent['filename']);
458
                }
459
                $package_type = 'aicc';
460
            } else {
461
                // else, look for one of the files we're searching for (something.crs case insensitive).
462
                $res = [];
463
                if (preg_match('?^(.*)\.(crs|au|des|cst|ore|pre|cmp)$?i', $thisContent['filename'], $res)) {
464
                    if ($this->debug > 1) {
465
                        error_log(
466
                            'New LP - aicc::import_package() - Found AICC config file: '.$thisContent['filename'].'. Now splitting: '.$res[1].' and '.$res[2]
467
                        );
468
                    }
469
                    if ($thisContent['filename'] == basename($thisContent['filename'])) {
470
                        if ($this->debug > 2) {
471
                            error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is at root level', 0);
472
                        }
473
                        $at_root = true;
474
                        if (!is_array($files_found[$res[1]])) {
475
                            $files_found[$res[1]] = $this->config_exts; // Initialise list of expected extensions (defined in class definition).
476
                        }
477
                        $files_found[$res[1]][api_strtolower($res[2])] = $thisContent['filename'];
478
                        $subdir_isset = true;
479
                    } else {
480
                        if (!$subdir_isset) {
481
                            if (preg_match('?^.*/aicc$?i', dirname($thisContent['filename']))) {
482
                                //echo "Cutting subdir<br/>";
483
                                $this->subdir .= '/'.substr(dirname($thisContent['filename']), 0, -5);
484
                            } else {
485
                                //echo "Not cutting subdir<br/>";
486
                                $this->subdir .= '/'.dirname($thisContent['filename']);
487
                            }
488
                            $subdir_isset = true;
489
                        }
490
                        if ($this->debug > 2) {
491
                            error_log('New LP - aicc::import_package() - '.$thisContent['filename'].' is not at root level - recording subdir '.$this->subdir, 0);
492
                        }
493
                        $config_dir = dirname($thisContent['filename']); // Just the relative directory inside scorm/
494
                        if (!is_array($files_found[basename($res[1])])) {
495
                            $files_found[basename($res[1])] = $this->config_exts;
496
                        }
497
                        $files_found[basename($res[1])][api_strtolower($res[2])] = basename($thisContent['filename']);
498
                    }
499
                    $package_type = 'aicc';
500
                } else {
501
                    if ($this->debug > 3) {
502
                        error_log('New LP - aicc::import_package() - File '.$thisContent['filename'].' didnt match any check', 0);
503
                    }
504
                }
505
            }
506
            $realFileSize += $thisContent['size'];
507
        }
508
        if ($this->debug > 2) {
509
            error_log('New LP - aicc::import_package() - $files_found: '.print_r($files_found, true), 0);
510
        }
511
        if ($this->debug > 1) {
512
            error_log('New LP - aicc::import_package() - Package type is now '.$package_type, 0);
513
        }
514
        $mandatory = false;
515
        foreach ($files_found as $file_name => $file_exts) {
516
            $temp = (
517
                !empty($files_found[$file_name]['crs'])
518
                && !empty($files_found[$file_name]['au'])
519
                && !empty($files_found[$file_name]['des'])
520
                && !empty($files_found[$file_name]['cst'])
521
            );
522
            if ($temp) {
523
                if ($this->debug > 1) {
524
                    error_log('New LP - aicc::import_package() - Found all config files for '.$file_name, 0);
525
                }
526
                $mandatory = true;
527
                $package = $file_name;
528
                // Store base config file name for reuse in parse_config_files().
529
                $this->config_basename = $file_name;
530
                // Store filenames for reuse in parse_config_files().
531
                $this->config_files = $files_found[$file_name];
532
                // Get out, we only want one config files set.
533
                break;
534
            }
535
        }
536
537
        if ($package_type == '' || !$mandatory) {
538
            Display::addFlash(
539
                Display::return_message(get_lang('FileError'))
540
            );
541
542
            return false;
543
        }
544
545
        if (!enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
546
            Display::addFlash(
547
                Display::return_message(get_lang('NoSpace'))
548
            );
549
550
            return false;
551
        }
552
553
        // It happens on Linux that $new_dir sometimes doesn't start with '/'
554
        if ($new_dir[0] != '/') {
555
            $new_dir = '/'.$new_dir;
556
        }
557
        // Cut trailing slash.
558
        if ($new_dir[strlen($new_dir) - 1] == '/') {
559
            $new_dir = substr($new_dir, 0, -1);
560
        }
561
562
        /* Uncompressing phase */
563
564
        /*
565
            We need to process each individual file in the zip archive to
566
            - add it to the database
567
            - parse & change relative html links
568
            - make sure the filenames are secure (filter funny characters or php extensions)
569
        */
570
        if (is_dir($course_sys_dir.$new_dir) ||
571
            @mkdir($course_sys_dir.$new_dir, api_get_permissions_for_new_directories())
572
        ) {
573
            // PHP method - slower...
574
            if ($this->debug >= 1) {
575
                error_log('New LP - Changing dir to '.$course_sys_dir.$new_dir, 0);
576
            }
577
            chdir($course_sys_dir.$new_dir);
578
            $zipFile->extract(
579
                PCLZIP_CB_PRE_EXTRACT,
580
                'clean_up_files_in_zip'
581
            );
582
        } else {
583
            return '';
584
        }
585
586
        return $course_sys_dir.$new_dir.$config_dir;
587
    }
588
589
    /**
590
     * Sets the proximity setting in the database.
591
     *
592
     * @param string $proxy Proximity setting
593
     *
594
     * @return bool
595
     */
596
    public function set_proximity($proxy = '')
597
    {
598
        $course_id = api_get_course_int_id();
599
        if ($this->debug > 0) {
600
            error_log('In aicc::set_proximity('.$proxy.') method', 0);
601
        }
602
        $lp = $this->get_id();
603
        if ($lp != 0) {
604
            $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
605
            $sql = "UPDATE $tbl_lp SET content_local = '$proxy' WHERE c_id = ".$course_id." id = ".$lp;
606
            Database::query($sql);
607
608
            return true;
609
        } else {
610
            return false;
611
        }
612
    }
613
614
    /**
615
     * Sets the theme setting in the database.
616
     *
617
     * @param    string    Theme setting
618
     *
619
     * @return bool
620
     */
621
    public function set_theme($theme = '')
622
    {
623
        $course_id = api_get_course_int_id();
624
        if ($this->debug > 0) {
625
            error_log('In aicc::set_theme('.$theme.') method', 0);
626
        }
627
        $lp = $this->get_id();
628
        if ($lp != 0) {
629
            $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
630
            $sql = "UPDATE $tbl_lp SET theme = '$theme' WHERE c_id = ".$course_id." id = ".$lp;
631
            $res = Database::query($sql);
632
633
            return true;
634
        } else {
635
            return false;
636
        }
637
    }
638
639
    /**
640
     * Sets the image LP in the database.
641
     *
642
     * @param string $preview_image Theme setting
643
     *
644
     * @return bool
645
     */
646
    public function set_preview_image($preview_image = '')
647
    {
648
        $course_id = api_get_course_int_id();
649
        if ($this->debug > 0) {
650
            error_log('In aicc::set_preview_image('.$preview_image.') method', 0);
651
        }
652
        $lp = $this->get_id();
653
        if ($lp != 0) {
654
            $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
655
            $sql = "UPDATE $tbl_lp SET preview_image = '$preview_image'
656
                    WHERE c_id = ".$course_id." id = ".$lp;
657
            Database::query($sql);
658
659
            return true;
660
        } else {
661
            return false;
662
        }
663
    }
664
665
    /**
666
     * Sets the Author LP in the database.
667
     *
668
     * @param string $author
669
     *
670
     * @return true
671
     */
672
    public function set_author($author = '')
673
    {
674
        $course_id = api_get_course_int_id();
675
        $lp = $this->get_id();
676
        if ($lp != 0) {
677
            $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
678
            $sql = "UPDATE $tbl_lp SET author = '$author'
679
                    WHERE c_id = ".$course_id." id = ".$lp;
680
            Database::query($sql);
681
682
            return true;
683
        }
684
685
        return false;
686
    }
687
688
    /**
689
     * Sets the content maker setting in the database.
690
     *
691
     * @param string $maker
692
     *
693
     * @return bool
694
     */
695
    public function set_maker($maker = '')
696
    {
697
        $course_id = api_get_course_int_id();
698
        if ($this->debug > 0) {
699
            error_log('In aicc::set_maker method('.$maker.')', 0);
700
        }
701
        $lp = $this->get_id();
702
        if ($lp != 0) {
703
            $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
704
            $sql = "UPDATE $tbl_lp SET content_maker = '$maker'
705
                    WHERE c_id = ".$course_id." id = ".$lp;
706
            Database::query($sql);
707
708
            return true;
709
        } else {
710
            return false;
711
        }
712
    }
713
714
    /**
715
     * Exports the current AICC object's files as a zip. Excerpts taken from learnpath_functions.inc.php::exportpath().
716
     *
717
     * @param    int    Learnpath ID (optional, taken from object context if not defined)
718
     *
719
     * @return bool
720
     */
721
    public function export_zip($lp_id = null)
722
    {
723
        if ($this->debug > 0) {
724
            error_log('In aicc::export_zip method('.$lp_id.')', 0);
725
        }
726
        if (empty($lp_id)) {
727
            if (!is_object($this)) {
728
                return false;
729
            } else {
730
                $id = $this->get_id();
731
                if (empty($id)) {
732
                    return false;
733
                } else {
734
                    $lp_id = $this->get_id();
735
                }
736
            }
737
        }
738
        // Zip everything that is in the corresponding scorm dir.
739
        // Write the zip file somewhere (might be too big to return).
740
        $course_id = api_get_course_int_id();
741
        $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
742
        $_course = api_get_course_info(api_get_course_id());
743
744
        $sql = "SELECT * FROM $tbl_lp WHERE iid= $lp_id";
745
        $result = Database::query($sql);
746
        $row = Database::fetch_array($result);
747
        $LPname = $row['path'];
748
        $list = explode('/', $LPname);
749
        $LPnamesafe = $list[0];
750
        //$zipfoldername = '/tmp';
751
        //$zipfoldername = '../../courses/'.$_course['directory'].'/temp/'.$LPnamesafe;
752
        $zipfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/temp/'.$LPnamesafe;
753
        $scormfoldername = api_get_path(SYS_COURSE_PATH).$_course['directory'].'/scorm/'.$LPnamesafe;
754
        $zipfilename = $zipfoldername.'/'.$LPnamesafe.'.zip';
755
756
        // Get a temporary dir for creating the zip file.
757
        removeDir($zipfoldername); //make sure the temp dir is cleared
758
        mkdir($zipfoldername, api_get_permissions_for_new_directories());
759
760
        // Create zipfile of given directory.
761
        $zip_folder = new PclZip($zipfilename);
762
        $zip_folder->create($scormfoldername.'/', PCLZIP_OPT_REMOVE_PATH, $scormfoldername.'/');
763
764
        //this file sending implies removing the default mime-type from php.ini
765
        DocumentManager::file_send_for_download($zipfilename, true);
766
767
        // Delete the temporary zip file and directory in fileManage.lib.php
768
        my_delete($zipfilename);
769
        my_delete($zipfoldername);
770
771
        return true;
772
    }
773
774
    /**
775
     * Gets a resource's path if available, otherwise return empty string.
776
     *
777
     * @param	string	Resource ID as used in resource array
778
     *
779
     * @return string The resource's path as declared in config file course.crs
780
     */
781
    public function get_res_path($id)
782
    {
783
        if ($this->debug > 0) {
784
            error_log('In aicc::get_res_path('.$id.') method', 0);
785
        }
786
        $path = '';
787
        if (isset($this->resources[$id])) {
0 ignored issues
show
Bug Best Practice introduced by
The property resources does not exist on aicc. Did you maybe forget to declare it?
Loading history...
788
            $oRes = &$this->resources[$id];
789
            $path = @$oRes->get_path();
790
        }
791
792
        return $path;
793
    }
794
795
    /**
796
     * Gets a resource's type if available, otherwise return empty string.
797
     *
798
     * @param	string	Resource ID as used in resource array
799
     *
800
     * @return string The resource's type as declared in the assignable unit (.au) file
801
     */
802
    public function get_res_type($id)
803
    {
804
        if ($this->debug > 0) {
805
            error_log('In aicc::get_res_type('.$id.') method', 0);
806
        }
807
        $type = '';
808
        if (isset($this->resources[$id])) {
0 ignored issues
show
Bug Best Practice introduced by
The property resources does not exist on aicc. Did you maybe forget to declare it?
Loading history...
809
            $oRes = &$this->resources[$id];
810
            $temptype = $oRes->get_scorm_type();
811
            if (!empty($temptype)) {
812
                $type = $temptype;
813
            }
814
        }
815
816
        return $type;
817
    }
818
819
    /**
820
     * Gets the default organisation's title.
821
     *
822
     * @return string The organization's title
823
     */
824
    public function get_title()
825
    {
826
        if ($this->debug > 0) {
827
            error_log('In aicc::get_title() method', 0);
828
        }
829
        $title = '';
830
        if (isset($this->config['organizations']['default'])) {
831
            $title = $this->organizations[$this->config['organizations']['default']]->get_name();
0 ignored issues
show
Bug Best Practice introduced by
The property organizations does not exist on aicc. Did you maybe forget to declare it?
Loading history...
832
        } elseif (count($this->organizations) == 1) {
833
            // This will only get one title but so we don't need to know the index.
834
            foreach ($this->organizations as $id => $value) {
835
                $title = $this->organizations[$id]->get_name();
836
                break;
837
            }
838
        }
839
840
        return $title;
841
    }
842
843
    /**
844
     * TODO: Implement this function to restore items data from a set of AICC config files,
845
     * updating the existing table... This will prove very useful in case initial data
846
     * from config files were not imported well enough.
847
     */
848
    public function reimport_aicc()
849
    {
850
        if ($this->debug > 0) {
851
            error_log('In aicc::reimport_aicc() method', 0);
852
        }
853
        //query current items list
854
        //get the identifiers
855
        //parse the config files
856
        //match both
857
        //update DB accordingly
858
        return true;
859
    }
860
861
    /**
862
     * Static function to parse AICC ini files.
863
     * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file()).
864
     *
865
     * @param	string	File path
866
     *
867
     * @return array Structured array
868
     */
869
    public function parse_ini_file_quotes_safe($f)
870
    {
871
        $null = '';
872
        $r = $null;
873
        $sec = $null;
874
        $f = @file_get_contents($f);
875
        $f = api_convert_encoding($f, api_get_system_encoding(), $this->config_encoding);
876
        $f = preg_split('/\r?\n/', $f);
877
        for ($i = 0; $i < @count($f); $i++) {
878
            $newsec = 0;
879
            $w = @trim($f[$i]);
880
            if (substr($w, 0, 1) == ';') {
881
                // Ignore comment lines
882
                continue;
883
            }
884
            if ($w) {
885
                if ((!$r) or ($sec)) {
886
                    if ((@substr($w, 0, 1) == '[') and (@substr($w, -1, 1)) == ']') {
887
                        $sec = @substr($w, 1, @strlen($w) - 2);
888
                        $newsec = 1;
889
                    }
890
                }
891
                if (!$newsec) {
892
                    $w = @explode('=', $w);
893
                    $k = @trim($w[0]);
894
                    unset($w[0]);
895
                    $v = @trim(@implode('=', $w));
896
                    if ((@substr($v, 0, 1) == "\"") and (@substr($v, -1, 1) == "\"")) {
897
                        $v = @substr($v, 1, @strlen($v) - 2);
898
                    }
899
                    if ($sec) {
900
                        if (api_strtolower($sec) == 'course_description') { // A special case.
901
                            $r[api_strtolower($sec)] = $k;
902
                        } else {
903
                            $r[api_strtolower($sec)][api_strtolower($k)] = $v;
904
                        }
905
                    } else {
906
                        $r[api_strtolower($k)] = $v;
907
                    }
908
                }
909
            }
910
        }
911
912
        return $r;
913
    }
914
915
    /**
916
     * Static function to parse AICC ini strings.
917
     * Based on work by sinedeo at gmail dot com published on php.net (parse_ini_file()).
918
     *
919
     * @param		string	INI File string
920
     * @param		array	List of names of sections that should be considered
921
     * as containing only hard string data (no variables), provided in lower case
922
     *
923
     * @return array Structured array
924
     */
925
    public function parse_ini_string_quotes_safe($s, $pure_strings = [])
926
    {
927
        $null = '';
928
        $r = $null;
929
        $sec = $null;
930
        $s = api_convert_encoding($s, api_get_system_encoding(), $this->config_encoding);
931
        //$f = split("\r\n", $s);
932
        $f = preg_split('/\r?\n/', $s);
933
        for ($i = 0; $i < @count($f); $i++) {
934
            $newsec = 0;
935
            $w = @trim($f[$i]);
936
            if (substr($w, 0, 1) == ';') {
937
                // Ignore comment lines
938
                continue;
939
            }
940
            if ($w) {
941
                if ((!$r) or ($sec)) {
942
                    if ((@substr($w, 0, 1) == '[') and (@substr($w, -1, 1)) == ']') {
943
                        $sec = @substr($w, 1, @strlen($w) - 2);
944
                        $pure_data = 0;
945
                        if (in_array(api_strtolower($sec), $pure_strings)) {
946
                            // This section can only be considered as pure string data (until the next section).
947
                            $pure_data = 1;
948
                            $r[api_strtolower($sec)] = '';
949
                        }
950
                        $newsec = 1;
951
                    }
952
                }
953
                if (!$newsec) {
954
                    $w = @explode('=', $w);
955
                    $k = @trim($w[0]);
956
                    unset($w[0]);
957
                    $v = @trim(@implode('=', $w));
958
                    if ((@substr($v, 0, 1) == "\"") and (@substr($v, -1, 1) == "\"")) {
959
                        $v = @substr($v, 1, @strlen($v) - 2);
960
                    }
961
                    if ($sec) {
962
                        if ($pure_data) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pure_data does not seem to be defined for all execution paths leading up to this point.
Loading history...
963
                            $r[api_strtolower($sec)] .= $f[$i];
964
                        } else {
965
                            if (api_strtolower($sec) == 'course_description') { // A special case.
966
                                $r[api_strtolower($sec)] = $k;
967
                            } else {
968
                                $r[api_strtolower($sec)][api_strtolower($k)] = $v;
969
                            }
970
                        }
971
                    } else {
972
                        $r[api_strtolower($k)] = $v;
973
                    }
974
                }
975
            }
976
        }
977
978
        return $r;
979
    }
980
981
    /**
982
     * Static function that parses CSV files into simple arrays, based on a function
983
     * by spam at cyber-space dot nl published on php.net (fgetcsv()).
984
     *
985
     * @param	string	Filepath
986
     * @param	string	CSV delimiter
987
     * @param	string	CSV enclosure
988
     * @param	bool	Might one field name happen more than once on the same line? (then split by comma in the values)
989
     *
990
     * @return array Simple structured array
991
     */
992
    public function parse_csv_file($f, $delim = ',', $enclosure = '"', $multiples = false)
993
    {
994
        $data = @file_get_contents($f);
995
        $data = api_convert_encoding($data, api_get_system_encoding(), $this->config_encoding);
996
        $enclosed = false;
997
        $fldcount = 0;
998
        $linecount = 0;
999
        $fldval = '';
1000
        for ($i = 0; $i < strlen($data); $i++) {
1001
            $chr = $data[$i];
1002
            switch ($chr) {
1003
                case $enclosure:
1004
                    if ($enclosed && $data[$i + 1] == $enclosure) {
1005
                        $fldval .= $chr;
1006
                        $i++; // Skip the next character.
1007
                    } else {
1008
                        $enclosed = !$enclosed;
1009
                    }
1010
                    break;
1011
                case $delim:
1012
                    if (!$enclosed) {
1013
                        $ret_array[$linecount][$fldcount++] = $fldval;
1014
                        $fldval = '';
1015
                    } else {
1016
                        $fldval .= $chr;
1017
                    }
1018
                    break;
1019
                case "\r":
1020
                    if (!$enclosed && $data[$i + 1] == "\n") {
1021
                        break;
1022
                    }
1023
                    // no break
1024
                case "\n":
1025
                    if (!$enclosed) {
1026
                        $ret_array[$linecount++][$fldcount] = $fldval;
1027
                        $fldcount = 0;
1028
                        $fldval = '';
1029
                    } else {
1030
                        $fldval .= $chr;
1031
                    }
1032
                    break;
1033
                case "\\r":
1034
                    if (!$enclosed && $data[$i + 1] == "\\n") {
1035
                        break;
1036
                    }
1037
                    // no break
1038
                case "\\n":
1039
                    if (!$enclosed) {
1040
                        $ret_array[$linecount++][$fldcount] = $fldval;
1041
                        $fldcount = 0;
1042
                        $fldval = '';
1043
                    } else {
1044
                        $fldval .= $chr;
1045
                    }
1046
                    break;
1047
                default:
1048
                    $fldval .= $chr;
1049
            }
1050
        }
1051
        if ($fldval) {
1052
            $ret_array[$linecount][$fldcount] = $fldval;
1053
        }
1054
        // Transform the array to use the first line as titles.
1055
        $titles = [];
1056
        $ret_ret_array = [];
1057
        foreach ($ret_array as $line_idx => $line) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ret_array does not seem to be defined for all execution paths leading up to this point.
Loading history...
1058
            if ($line_idx == 0) {
1059
                $titles = $line;
1060
            } else {
1061
                $ret_ret_array[$line_idx] = [];
1062
                foreach ($line as $idx => $val) {
1063
                    if ($multiples && !empty($ret_ret_array[$line_idx][api_strtolower($titles[$idx])])) {
1064
                        $ret_ret_array[$line_idx][api_strtolower($titles[$idx])] .= ','.$val;
1065
                    } else {
1066
                        $ret_ret_array[$line_idx][api_strtolower($titles[$idx])] = $val;
1067
                    }
1068
                }
1069
            }
1070
        }
1071
1072
        return $ret_ret_array;
1073
    }
1074
}
1075