1<?php
2
3/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
4
5require_once './Services/User/classes/class.ilObjUser.php';
6require_once "Services/Mail/classes/class.ilMailbox.php";
7require_once "Services/Mail/classes/class.ilFormatMail.php";
8require_once 'Services/Contact/BuddySystem/classes/class.ilBuddySystem.php';
9
10/**
11* @author Jens Conze
12* @version $Id$
13* @ilCtrl_Calls ilMailSearchCoursesGUI: ilBuddySystemGUI
14* @ingroup ServicesMail
15*/
16class ilMailSearchCoursesGUI
17{
18    /**
19     * @var ilTemplate
20     */
21    protected $tpl;
22
23    /**
24     * @var ilCtrl
25     */
26    protected $ctrl;
27
28    /**
29     * @var ilLanguage
30     */
31    protected $lng;
32
33    /**
34     * @var ilObjUser
35     */
36    protected $user;
37
38    /**
39     * @var ilErrorHandling
40     */
41    protected $error;
42
43    /**
44     * @var ilRbacSystem
45     */
46    protected $rbacsystem;
47
48    /**
49     * @var ilRbacReview
50     */
51    protected $rbacreview;
52
53    /**
54     * @var ilTree
55     */
56    protected $tree;
57
58    /**
59     * @var ilObjectDataCache
60     */
61    protected $cache;
62
63    /**
64     * @var ilFormatMail
65     */
66    protected $umail;
67
68    /**
69     * @var bool
70     */
71    protected $mailing_allowed;
72
73    public function __construct($wsp_access_handler = null, $wsp_node_id = null)
74    {
75        global $DIC;
76
77        $this->tpl = $DIC['tpl'];
78        $this->ctrl = $DIC['ilCtrl'];
79        $this->lng = $DIC['lng'];
80        $this->user = $DIC['ilUser'];
81        $this->error = $DIC['ilErr'];
82        $this->rbacsystem = $DIC['rbacsystem'];
83        $this->rbacreview = $DIC['rbacreview'];
84        $this->tree = $DIC['tree'];
85        $this->cache = $DIC['ilObjDataCache'];
86
87        // personal workspace
88        $this->wsp_access_handler = $wsp_access_handler;
89        $this->wsp_node_id = $wsp_node_id;
90
91        // check if current user may send mails
92        include_once "Services/Mail/classes/class.ilMail.php";
93        $mail = new ilMail($this->user->getId());
94        $this->mailing_allowed = $this->rbacsystem->checkAccess('internal_mail', $mail->getMailObjectReferenceId());
95
96        $this->ctrl->saveParameter($this, "mobj_id");
97        $this->ctrl->saveParameter($this, "ref");
98
99        $this->umail = new ilFormatMail($this->user->getId());
100    }
101
102    public function executeCommand()
103    {
104        $forward_class = $this->ctrl->getNextClass($this);
105        switch ($forward_class) {
106            case 'ilbuddysystemgui':
107                if (!ilBuddySystem::getInstance()->isEnabled()) {
108                    $this->error->raiseError($this->lng->txt('msg_no_perm_read'), $this->error->MESSAGE);
109                }
110
111                require_once 'Services/Contact/BuddySystem/classes/class.ilBuddySystemGUI.php';
112                $this->ctrl->saveParameter($this, 'search_crs');
113                $this->ctrl->setReturn($this, 'showMembers');
114                $this->ctrl->forwardCommand(new ilBuddySystemGUI());
115                break;
116
117            default:
118                if (!($cmd = $this->ctrl->getCmd())) {
119                    $cmd = "showMyCourses";
120                }
121
122                $this->$cmd();
123                break;
124        }
125        return true;
126    }
127
128    public function mail()
129    {
130        if ($_GET["view"] == "mycourses") {
131            $ids = ((int) $_GET['search_crs']) ? array((int) $_GET['search_crs']) : $_POST['search_crs'];
132
133            if ($ids) {
134                $this->mailCourses();
135            } else {
136                ilUtil::sendInfo($this->lng->txt("mail_select_course"));
137                $this->showMyCourses();
138            }
139        } elseif ($_GET["view"] == "crs_members") {
140            $ids = ((int) $_GET['search_members']) ? array((int) $_GET['search_members']) : $_POST['search_members'];
141            if ($ids) {
142                $this->mailMembers();
143            } else {
144                ilUtil::sendInfo($this->lng->txt("mail_select_one_entry"));
145                $this->showMembers();
146            }
147        } else {
148            $this->showMyCourses();
149        }
150    }
151
152    public function mailCourses()
153    {
154        $members = array();
155
156        if (!is_array($old_mail_data = $this->umail->getSavedData())) {
157            $this->umail->savePostData(
158                $this->user->getId(),
159                array(),
160                "",
161                "",
162                "",
163                "",
164                "",
165                "",
166                "",
167                ""
168            );
169        }
170
171        require_once './Services/Object/classes/class.ilObject.php';
172        require_once 'Services/Mail/classes/Address/Type/class.ilMailRoleAddressType.php';
173        $ids = ((int) $_GET['search_crs']) ? array((int) $_GET['search_crs']) : $_POST['search_crs'];
174
175        foreach ($ids as $crs_id) {
176            $ref_ids = ilObject::_getAllReferences($crs_id);
177
178            foreach ($ref_ids as $ref_id) {
179                $roles = $this->rbacreview->getAssignableChildRoles($ref_id);
180                foreach ($roles as $role) {
181                    if (substr($role['title'], 0, 14) == 'il_crs_member_' ||
182                        substr($role['title'], 0, 13) == 'il_crs_tutor_' ||
183                        substr($role['title'], 0, 13) == 'il_crs_admin_') {
184                        if (isset($old_mail_data['rcp_to']) &&
185                           trim($old_mail_data['rcp_to']) != '') {
186                            $rcpt = (new \ilRoleMailboxAddress($role['obj_id']))->value();
187                            if (!$this->umail->existsRecipient($rcpt, (string) $old_mail_data['rcp_to'])) {
188                                array_push($members, $rcpt);
189                            }
190                        } else {
191                            array_push($members, (new \ilRoleMailboxAddress($role['obj_id']))->value());
192                        }
193                    }
194                }
195            }
196        }
197
198        if (count($members)) {
199            $mail_data = $this->umail->appendSearchResult($members, 'to');
200        } else {
201            $mail_data = $this->umail->getSavedData();
202        }
203
204        $this->umail->savePostData(
205            $mail_data["user_id"],
206            $mail_data["attachments"],
207            $mail_data["rcp_to"],
208            $mail_data["rcp_cc"],
209            $mail_data["rcp_bcc"],
210            $mail_data["m_email"],
211            $mail_data["m_subject"],
212            $mail_data["m_message"],
213            $mail_data["use_placeholders"],
214            $mail_data['tpl_ctx_id'],
215            $mail_data['tpl_ctx_params']
216        );
217
218        #$this->ctrl->returnToParent($this);
219        ilUtil::redirect("ilias.php?baseClass=ilMailGUI&type=search_res");
220    }
221
222    public function mailMembers()
223    {
224        $members = array();
225
226        if (!is_array($this->umail->getSavedData())) {
227            $this->umail->savePostData(
228                $this->user->getId(),
229                array(),
230                "",
231                "",
232                "",
233                "",
234                "",
235                "",
236                "",
237                ""
238            );
239        }
240
241        $ids = ((int) $_GET['search_members']) ? array((int) $_GET['search_members']) : $_POST['search_members'];
242
243        foreach ($ids as $member) {
244            $login = ilObjUser::_lookupLogin($member);
245            array_push($members, $login);
246        }
247        $mail_data = $this->umail->appendSearchResult($members, "to");
248
249        $this->umail->savePostData(
250            $mail_data["user_id"],
251            $mail_data["attachments"],
252            $mail_data["rcp_to"],
253            $mail_data["rcp_cc"],
254            $mail_data["rcp_bcc"],
255            $mail_data["m_email"],
256            $mail_data["m_subject"],
257            $mail_data["m_message"],
258            $mail_data["use_placeholders"],
259            $mail_data['tpl_ctx_id'],
260            $mail_data['tpl_ctx_params']
261        );
262
263        #$this->ctrl->returnToParent($this);
264        ilUtil::redirect("ilias.php?baseClass=ilMailGUI&type=search_res");
265    }
266
267    /**
268     * Cancel action
269     */
270    public function cancel()
271    {
272        if ($_GET["view"] == "mycourses" &&
273            $_GET["ref"] == "mail") {
274            $this->ctrl->returnToParent($this);
275        } else {
276            $this->showMyCourses();
277        }
278    }
279
280    /**
281     * Show user's courses
282     */
283    public function showMyCourses()
284    {
285        include_once 'Modules/Course/classes/class.ilCourseParticipants.php';
286
287        $this->tpl->setTitle($this->lng->txt('mail_addressbook'));
288
289        $searchTpl = new ilTemplate('tpl.mail_search_template.html', true, true, 'Services/Contact');
290
291        $_GET['view'] = 'mycourses';
292
293        $this->lng->loadLanguageModule('crs');
294
295        include_once 'Services/Contact/classes/class.ilMailSearchCoursesTableGUI.php';
296        $table = new ilMailSearchCoursesTableGUI($this, "crs", $_GET["ref"]);
297        $table->setId('search_crs_tbl');
298        include_once 'Modules/Course/classes/class.ilCourseParticipants.php';
299        $crs_ids = ilCourseParticipants::_getMembershipByType($this->user->getId(), 'crs');
300        $counter = 0;
301        $tableData = array();
302        if (is_array($crs_ids) && count($crs_ids) > 0) {
303            $num_courses_hidden_members = 0;
304            include_once("./Services/UIComponent/AdvancedSelectionList/classes/class.ilAdvancedSelectionListGUI.php");
305            foreach ($crs_ids as $crs_id) {
306                /**
307                 * @var $oTmpCrs ilObjCourse
308                 */
309                $oTmpCrs = ilObjectFactory::getInstanceByObjId($crs_id);
310
311                $isOffline = !$oTmpCrs->isActivated();
312                $hasUntrashedReferences = ilObject::_hasUntrashedReference($crs_id);
313                $showMemberListEnabled = (boolean) $oTmpCrs->getShowMembers();
314                $ref_ids = array_keys(ilObject::_getAllReferences($crs_id));
315                $isPrivilegedUser = $this->rbacsystem->checkAccess('write', $ref_ids[0]);
316
317                if ($hasUntrashedReferences && ((!$isOffline && $showMemberListEnabled) || $isPrivilegedUser)) {
318                    $oCrsParticipants = ilCourseParticipants::_getInstanceByObjId($crs_id);
319                    $crs_members = $oCrsParticipants->getParticipants();
320
321                    foreach ($crs_members as $key => $member) {
322                        $tmp_usr = new ilObjUser($member);
323                        if (!$tmp_usr->getActive()) {
324                            unset($crs_members[$key]);
325                        }
326                    }
327
328                    $hiddenMembers = false;
329                    if ((int) $oTmpCrs->getShowMembers() == $oTmpCrs->SHOW_MEMBERS_DISABLED) {
330                        ++$num_courses_hidden_members;
331                        $hiddenMembers = true;
332                    }
333                    unset($oTmpCrs);
334
335                    $ref_ids = ilObject::_getAllReferences($crs_id);
336                    $ref_id = current($ref_ids);
337                    $path_arr = $this->tree->getPathFull($ref_id, $this->tree->getRootId());
338                    $path_counter = 0;
339                    $path = '';
340                    foreach ($path_arr as $data) {
341                        if ($path_counter++) {
342                            $path .= " -> ";
343                        }
344                        $path .= $data['title'];
345                    }
346                    $path = $this->lng->txt('path') . ': ' . $path;
347
348                    $current_selection_list = new ilAdvancedSelectionListGUI();
349                    $current_selection_list->setListTitle($this->lng->txt("actions"));
350                    $current_selection_list->setId("act_" . $counter);
351
352                    $this->ctrl->setParameter($this, 'search_crs', $crs_id);
353                    $this->ctrl->setParameter($this, 'view', 'mycourses');
354
355                    if ($_GET["ref"] == "mail") {
356                        if ($this->mailing_allowed) {
357                            $current_selection_list->addItem($this->lng->txt("mail_members"), '', $this->ctrl->getLinkTarget($this, "mail"));
358                        }
359                    } elseif ($_GET["ref"] == "wsp") {
360                        $current_selection_list->addItem($this->lng->txt("wsp_share_with_members"), '', $this->ctrl->getLinkTarget($this, "share"));
361                    }
362                    $current_selection_list->addItem($this->lng->txt("mail_list_members"), '', $this->ctrl->getLinkTarget($this, "showMembers"));
363
364                    $this->ctrl->clearParameters($this);
365
366                    $rowData = array(
367                        "CRS_ID" => $crs_id,
368                        "CRS_NAME" => $this->cache->lookupTitle($crs_id),
369                        "CRS_NO_MEMBERS" => count($crs_members),
370                        "CRS_PATH" => $path,
371                        'COMMAND_SELECTION_LIST' => $current_selection_list->getHTML(),
372                        "hidden_members" => $hiddenMembers,
373                    );
374                    $counter++;
375                    $tableData[] = $rowData;
376                }
377            }
378
379            if ($num_courses_hidden_members > 0) {
380                $searchTpl->setCurrentBlock('caption_block');
381                $searchTpl->setVariable('TXT_LIST_MEMBERS_NOT_AVAILABLE', $this->lng->txt('mail_crs_list_members_not_available'));
382                $searchTpl->parseCurrentBlock();
383            }
384        }
385
386        $searchTpl->setVariable('TXT_MARKED_ENTRIES', $this->lng->txt('marked_entries'));
387
388        $table->setData($tableData);
389        if ($_GET['ref'] == 'mail') {
390            $this->tpl->setVariable('BUTTON_CANCEL', $this->lng->txt('cancel'));
391        }
392
393        $searchTpl->setVariable('TABLE', $table->getHtml());
394        $this->tpl->setContent($searchTpl->get());
395
396        if ($_GET["ref"] != "wsp") {
397            $this->tpl->printToStdout();
398        }
399    }
400
401    /**
402     * Show course members
403     */
404    public function showMembers()
405    {
406        include_once 'Modules/Course/classes/class.ilCourseParticipants.php';
407
408        if ($_GET["search_crs"] != "") {
409            $_POST["search_crs"] = explode(",", $_GET["search_crs"]);
410            $_GET["search_crs"] = "";
411        } elseif ($_SESSION["search_crs"] != "") {
412            $_POST["search_crs"] = explode(",", $_SESSION["search_crs"]);
413            $_SESSION["search_crs"] = "";
414        }
415
416        if (is_array($_POST['search_crs'])) {
417            $_POST['search_crs'] = array_filter(array_map('intval', $_POST['search_crs']));
418        }
419
420        if (!is_array($_POST["search_crs"]) ||
421            count($_POST["search_crs"]) == 0) {
422            ilUtil::sendInfo($this->lng->txt("mail_select_course"));
423            $this->showMyCourses();
424        } else {
425            foreach ($_POST['search_crs'] as $crs_id) {
426                $oTmpCrs = ilObjectFactory::getInstanceByObjId($crs_id);
427                if ($oTmpCrs->getShowMembers() == $oTmpCrs->SHOW_MEMBERS_DISABLED) {
428                    unset($_POST['search_crs']);
429                    ilUtil::sendInfo($this->lng->txt('mail_crs_list_members_not_available_for_at_least_one_crs'));
430                    return $this->showMyCourses();
431                }
432                unset($oTmpCrs);
433            }
434
435            $this->tpl->setTitle($this->lng->txt("mail_addressbook"));
436
437            $this->ctrl->setParameter($this, "view", "crs_members");
438            if ($_GET["ref"] != "") {
439                $this->ctrl->setParameter($this, "ref", $_GET["ref"]);
440            }
441            if (is_array($_POST["search_crs"])) {
442                $this->ctrl->setParameter($this, "search_crs", implode(",", $_POST["search_crs"]));
443            }
444            $this->tpl->setVariable("ACTION", $this->ctrl->getFormAction($this));
445            $this->ctrl->clearParameters($this);
446
447            $this->lng->loadLanguageModule('crs');
448            include_once 'Services/Contact/classes/class.ilMailSearchCoursesMembersTableGUI.php';
449            $context = $_GET["ref"] ? $_GET["ref"] : "mail";
450            $table = new ilMailSearchCoursesMembersTableGUI($this, 'crs', $context, $_POST["search_crs"]);
451            $tableData = array();
452            $searchTpl = new ilTemplate('tpl.mail_search_template.html', true, true, 'Services/Contact');
453            foreach ($_POST["search_crs"] as $crs_id) {
454                $members_obj = ilCourseParticipants::_getinstanceByObjId($crs_id);
455                $tmp_members = $members_obj->getParticipants();
456                $course_members = ilUtil::_sortIds($tmp_members, 'usr_data', 'lastname', 'usr_id');
457
458                foreach ($course_members as $member) {
459                    $tmp_usr = new ilObjUser($member);
460                    if (!$tmp_usr->getActive()) {
461                        continue;
462                    }
463
464                    $name = ilObjUser::_lookupName($member);
465                    $login = ilObjUser::_lookupLogin($member);
466
467                    $fullname = "";
468                    if (in_array(ilObjUser::_lookupPref($member, 'public_profile'), array("g", 'y'))) {
469                        $fullname = $name['lastname'] . ', ' . $name['firstname'];
470                    }
471
472                    $rowData = array(
473                        'members_id' => $member,
474                        'members_login' => $login,
475                        'members_name' => $fullname,
476                        'members_crs_grp' => $this->cache->lookupTitle($crs_id),
477                        'search_crs' => $crs_id
478                    );
479
480                    if ('mail' == $context && ilBuddySystem::getInstance()->isEnabled()) {
481                        $relation = ilBuddyList::getInstanceByGlobalUser()->getRelationByUserId($member);
482                        $state_name = ilStr::convertUpperCamelCaseToUnderscoreCase($relation->getState()->getName());
483                        $rowData['status'] = '';
484                        if ($member != $this->user->getId()) {
485                            if ($relation->isOwnedByActor()) {
486                                $rowData['status'] = $this->lng->txt('buddy_bs_state_' . $state_name . '_a');
487                            } else {
488                                $rowData['status'] = $this->lng->txt('buddy_bs_state_' . $state_name . '_p');
489                            }
490                        }
491                    }
492
493                    $tableData[] = $rowData;
494                }
495            }
496            $table->setData($tableData);
497
498            if (count($tableData)) {
499                $searchTpl->setVariable("TXT_MARKED_ENTRIES", $this->lng->txt("marked_entries"));
500            }
501
502            $searchTpl->setVariable('TABLE', $table->getHtml());
503            $this->tpl->setContent($searchTpl->get());
504
505            if ($_GET["ref"] != "wsp") {
506                $this->tpl->printToStdout();
507            }
508        }
509    }
510
511    public function share()
512    {
513        if ($_GET["view"] == "mycourses") {
514            $ids = $_REQUEST["search_crs"];
515            if (is_array($ids) && sizeof($ids)) {
516                $this->addPermission($ids);
517            } else {
518                ilUtil::sendInfo($this->lng->txt("mail_select_course"));
519                $this->showMyCourses();
520            }
521        } elseif ($_GET["view"] == "crs_members") {
522            $ids = $_REQUEST["search_members"];
523            if (is_array($ids) && sizeof($ids)) {
524                $this->addPermission($ids);
525            } else {
526                ilUtil::sendInfo($this->lng->txt("mail_select_one_entry"));
527                $this->showMembers();
528            }
529        } else {
530            $this->showMyCourses();
531        }
532    }
533
534    protected function addPermission($a_obj_ids)
535    {
536        if (!is_array($a_obj_ids)) {
537            $a_obj_ids = array($a_obj_ids);
538        }
539
540        $existing = $this->wsp_access_handler->getPermissions($this->wsp_node_id);
541        $added = false;
542        foreach ($a_obj_ids as $object_id) {
543            if (!in_array($object_id, $existing)) {
544                $added = $this->wsp_access_handler->addPermission($this->wsp_node_id, $object_id);
545            }
546        }
547
548        if ($added) {
549            ilUtil::sendSuccess($this->lng->txt("wsp_share_success"), true);
550        }
551        $this->ctrl->redirectByClass("ilworkspaceaccessgui", "share");
552    }
553}
554