1<?php
2/* Copyright (c) 1998-2010 ILIAS open source, Extended GPL, see docs/LICENSE */
3
4include_once "Services/Object/classes/class.ilObject2.php";
5
6/**
7 * Remote object app base class
8*
9* @author Stefan Meyer <meyer@leifos.com>
10* @version $Id$
11*
12* @ingroup ServicesWebServicesECS
13*/
14
15abstract class ilRemoteObjectBase extends ilObject2
16{
17    protected $local_information;
18    protected $remote_link;
19    protected $organization;
20    protected $mid;
21    protected $auth_hash = '';
22
23    protected $realm_plain = '';
24
25    const MAIL_SENDER = 6;
26    const OBJECT_OWNER = 6;
27
28    /**
29     * Constructor
30     *
31     * @param int $a_id
32     * @param bool $a_call_by_reference
33     * @return ilObject
34     */
35    public function __construct($a_id = 0, $a_call_by_reference = true)
36    {
37        global $DIC;
38
39        $ilDB = $DIC['ilDB'];
40
41        parent::__construct($a_id, $a_call_by_reference);
42        $this->db = $ilDB;
43    }
44
45    /**
46     * Get instance by ilECSEvent(QueueReader) type
47     *
48     * @param int $a_type
49     * @return ilRemoteObjectBase
50     */
51    public static function getInstanceByEventType($a_type)
52    {
53        switch ($a_type) {
54            case ilECSEventQueueReader::TYPE_REMOTE_COURSE:
55                include_once 'Modules/RemoteCourse/classes/class.ilObjRemoteCourse.php';
56                return new ilObjRemoteCourse();
57
58            case ilECSEventQueueReader::TYPE_REMOTE_CATEGORY:
59                include_once 'Modules/RemoteCategory/classes/class.ilObjRemoteCategory.php';
60                return new ilObjRemoteCategory();
61
62            case ilECSEventQueueReader::TYPE_REMOTE_FILE:
63                include_once 'Modules/RemoteFile/classes/class.ilObjRemoteFile.php';
64                return new ilObjRemoteFile();
65
66            case ilECSEventQueueReader::TYPE_REMOTE_GLOSSARY:
67                include_once 'Modules/RemoteGlossary/classes/class.ilObjRemoteGlossary.php';
68                return new ilObjRemoteGlossary();
69
70            case ilECSEventQueueReader::TYPE_REMOTE_GROUP:
71                include_once 'Modules/RemoteGroup/classes/class.ilObjRemoteGroup.php';
72                return new ilObjRemoteGroup();
73
74            case ilECSEventQueueReader::TYPE_REMOTE_LEARNING_MODULE:
75                include_once 'Modules/RemoteLearningModule/classes/class.ilObjRemoteLearningModule.php';
76                return new ilObjRemoteLearningModule();
77
78            case ilECSEventQueueReader::TYPE_REMOTE_WIKI:
79                include_once 'Modules/RemoteWiki/classes/class.ilObjRemoteWiki.php';
80                return new ilObjRemoteWiki();
81
82            case ilECSEventQueueReader::TYPE_REMOTE_TEST:
83                include_once 'Modules/RemoteTest/classes/class.ilObjRemoteTest.php';
84                return new ilObjRemoteTest();
85        }
86    }
87
88    public function beforeCreate()
89    {
90        $this->setOwner(self::OBJECT_OWNER);
91        return parent::beforeCreate();
92    }
93
94    /**
95     * Get db table name
96     *
97     * @return string
98     */
99    abstract protected function getTableName();
100
101    /**
102     * Get ECS resource identifier, e.g. "/campusconnect/courselinks"
103     *
104     * @return string
105     */
106    abstract protected function getECSObjectType();
107
108    /**
109     * lookup organization
110     *
111     * @param int $a_obj_id
112     * @return string
113     */
114    public static function _lookupOrganization($a_obj_id)
115    {
116        global $DIC;
117
118        $ilDB = $DIC['ilDB'];
119
120        $query = "SELECT organization FROM " . static::DB_TABLE_NAME .
121            " WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " ";
122        $res = $ilDB->query($query);
123        while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
124            return $row->organization;
125        }
126        return '';
127    }
128
129    /**
130     * Get realm plain
131     * @return type
132     */
133    public function getRealmPlain()
134    {
135        return $this->realm_plain;
136    }
137
138    /**
139     * set organization
140     *
141     * @param string $a_organization
142     */
143    public function setOrganization($a_organization)
144    {
145        $this->organization = $a_organization;
146    }
147
148    /**
149     * get organization
150     *
151     * @return string
152     */
153    public function getOrganization()
154    {
155        return $this->organization;
156    }
157
158    /**
159     * get local information
160     *
161     * @return string
162     */
163    public function getLocalInformation()
164    {
165        return $this->local_information;
166    }
167
168    /**
169     * set local information
170     *
171     * @param string $a_info
172     */
173    public function setLocalInformation($a_info)
174    {
175        $this->local_information = $a_info;
176    }
177
178    /**
179     * get mid
180     *
181     * @return int
182     */
183    public function getMID()
184    {
185        return $this->mid;
186    }
187
188    /**
189     * set mid
190     *
191     * @param int $a_mid mid
192     */
193    public function setMID($a_mid)
194    {
195        $this->mid = $a_mid;
196    }
197
198    /**
199     * lookup owner mid
200     *
201     * @param int $a_obj_id obj_id
202     * @return int
203     */
204    public static function _lookupMID($a_obj_id)
205    {
206        global $DIC;
207
208        $ilDB = $DIC['ilDB'];
209
210        $query = "SELECT mid FROM " . static::DB_TABLE_NAME .
211            " WHERE obj_id = " . $ilDB->quote($a_obj_id, 'integer') . " ";
212        $res = $ilDB->query($query);
213        while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
214            return $row->mid;
215        }
216        return 0;
217    }
218
219    /**
220     * set remote link
221     *
222     * @param string $a_link link to original object
223     */
224    public function setRemoteLink($a_link)
225    {
226        $this->remote_link = $a_link;
227    }
228
229    /**
230     * get remote link
231     *
232     * @return string
233     */
234    public function getRemoteLink()
235    {
236        return $this->remote_link;
237    }
238
239    /**
240     * get full remote link
241     * Including ecs generated hash and auth mode
242     *
243     * @return string
244     * @throws ilECSConnectorException
245     */
246    public function getFullRemoteLink()
247    {
248        global $DIC;
249
250        $ilUser = $DIC['ilUser'];
251
252
253        include_once './Services/WebServices/ECS/classes/class.ilECSImport.php';
254        $server_id = ilECSImport::lookupServerId($this->getId());
255        $server = ilECSSetting::getInstanceByServerId($server_id);
256
257        include_once('./Services/WebServices/ECS/classes/class.ilECSUser.php');
258        $user = new ilECSUser($ilUser);
259        $ecs_user_data = $user->toGET();
260        $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ': Using ecs user data ' . $ecs_user_data);
261
262        // check token mechanism enabled
263        include_once './Services/WebServices/ECS/classes/class.ilECSParticipantSetting.php';
264        $part = new ilECSParticipantSetting($server_id, $this->getMID());
265        if (!$part->isTokenEnabled()) {
266            return $this->getRemoteLink();
267        }
268
269        $auth_hash = $this->createAuthResource($this->getRemoteLink() . $user->toREALM());
270        $ecs_url_hash = 'ecs_hash_url=' . urlencode($server->getServerURI() . '/sys/auths/' . $auth_hash);
271
272        if (strpos($this->getRemoteLink(), '?')) {
273            $link = $this->getRemoteLink() . '&ecs_hash=' . $auth_hash . $ecs_user_data . '&' . $ecs_url_hash;
274        } else {
275            $link = $this->getRemoteLink() . '?ecs_hash=' . $auth_hash . $ecs_user_data . '&' . $ecs_url_hash;
276        }
277        $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ': ECS full link: ' . $link);
278        return $link;
279    }
280
281    /**
282     * create authentication resource on ecs server
283     *
284     * @return bool
285     * @throws ilECSConnectorException
286     */
287    public function createAuthResource($a_plain_realm)
288    {
289        global $DIC;
290
291        $ilLog = $DIC['ilLog'];
292
293        include_once './Services/WebServices/ECS/classes/class.ilECSAuth.php';
294        include_once './Services/WebServices/ECS/classes/class.ilECSConnector.php';
295        include_once './Services/WebServices/ECS/classes/class.ilECSImport.php';
296        include_once './Services/WebServices/ECS/classes/class.ilECSSetting.php';
297
298        try {
299            $server_id = ilECSImport::lookupServerId($this->getId());
300            $import_info = new ilECSImport($server_id, $this->getId());
301
302            $connector = new ilECSConnector(ilECSSetting::getInstanceByServerId($server_id));
303            $auth = new ilECSAuth();
304            $auth->setPid($import_info->getMID());
305            // URL is deprecated
306            $auth->setUrl($this->getRemoteLink());
307            $realm = sha1($a_plain_realm);
308            $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ': Using realm ' . $a_plain_realm);
309            $auth->setRealm($realm);
310            $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ' Mid is ' . $this->getMID());
311            $this->auth_hash = $connector->addAuth(@json_encode($auth), $this->getMID());
312            return $this->auth_hash;
313        } catch (ilECSConnectorException $exc) {
314            $ilLog->write(__METHOD__ . ': Caught error from ECS Auth resource: ' . $exc->getMessage());
315            return false;
316        }
317    }
318
319    /**
320     * Create remote object
321     */
322    public function doCreate()
323    {
324        global $DIC;
325
326        $ilDB = $DIC['ilDB'];
327
328        $fields = array(
329            "obj_id" => array("integer", $this->getId()),
330            "local_information" => array("text", ""),
331            "remote_link" => array("text", ""),
332            "mid" => array("integer", 0),
333            "organization" => array("text", "")
334        );
335
336        $this->doCreateCustomFields($fields);
337
338        $ilDB->insert($this->getTableName(), $fields);
339    }
340
341    /**
342     * Add custom fields to db insert
343     * @param array $a_fields
344     */
345    protected function doCreateCustomFields(array &$a_fields)
346    {
347    }
348
349    /**
350     * Update remote object
351     */
352    public function doUpdate()
353    {
354        global $DIC;
355
356        $ilDB = $DIC['ilDB'];
357
358        $fields = array(
359            "local_information" => array("text", $this->getLocalInformation()),
360            "remote_link" => array("text", $this->getRemoteLink()),
361            "mid" => array("integer", $this->getMID()),
362            "organization" => array("text", $this->getOrganization())
363        );
364
365        $this->doUpdateCustomFields($fields);
366
367        $where = array("obj_id" => array("integer", $this->getId()));
368
369        $ilDB->update($this->getTableName(), $fields, $where);
370    }
371
372    /**
373     * Add custom fields to db update
374     * @param array $a_fields
375     */
376    protected function doUpdateCustomFields(array &$a_fields)
377    {
378    }
379
380    /**
381     * Delete remote object
382     */
383    public function doDelete()
384    {
385        global $DIC;
386
387        $ilDB = $DIC['ilDB'];
388
389        //put here your module specific stuff
390        include_once('./Services/WebServices/ECS/classes/class.ilECSImport.php');
391        ilECSImport::_deleteByObjId($this->getId());
392
393        $query = "DELETE FROM " . $this->getTableName() .
394            " WHERE obj_id = " . $this->db->quote($this->getId(), 'integer') . " ";
395        $ilDB->manipulate($query);
396    }
397
398    /**
399     * read settings
400     */
401    public function doRead()
402    {
403        $query = "SELECT * FROM " . $this->getTableName() .
404            " WHERE obj_id = " . $this->db->quote($this->getId(), 'integer') . " ";
405        $res = $this->db->query($query);
406        while ($row = $res->fetchRow(ilDBConstants::FETCHMODE_OBJECT)) {
407            $this->setLocalInformation($row->local_information);
408            $this->setRemoteLink($row->remote_link);
409            $this->setMID($row->mid);
410            $this->setOrganization($row->organization);
411
412            $this->doReadCustomFields($row);
413        }
414    }
415
416    /**
417     * Read custom fields from db row
418     * @param object $a_row
419     */
420    protected function doReadCustomFields($a_row)
421    {
422    }
423
424    /**
425     * create remote object from ECSContent object
426     *
427     * @param ilECSSetting $a_server
428     * @param object $a_ecs_content object with object settings
429     * @param int $a_owner
430     */
431    public function createFromECSEContent(ilECSSetting $a_server, $a_ecs_content, $a_owner)
432    {
433        $this->create();
434
435        // won't work for personal workspace
436        $this->createReference();
437        $this->setPermissions($a_server->getImportId());
438
439        include_once './Services/WebServices/ECS/classes/class.ilECSUtils.php';
440        $matchable_content = ilECSUtils::getMatchableContent(
441            $this->getECSObjectType(),
442            $a_server->getServerId(),
443            $a_ecs_content,
444            $a_owner
445        );
446
447        include_once './Services/WebServices/ECS/classes/class.ilECSCategoryMapping.php';
448        $this->putInTree(ilECSCategoryMapping::getMatchingCategory(
449            $a_server->getServerId(),
450            $matchable_content
451        ));
452
453        $this->updateFromECSContent($a_server, $a_ecs_content, $a_owner);
454    }
455
456    /**
457     * update remote object settings from ecs content
458     *
459     * @param ilECSSetting $a_server
460     * @param object $a_ecs_content object with object settings
461     * @param int $a_owner
462     */
463    public function updateFromECSContent(ilECSSetting $a_server, $a_ecs_content, $a_owner)
464    {
465        global $DIC;
466
467        $ilLog = $DIC['ilLog'];
468
469        $ilLog->write('updateFromECSContent: ' . print_r($a_ecs_content, true));
470
471        // Get organisation for owner (ObjectListGUI performance)
472        $organisation = null;
473        if ($a_owner) {
474            include_once './Services/WebServices/ECS/classes/class.ilECSUtils.php';
475            $organisation = ilECSUtils::lookupParticipantName($a_owner, $a_server->getServerId());
476            $ilLog->write('found organisation: ' . $organisation);
477        }
478
479        $this->setMID($a_owner); // obsolete?
480        $this->setOrganization($organisation);
481        $this->setTitle($a_ecs_content->title);
482        $this->setDescription($a_ecs_content->abstract);
483        $this->setRemoteLink($a_ecs_content->url);
484
485        $ilLog->write('updateCustomFromECSContent');
486        $this->updateCustomFromECSContent($a_server, $a_ecs_content);
487
488        // we are updating late so custom values can be set
489
490        $ilLog->write('ilObject->update()');
491        $this->update();
492
493        include_once './Services/WebServices/ECS/classes/class.ilECSUtils.php';
494        $matchable_content = ilECSUtils::getMatchableContent(
495            $this->getECSObjectType(),
496            $a_server->getServerId(),
497            $a_ecs_content,
498            $a_owner
499        );
500
501        // rule-based category mapping
502        include_once './Services/WebServices/ECS/classes/class.ilECSCategoryMapping.php';
503        ilECSCategoryMapping::handleUpdate(
504            $this->getId(),
505            $a_server->getServerId(),
506            $matchable_content
507        );
508    }
509
510    /**
511     * Add advanced metadata to json (export)
512     *
513     * @param object $a_json
514     * @param ilECSSetting $a_server
515     * @param array $a_definition
516     * @param int $a_mapping_mode
517     */
518    protected function importMetadataFromJson($a_json, ilECSSetting $a_server, array $a_definition, $a_mapping_mode)
519    {
520        global $DIC;
521
522        $ilLog = $DIC['ilLog'];
523
524        $ilLog->write("importing metadata from json: " . print_r($a_json, true));
525
526        include_once('./Services/WebServices/ECS/classes/class.ilECSDataMappingSettings.php');
527        include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDValues.php');
528        include_once('./Services/AdvancedMetaData/classes/class.ilAdvancedMDFieldDefinition.php');
529
530        $mappings = ilECSDataMappingSettings::getInstanceByServerId($a_server->getServerId());
531        $values_records = ilAdvancedMDValues::getInstancesForObjectId($this->getId(), $this->getType());
532        foreach ($values_records as $values_record) {
533            // this correctly binds group and definitions
534            $values_record->read();
535        }
536
537        $do_save = false;
538
539        foreach ($a_definition as $id => $type) {
540            if (is_array($type)) {
541                $target = $type[1];
542                $type = $type[0];
543            } else {
544                $target = $id;
545            }
546
547            $timePlace = null;
548            if ($field = $mappings->getMappingByECSName($a_mapping_mode, $id)) {
549                // find element in records
550                $adv_md_def = null;
551                foreach ($values_records as $values_record) {
552                    $adv_md_defs = $values_record->getDefinitions();
553                    if (isset($adv_md_defs[$field])) {
554                        $adv_md_def = $adv_md_defs[$field];
555                        break;
556                    }
557                }
558                if (!$adv_md_def) {
559                    continue;
560                }
561
562                $raw_value = $a_json->$target;
563
564                if ($type == ilECSUtils::TYPE_TIMEPLACE) {
565                    if (!is_object($timePlace)) {
566                        include_once('./Services/WebServices/ECS/classes/class.ilECSTimePlace.php');
567                        if (is_object($raw_value)) {
568                            $timePlace = new ilECSTimePlace();
569                            $timePlace->loadFromJSON($raw_value);
570                        } else {
571                            $timePlace = new ilECSTimePlace();
572                        }
573                    }
574                    $raw_value = $timePlace;
575                }
576
577                if ($adv_md_def->importFromECS($type, $raw_value, $id)) {
578                    $do_save = true;
579                }
580            }
581        }
582
583        if ($do_save) {
584            foreach ($values_records as $values_record) {
585                $additional = array();
586                foreach ($values_record->getADTGroup()->getElements() as $element_id => $element) {
587                    if (!$element->isNull()) {
588                        $additional[$element_id] = array("disabled" => array("integer", 1));
589                    }
590                }
591                $values_record->write($additional);
592            }
593        }
594    }
595
596    /**
597     * update remote object settings from ecs content
598     *
599     * @param ilECSSetting $a_server
600     * @param object $a_ecs_content object with object settings
601     */
602    protected function updateCustomFromECSContent(ilECSSetting $a_server, $ecs_content)
603    {
604    }
605
606    /**
607     * Is remote object from same installation?
608     *
609     * @return boolean
610     */
611    public function isLocalObject()
612    {
613        include_once('./Services/WebServices/ECS/classes/class.ilECSExport.php');
614        include_once('./Services/WebServices/ECS/classes/class.ilECSImport.php');
615        if (ilECSExport::_isRemote(
616            ilECSImport::lookupServerId($this->getId()),
617            ilECSImport::_lookupEContentId($this->getId())
618        )) {
619            return false;
620        }
621        return true;
622    }
623
624    /**
625     * Handle creation
626     *
627     * called by ilTaskScheduler
628     *
629     * @param ilECSSetting $a_server
630     * @param type $a_econtent_id
631     * @param array $a_mids
632     */
633    public function handleCreate(ilECSSetting $a_server, $a_econtent_id, array $a_mids)
634    {
635        return $this->handleUpdate($a_server, $a_econtent_id, $a_mids);
636    }
637
638    /**
639     * Handle update event
640     *
641     * called by ilTaskScheduler
642     *
643     * @param ilECSSetting $a_server
644     * @param int $a_econtent_id
645     * @param array $a_mids
646     * @return boolean
647     */
648    public function handleUpdate(ilECSSetting $a_server, $a_econtent_id, array $a_mids)
649    {
650        global $DIC;
651
652        $ilLog = $DIC['ilLog'];
653
654        // get content details
655        include_once('./Services/WebServices/ECS/classes/class.ilECSEContentDetails.php');
656        $details = ilECSEContentDetails::getInstance(
657            $a_server->getServerId(),
658            $a_econtent_id,
659            $this->getECSObjectType()
660        );
661        if (!$details instanceof ilECSEContentDetails) {
662            $this->handleDelete($a_server, $a_econtent_id);
663            $ilLog->write(__METHOD__ . ': Handling delete of deprecated remote object. DONE');
664            return;
665        }
666
667        $ilLog->write(__METHOD__ . ': Receivers are ' . print_r($details->getReceivers(), true));
668        $ilLog->write(__METHOD__ . ': Senders are ' . print_r($details->getSenders(), true));
669
670        // check owner (sender mid)
671        include_once('./Services/WebServices/ECS/classes/class.ilECSParticipantSettings.php');
672        if (!ilECSParticipantSettings::getInstanceByServerId($a_server->getServerId())->isImportAllowed($details->getSenders())) {
673            $ilLog->write('Ignoring disabled participant. MID: ' . $details->getOwner());
674            return true;
675        }
676
677        // new mids
678        include_once 'Services/WebServices/ECS/classes/class.ilECSImport.php';
679        include_once 'Services/WebServices/ECS/classes/class.ilECSConnector.php';
680        foreach (array_intersect($a_mids, $details->getReceivers()) as $mid) {
681            try {
682                $connector = new ilECSConnector($a_server);
683                $res = $connector->getResource($this->getECSObjectType(), $a_econtent_id);
684                if ($res->getHTTPCode() == ilECSConnector::HTTP_CODE_NOT_FOUND) {
685                    continue;
686                }
687                $json = $res->getResult();
688                $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ': Received json: ' . print_r($json, true));
689                if (!is_object($json)) {
690                    // try as array (workaround for invalid content)
691                    $json = $json[0];
692                    if (!is_object($json)) {
693                        throw new ilECSConnectorException('invalid json');
694                    }
695                }
696            } catch (ilECSConnectorException $exc) {
697                $ilLog->write(__METHOD__ . ': Error parsing result. ' . $exc->getMessage());
698                $ilLog->logStack();
699                return false;
700            }
701
702            // Update existing
703
704            // Check receiver mid
705            if ($obj_id = ilECSImport::_isImported($a_server->getServerId(), $a_econtent_id, $mid)) {
706                $ilLog->write(__METHOD__ . ': Handling update for existing object');
707                $remote = ilObjectFactory::getInstanceByObjId($obj_id, false);
708                if (!$remote instanceof ilRemoteObjectBase) {
709                    $ilLog->write(__METHOD__ . ': Cannot instantiate remote object. Got object type ' . $remote->getType());
710                    continue;
711                }
712                $remote->updateFromECSContent($a_server, $json, $details->getMySender());
713            } else {
714                $GLOBALS['DIC']['ilLog']->write(__METHOD__ . ': my sender ' . $details->getMySender() . 'vs mid' . $mid);
715
716                $ilLog->write(__METHOD__ . ': Handling create for non existing object');
717                $this->createFromECSEContent($a_server, $json, $details->getMySender());
718
719                // update import status
720                $ilLog->write(__METHOD__ . ': Updating import status');
721                include_once('./Services/WebServices/ECS/classes/class.ilECSImport.php');
722                $import = new ilECSImport($a_server->getServerId(), $this->getId());
723                $import->setEContentId($a_econtent_id);
724                // Store receiver mid
725                $import->setMID($mid);
726                $import->save();
727
728                $ilLog->write(__METHOD__ . ': Sending notification');
729                $this->sendNewContentNotification($a_server->getServerId());
730            }
731        }
732
733        $ilLog->write(__METHOD__ . ': done');
734        return true;
735    }
736
737    /**
738     * send notifications about new EContent
739     */
740    protected function sendNewContentNotification($a_server_id)
741    {
742        include_once('Services/WebServices/ECS/classes/class.ilECSSetting.php');
743        $settings = ilECSSetting::getInstanceByServerId($a_server_id);
744        if (!count($rcps = $settings->getEContentRecipients())) {
745            return;
746        }
747
748        include_once('./Services/Mail/classes/class.ilMail.php');
749        include_once('./Services/Language/classes/class.ilLanguageFactory.php');
750
751        $lang = ilLanguageFactory::_getLanguage();
752        $lang->loadLanguageModule('ecs');
753
754        $mail = new ilMail(self::MAIL_SENDER);
755        $message = $lang->txt('ecs_' . $this->getType() . '_created_body_a') . "\n\n";
756        $message .= $lang->txt('title') . ': ' . $this->getTitle() . "\n";
757        if (strlen($desc = $this->getDescription())) {
758            $message .= $lang->txt('desc') . ': ' . $desc . "\n";
759        }
760
761        include_once('./Services/Link/classes/class.ilLink.php');
762        $href = ilLink::_getStaticLink($this->getRefId(), $this->getType(), true);
763        $message .= $lang->txt("perma_link") . ': ' . $href . "\n\n";
764        $message .= ilMail::_getAutoGeneratedMessageString();
765
766        $mail->sendMail(
767            $settings->getEContentRecipientsAsString(),
768            '',
769            '',
770            $lang->txt('ecs_new_econtent_subject'),
771            $message,
772            array(),
773            array('normal')
774        );
775    }
776
777    /**
778     * Handle delete event
779     *
780     * called by ilTaskScheduler
781     *
782     * @param ilECSSetting $a_server
783     * @param int $a_econtent_id
784     * @param int $a_mid
785     * @return boolean
786     */
787    public function handleDelete(ilECSSetting $a_server, $a_econtent_id, $a_mid = 0)
788    {
789        global $DIC;
790
791        $tree = $DIC['tree'];
792        $ilLog = $DIC['ilLog'];
793
794
795        include_once('./Services/WebServices/ECS/classes/class.ilECSImport.php');
796
797        // there is no information about the original mid anymore.
798        // Therefor delete any remote objects with given econtent id
799        $obj_ids = ilECSImport::_lookupObjIds($a_server->getServerId(), $a_econtent_id);
800        $ilLog->write(__METHOD__ . ': Received obj_ids ' . print_r($obj_ids, true));
801
802        foreach ($obj_ids as $obj_id) {
803            $references = ilObject::_getAllReferences($obj_id);
804            foreach ($references as $ref_id) {
805                if ($tmp_obj = ilObjectFactory::getInstanceByRefId($ref_id, false)) {
806                    $ilLog->write(__METHOD__ . ': Deleting obsolete remote course: ' . $tmp_obj->getTitle());
807                    $tmp_obj->delete();
808                    $tree->deleteTree($tree->getNodeData($ref_id));
809                }
810                unset($tmp_obj);
811            }
812        }
813        return true;
814    }
815
816    /**
817     * Get all available resources
818     *
819     * @param ilECSSetting $a_server
820     * @param bool $a_sender_only
821     * @return array
822     */
823    public function getAllResourceIds(ilECSSetting $a_server, $a_sender_only = false)
824    {
825        global $DIC;
826
827        $ilLog = $DIC['ilLog'];
828
829        try {
830            include_once './Services/WebServices/ECS/classes/class.ilECSConnector.php';
831            $connector = new ilECSConnector($a_server);
832            $connector->addHeader('X-EcsQueryStrings', $a_sender_only ? 'sender=true' : 'all=true'); // #11301
833            $list = $connector->getResourceList($this->getECSObjectType());
834            if ($list instanceof ilECSResult) {
835                return $list->getResult()->getLinkIds();
836            }
837        } catch (ilECSConnectorException $exc) {
838            $ilLog->write(__METHOD__ . ': Error getting resource list. ' . $exc->getMessage());
839        }
840    }
841}
842