1<?php
2/*
3    +-----------------------------------------------------------------------------+
4    | ILIAS open source                                                           |
5    +-----------------------------------------------------------------------------+
6    | Copyright (c) 1998-2006 ILIAS open source, University of Cologne            |
7    |                                                                             |
8    | This program is free software; you can redistribute it and/or               |
9    | modify it under the terms of the GNU General Public License                 |
10    | as published by the Free Software Foundation; either version 2              |
11    | of the License, or (at your option) any later version.                      |
12    |                                                                             |
13    | This program is distributed in the hope that it will be useful,             |
14    | but WITHOUT ANY WARRANTY; without even the implied warranty of              |
15    | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
16    | GNU General Public License for more details.                                |
17    |                                                                             |
18    | You should have received a copy of the GNU General Public License           |
19    | along with this program; if not, write to the Free Software                 |
20    | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. |
21    +-----------------------------------------------------------------------------+
22*/
23
24include_once('Services/PrivacySecurity/classes/class.ilExportFieldsInfo.php');
25include_once('./Services/Membership/classes/Export/class.ilMemberExport.php');
26include_once('Modules/Course/classes/class.ilFSStorageCourse.php');
27include_once('Modules/Group/classes/class.ilFSStorageGroup.php');
28include_once('Modules/Course/classes/Export/class.ilCourseDefinedFieldDefinition.php');
29include_once('Services/User/classes/class.ilUserDefinedFields.php');
30include_once('Services/User/classes/class.ilUserFormSettings.php');
31
32/**
33*
34* @author Stefan Meyer <meyer@leifos.com>
35* @version $Id$
36*
37*
38* @ilCtrl_Calls ilMemberExportGUI:
39* @ingroup ModulesCourse
40*/
41class ilMemberExportGUI
42{
43    private $ref_id;
44    private $obj_id;
45    private $type;
46    private $ctrl;
47    private $tpl;
48    private $lng;
49
50    private $fields_info;
51    private $fss_export = null;
52    /**
53     * @var ilUserFormSettings
54     */
55    private $exportSettings;
56
57    /**
58     * Constructor
59     *
60     * @access public
61     * @param
62     *
63     */
64    public function __construct($a_ref_id)
65    {
66        global $DIC;
67
68        $ilCtrl = $DIC['ilCtrl'];
69        $tpl = $DIC['tpl'];
70        $lng = $DIC['lng'];
71        $ilUser = $DIC['ilUser'];
72        $ilObjDataCache = $DIC['ilObjDataCache'];
73
74        $this->ctrl = $ilCtrl;
75        $this->tpl = $tpl;
76        $this->lng = $lng;
77        $this->lng->loadLanguageModule('ps');
78        $this->ref_id = $a_ref_id;
79        $this->obj_id = $ilObjDataCache->lookupObjId($this->ref_id);
80        $this->type = ilObject::_lookupType($this->obj_id);
81
82        $this->fields_info = ilExportFieldsInfo::_getInstanceByType(ilObject::_lookupType($this->obj_id));
83        $this->initFileSystemStorage();
84    }
85
86    /**
87     * Execute Command
88     *
89     * @access public
90     * @param
91     *
92     */
93    public function executeCommand()
94    {
95        global $DIC;
96
97        $ilAccess = $DIC['ilAccess'];
98        $rbacsystem = $DIC['rbacsystem'];
99
100
101        include_once('Services/PrivacySecurity/classes/class.ilPrivacySettings.php');
102        if (!ilPrivacySettings::_getInstance()->checkExportAccess($this->ref_id)) {
103            ilUtil::sendFailure($this->lng->txt('permission_denied'), true);
104            $this->ctrl->returnToParent($this);
105        }
106
107        $next_class = $this->ctrl->getNextClass($this);
108        $cmd = $this->ctrl->getCmd();
109
110        switch ($next_class) {
111            default:
112                if (!$cmd) {
113                    $cmd = 'show';
114                }
115                $this->$cmd();
116                break;
117        }
118    }
119
120
121    //
122    // export incl. settings
123    //
124
125    protected function initSettingsForm($a_is_excel = false)
126    {
127        // Check user selection
128        $this->exportSettings = new ilUserFormSettings('memexp');
129
130        include_once 'Services/Form/classes/class.ilPropertyFormGUI.php';
131        $form = new ilPropertyFormGUI();
132        $form->setFormAction($this->ctrl->getFormAction($this));
133        $form->setTitle($this->lng->txt('ps_export_settings'));
134
135        if ((bool) $a_is_excel) {
136            $form->addCommandButton('exportExcel', $this->lng->txt('ps_export_excel'));
137        } else {
138            $form->addCommandButton('export', $this->lng->txt('ps_perform_export'));
139        }
140        $form->addCommandButton('show', $this->lng->txt('cancel'));
141
142        // roles
143        $roles = new ilCheckboxGroupInputGUI($this->lng->txt('ps_user_selection'), 'export_members');
144        $roles->addOption(new ilCheckboxOption($this->lng->txt('ps_export_admin'), 'admin'));
145        if ($this->type == 'crs') {
146            $roles->addOption(new ilCheckboxOption($this->lng->txt('ps_export_tutor'), 'tutor'));
147        }
148        $roles->addOption(new ilCheckboxOption($this->lng->txt('ps_export_member'), 'member'));
149        $roles->addOption(new ilCheckboxOption($this->lng->txt('ps_export_sub'), 'subscribers'));
150        $roles->addOption(new ilCheckboxOption($this->lng->txt('ps_export_wait'), 'waiting_list'));
151        $form->addItem($roles);
152
153        $current_roles = array();
154        foreach (array('admin', 'tutor', 'member', 'subscribers', 'waiting_list') as $role) {
155            if ($this->exportSettings->enabled($role)) {
156                $current_roles[] = $role;
157            }
158        }
159        $roles->setValue($current_roles);
160
161        // user data
162        $current_udata = array();
163        $udata = new ilCheckboxGroupInputGUI($this->lng->txt('ps_export_user_data'), 'export_members');
164        $form->addItem($udata);
165
166        // standard fields
167        $this->fields_info->sortExportFields();
168        foreach ($this->fields_info->getFieldsInfo() as $field => $exportable) {
169            if (!$exportable) {
170                continue;
171            }
172            $udata->addOption(new ilCheckboxOption($this->lng->txt($field), $field));
173            if ($this->exportSettings->enabled($field)) {
174                $current_udata[] = $field;
175            }
176        }
177
178        // udf
179        foreach (ilUserDefinedFields::_getInstance()->getExportableFields($this->obj_id) as $field_id => $udf_data) {
180            $field = 'udf_' . $field_id;
181            $udata->addOption(new ilCheckboxOption($udf_data['field_name'], $field));
182            if ($this->exportSettings->enabled($field)) {
183                $current_udata[] = $field;
184            }
185        }
186
187        $udata->setValue($current_udata);
188
189        // course custom data
190        $cdf_fields = ilCourseDefinedFieldDefinition::_getFields($this->obj_id);
191        if (count($cdf_fields)) {
192            $cdf = new ilCheckboxGroupInputGUI($this->lng->txt('ps_' . $this->type . '_user_fields'), 'export_members');
193            $form->addItem($cdf);
194
195            $current_cdf = array();
196            foreach ($cdf_fields as $field_obj) {
197                $field = 'cdf_' . $field_obj->getId();
198                $cdf->addOption(new ilCheckboxOption($field_obj->getName(), $field));
199                if ($this->exportSettings->enabled($field)) {
200                    $current_cdf[] = $field;
201                }
202            }
203
204            $cdf->setValue($current_cdf);
205        }
206
207        // consultation hours
208        include_once './Services/Booking/classes/class.ilBookingEntry.php';
209        if (ilBookingEntry::hasObjectBookingEntries($this->obj_id, $GLOBALS['DIC']['ilUser']->getId())) {
210            $this->lng->loadLanguageModule('dateplaner');
211            $chours = new ilCheckboxInputGUI($this->lng->txt('cal_ch_field_ch'), 'export_members[]');
212            $chours->setValue('consultation_hour');
213            $chours->setChecked($this->exportSettings->enabled('consultation_hour'));
214            $form->addItem($chours);
215        }
216
217        $grp_membr = new ilCheckboxInputGUI($this->lng->txt('crs_members_groups'), 'export_members[]');
218        $grp_membr->setValue('group_memberships');
219        $grp_membr->setChecked($this->exportSettings->enabled('group_memberships'));
220        $form->addItem($grp_membr);
221        return $form;
222    }
223
224    public function initCSV(ilPropertyFormGUI $a_form = null)
225    {
226        if (!$a_form) {
227            $a_form = $this->initSettingsForm();
228        }
229        $this->tpl->setContent($a_form->getHTML());
230    }
231
232    public function initExcel(ilPropertyFormGUI $a_form = null)
233    {
234        if (!$a_form) {
235            $a_form = $this->initSettingsForm(true);
236        }
237        $this->tpl->setContent($a_form->getHTML());
238    }
239
240    /**
241     * Show list of export files
242     *
243     * @access public
244     *
245     */
246    public function show()
247    {
248        global $DIC;
249
250        $ilToolbar = $DIC['ilToolbar'];
251
252        $ilToolbar->addButton(
253            $this->lng->txt('ps_perform_export'),
254            $this->ctrl->getLinkTarget($this, "initCSV")
255        );
256        $ilToolbar->addButton(
257            $this->lng->txt('ps_export_excel'),
258            $this->ctrl->getLinkTarget($this, "initExcel")
259        );
260
261        $this->showFileList();
262    }
263
264    protected function handleIncoming()
265    {
266        $settings = array();
267        $incoming = $_POST['export_members'];
268        if (is_array($incoming)) {
269            foreach ($incoming as $id) {
270                $settings[$id] = true;
271            }
272        }
273
274        // Save (form) settings
275        $this->exportSettings = new ilUserFormSettings('memexp');
276        $this->exportSettings->set($settings);
277        $this->exportSettings->store();
278    }
279
280    /**
281     * Export Create member export file and store it in data directory.
282     *
283     * @access public
284     *
285     */
286    public function export()
287    {
288        $this->handleIncoming();
289
290        $this->export = new ilMemberExport($this->ref_id);
291        $this->export->create();
292
293        $filename = time() . '_participant_export_csv_' . $this->obj_id . '.csv';
294        $this->fss_export->addMemberExportFile($this->export->getCSVString(), $filename);
295
296        $this->ctrl->redirect($this, 'show');
297    }
298
299    public function exportExcel()
300    {
301        $this->handleIncoming();
302
303        $filename = time() . '_participant_export_xls_' . $this->obj_id;
304        $this->fss_export->initMemberExportDirectory();
305        $filepath = $this->fss_export->getMemberExportDirectory() . DIRECTORY_SEPARATOR . $filename;
306
307        $this->export = new ilMemberExport($this->ref_id, ilMemberExport::EXPORT_EXCEL);
308        $this->export->setFilename($filepath);
309        $this->export->create();
310
311        $this->ctrl->redirect($this, 'show');
312    }
313
314    /**
315     * Deliver Data
316     *
317     * @access public
318     * @param
319     *
320     */
321    public function deliverData()
322    {
323        foreach ($this->fss_export->getMemberExportFiles() as $file) {
324            if ($file['name'] == $_SESSION['member_export_filename']) {
325                $content = $this->fss_export->getMemberExportFile($_SESSION['member_export_filename']);
326                ilUtil::deliverData($content, date('Y_m_d_H-i', $file['timest']) .
327                '_member_export_' .
328                $this->obj_id .
329                '.csv', 'text/csv');
330            }
331        }
332    }
333
334    /**
335     * Show file list of available export files
336     *
337     * @access public
338     *
339     */
340    public function showFileList()
341    {
342        include_once 'Services/Membership/classes/Export/class.ilMemberExportFileTableGUI.php';
343        $tbl = new ilMemberExportFileTableGUI($this, 'show', $this->fss_export);
344        $this->tpl->setContent($tbl->getHTML());
345    }
346
347    /**
348     * Download export file
349     *
350     * @access public
351     * @param
352     *
353     */
354    public function downloadExportFile()
355    {
356        $hash = trim($_GET['fl']);
357        if (!$hash) {
358            $this->ctrl->redirect($this, 'show');
359        }
360
361        foreach ($this->fss_export->getMemberExportFiles() as $file) {
362            if (md5($file['name']) == $hash) {
363                $contents = $this->fss_export->getMemberExportFile($file['timest'] . '_participant_export_' .
364                    $file['type'] . '_' . $this->obj_id . '.' . $file['type']);
365
366                // newer export files could be .xlsx
367                if ($file['type'] == 'xls' && !$contents) {
368                    $contents = $this->fss_export->getMemberExportFile($file['timest'] . '_participant_export_' .
369                        $file['type'] . '_' . $this->obj_id . '.xlsx');
370                    $file['type'] = 'xlsx';
371                }
372
373                switch ($file['type']) {
374                    case 'xlsx':
375                        ilUtil::deliverData(
376                            $contents,
377                            date('Y_m_d_H-i' . $file['timest']) . '_member_export_' . $this->obj_id . '.xlsx',
378                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
379                        );
380
381                        // no break
382                    case 'xls':
383                        ilUtil::deliverData(
384                            $contents,
385                            date('Y_m_d_H-i' . $file['timest']) . '_member_export_' . $this->obj_id . '.xls',
386                            'application/vnd.ms-excel'
387                        );
388
389                        // no break
390                    default:
391                    case 'csv':
392                        ilUtil::deliverData($contents, date('Y_m_d_H-i' . $file['timest']) .
393                            '_member_export_' .
394                            $this->obj_id .
395                            '.csv', 'text/csv');
396                        break;
397                }
398                return true;
399            }
400        }
401    }
402
403    /**
404     * Confirm deletion of export files
405     *
406     * @access public
407     * @param
408     *
409     */
410    public function confirmDeleteExportFile()
411    {
412        if (!array_key_exists('id', $_POST) || !is_array($_POST['id']) || !count($_POST['id'])) {
413            ilUtil::sendFailure($this->lng->txt('ps_select_one'), true);
414            $this->ctrl->redirect($this, 'show');
415        }
416
417        include_once('./Services/Utilities/classes/class.ilConfirmationGUI.php');
418        $confirmation_gui = new ilConfirmationGUI();
419        $confirmation_gui->setFormAction($this->ctrl->getFormAction($this));
420        $confirmation_gui->setHeaderText($this->lng->txt('info_delete_sure') /* .' '.$this->lng->txt('ps_delete_export_files') */);
421        $confirmation_gui->setCancel($this->lng->txt('cancel'), 'show');
422        $confirmation_gui->setConfirm($this->lng->txt('delete'), 'deleteExportFile');
423
424        $counter = 0;
425        foreach ($this->fss_export->getMemberExportFiles() as $file) {
426            if (!in_array(md5($file['name']), $_POST['id'])) {
427                continue;
428            }
429
430            $confirmation_gui->addItem(
431                "id[]",
432                md5($file['name']),
433                strtoupper($file['type']) . ' - ' .
434                ilDatePresentation::formatDate(new ilDateTime($file['timest'], IL_CAL_UNIX))
435            );
436        }
437
438        $this->tpl->setContent($confirmation_gui->getHTML());
439    }
440
441    /**
442     * Delete member export files
443     *
444     * @access public
445     * @param
446     *
447     */
448    public function deleteExportFile()
449    {
450        if (!count($_POST['id'])) {
451            $this->ctrl->redirect($this, 'show');
452        }
453
454        $counter = 0;
455        foreach ($this->fss_export->getMemberExportFiles() as $file) {
456            if (!in_array(md5($file['name']), $_POST['id'])) {
457                continue;
458            }
459
460            $ret = $this->fss_export->deleteMemberExportFile($file['timest'] . '_participant_export_' .
461                $file['type'] . '_' . $this->obj_id . '.' . $file['type']);
462
463            //try xlsx if return is false and type is xls
464            if ($file['type'] == "xls" && !$ret) {
465                $this->fss_export->deleteMemberExportFile($file['timest'] . '_participant_export_' .
466                    $file['type'] . '_' . $this->obj_id . '.' . "xlsx");
467            }
468        }
469
470        ilUtil::sendSuccess($this->lng->txt('ps_files_deleted'), true);
471        $this->ctrl->redirect($this, 'show');
472    }
473
474
475    /**
476     * Init file object
477     * @return
478     */
479    protected function initFileSystemStorage()
480    {
481        if ($this->type == 'crs') {
482            $this->fss_export = new ilFSStorageCourse($this->obj_id);
483        }
484        if ($this->type == 'grp') {
485            $this->fss_export = new ilFSStorageGroup($this->obj_id);
486        }
487    }
488}
489