Simulate the imscp/view.php web interface page: trigger events, completion, etc...

@param int $imscpid the imscp instance id
@return array of warnings and status result
@since Moodle 3.0
@throws moodle_exception
347090
public static function view_imscp($imscpid) {
        global $DB, $CFG;
        require_once($CFG->dirroot . "/mod/imscp/lib.php");

        $params = self::validate_parameters(self::view_imscp_parameters(),
                                            array(
                                                'imscpid' => $imscpid
                                            ));
        $warnings = array();

        // Request and permission validation.
        $imscp = $DB->get_record('imscp', array('id' => $params['imscpid']), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($imscp, 'imscp');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        require_capability('mod/imscp:view', $context);

        // Call the imscp/lib API.
        imscp_view($imscp, $course, $cm, $context);

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }
676004
public function execute($respId = null, $orgId = null)
    {
        $batch = $this->getBatch();
        $org   = $this->loader->getOrganization($orgId);

        $changeEventClass = $org->getRespondentChangeEventClass();

        if ($changeEventClass) {
            $event = $this->loader->getEvents()->loadRespondentChangedEvent($changeEventClass);

            if ($event) {
                $respondent = $this->loader->getRespondent(null, $orgId, $respId);

                $batch->addToCounter('respondentsChecked');
                if ($respondent->getReceptionCode()->isSuccess() &&
                        $event->processChangedRespondent($respondent)) {

                    $batch->addToCounter('respondentsChanged');
                }

            }
        }

        $batch->setMessage(
                'respCheck',
                sprintf(
                        $this->_('%d respondents checked, %d respondents were changed.'),
                        $batch->getCounter('respondentsChecked'),
                        $batch->getCounter('respondentsChanged')
                        ));
    }
1285888
def set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None):
    
    global auth, url
    if h_url is None:
        imc_protocol = input(
        "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:")
        if imc_protocol == "1":
            h_url = 'http://'
        else:
            h_url = 'https://'
        imc_server = input("What is the ip address of the IMC server?")
        imc_port = input("What is the port number of the IMC server?")
        imc_user = input("What is the username of the IMC eAPI user?")
        imc_pw = input('''What is the password of the IMC eAPI user?''')
    url = h_url + imc_server + ":" + imc_port
    auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw)
    test_url = '/imcrs'
    f_url = url + test_url
    try:
        r = requests.get(f_url, auth=auth, headers=headers, verify=False)
        print (r.status_code)
        return auth
    # checks for reqeusts exceptions
    except requests.exceptions.RequestException as e:
        print("Error:\n" + str(e))
        print("\n\nThe IMC server address is invalid. Please try again\n\n")
        set_imc_creds()
    if r.status_code != 200:  # checks for valid IMC credentials
        print("Error: \n You're credentials are invalid. Please try again\n\n")
        set_imc_creds()
    else:
        print("You've successfully access the IMC eAPI")
99924
public function query($postId, $comCodes)
    {
        try {
            return $this->bizImpl->query($postId, $comCodes);
        } catch (\Throwable $throwable) {
            throw new SystemException($throwable->getMessage());
        }
    }
406001
public static function delete_entry($entryid) {
        global $PAGE, $DB;

        $params = array('entryid' => $entryid);
        $params = self::validate_parameters(self::delete_entry_parameters(), $params);
        $warnings = array();

        $record = $DB->get_record('data_records', array('id' => $params['entryid']), '*', MUST_EXIST);
        list($database, $course, $cm, $context) = self::validate_database($record->dataid);

        if (data_user_can_manage_entry($record, $database, $context)) {
            data_delete_record($record->id, $database, $course->id, $cm->id);
        } else {
            throw new moodle_exception('noaccess', 'data');
        }

        $result = array(
            'status' => true,
            'warnings' => $warnings
        );
        return $result;
    }
249720
public function channelGetById($cid)
  {
    if(!array_key_exists((string) $cid, $this->channelList()))
    {
      throw new Exception("invalid channelID", 0x300);
    }

    return $this->channelList[intval((string) $cid)];
  }
214834
public static function view_attempt($attemptid, $page, $preflightdata = array()) {

        $warnings = array();

        $params = array(
            'attemptid' => $attemptid,
            'page' => $page,
            'preflightdata' => $preflightdata,
        );
        $params = self::validate_parameters(self::view_attempt_parameters(), $params);
        list($attemptobj, $messages) = self::validate_attempt($params);

        // Log action.
        $attemptobj->fire_attempt_viewed_event();

        // Update attempt page, throwing an exception if $page is not valid.
        if (!$attemptobj->set_currentpage($params['page'])) {
            throw new moodle_quiz_exception($attemptobj->get_quizobj(), 'Out of sequence access');
        }

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }
229304
protected function __bindEvents()
    {
        $server = $this->swoolePort ?? $this->swooleServer;

        $server->on('packet', function(\swoole_server $server, $data, $clientInfo){
            try{
                $this->trigger('packet', [
                    'server'        => $this,
                    'data'          => $data,
                    'clientInfo'    => $clientInfo,
                ], $this, PacketEventParam::class);
            }
            catch(\Throwable $ex)
            {
                App::getBean('ErrorLog')->onException($ex);
            }
        });
        
    }
983038
public function execute() {
        global $CFG;

        // Raise the time limit for each discussion.
        \core_php_time_limit::raise(120);

        $this->recipient = \core_user::get_user($this->get_userid());

        // Create the generic messageinboundgenerator.
        $this->inboundmanager = new \core\message\inbound\address_manager();
        $this->inboundmanager->set_handler('\mod_forum\message\inbound\reply_handler');

        $data = $this->get_custom_data();

        $this->prepare_data((array) $data);

        $markposts = [];
        $errorcount = 0;
        $sentcount = 0;
        $this->log_start("Sending messages to {$this->recipient->username} ({$this->recipient->id})");
        foreach ($this->courses as $course) {
            $coursecontext = \context_course::instance($course->id);
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                // The course is hidden and the user does not have access to it.
                // Permissions may have changed since it was queued.
                continue;
            }
            foreach ($this->courseforums[$course->id] as $forumid) {
                $forum = $this->forums[$forumid];

                $cm = get_fast_modinfo($course)->instances['forum'][$forumid];
                $modcontext = \context_module::instance($cm->id);

                foreach (array_values($this->forumdiscussions[$forumid]) as $discussionid) {
                    $discussion = $this->discussions[$discussionid];

                    if (!forum_user_can_see_discussion($forum, $discussion, $modcontext, $this->recipient)) {
                        // User cannot see this discussion.
                        // Permissions may have changed since it was queued.
                        continue;
                    }

                    if (!\mod_forum\subscriptions::is_subscribed($this->recipient->id, $forum, $discussionid, $cm)) {
                        // The user does not subscribe to this forum as a whole, or to this specific discussion.
                        continue;
                    }

                    foreach ($this->posts[$discussionid] as $post) {
                        if (!forum_user_can_see_post($forum, $discussion, $post, $this->recipient, $cm)) {
                            // User cannot see this post.
                            // Permissions may have changed since it was queued.
                            continue;
                        }

                        if ($this->send_post($course, $forum, $discussion, $post, $cm, $modcontext)) {
                            $this->log("Post {$post->id} sent", 1);
                            // Mark post as read if forum_usermarksread is set off.
                            if (!$CFG->forum_usermarksread) {
                                $markposts[$post->id] = true;
                            }
                            $sentcount++;
                        } else {
                            $this->log("Failed to send post {$post->id}", 1);
                            $errorcount++;
                        }
                    }
                }
            }
        }

        $this->log_finish("Sent {$sentcount} messages with {$errorcount} failures");
        if (!empty($markposts)) {
            if (get_user_preferences('forum_markasreadonnotification', 1, $this->recipient->id) == 1) {
                $this->log_start("Marking posts as read");
                $count = count($markposts);
                forum_tp_mark_posts_read($this->recipient, array_keys($markposts));
                $this->log_finish("Marked {$count} posts as read");
            }
        }
    }
719809
public function subChannelGetById($cid)
  {
    if(!array_key_exists((int) $cid, $this->subChannelList()))
    {
      throw new Exception("invalid channelID", 0x300);
    }

    return $this->channelList[(int) $cid];
  }
233202
protected function invokeSubscription(IEventSubscription $subscription, IEvent $event) {
        foreach ($this->invokers as $invoker) {
            if ($invoker->invoke($subscription, $event)) {
                return;
            }
        }

        $subscriber = $subscription->getSubscriber();

        throw new Exception(
            s('Could not invoke subscriber "%s".',
                is_scalar($subscriber) ? $subscriber : get_type($subscriber))
        );
    }
1356414
public static function send_instant_messages($messages = array()) {
        global $CFG, $USER, $DB;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Ensure the current user is allowed to run this function
        $context = context_system::instance();
        self::validate_context($context);
        require_capability('moodle/site:sendmessage', $context);

        $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));

        //retrieve all tousers of the messages
        $receivers = array();
        foreach($params['messages'] as $message) {
            $receivers[] = $message['touserid'];
        }
        list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers);
        $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);

        $resultmessages = array();
        $messageids = array();
        foreach ($params['messages'] as $message) {
            $resultmsg = array(); //the infos about the success of the operation

            // We are going to do some checking.
            // Code should match /messages/index.php checks.
            $success = true;

            // Check the user exists.
            if (empty($tousers[$message['touserid']])) {
                $success = false;
                $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
            }

            // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
            // Check if the recipient can be messaged by the sender.
            if ($success && !\core_message\api::can_post_message($tousers[$message['touserid']], $USER)) {
                $success = false;
                $errormessage = get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message['touserid'])));
            }

            // Now we can send the message (at least try).
            if ($success) {
                // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object.
                $success = message_post_message($USER, $tousers[$message['touserid']],
                        $message['text'], external_validate_format($message['textformat']));
            }

            // Build the resultmsg.
            if (isset($message['clientmsgid'])) {
                $resultmsg['clientmsgid'] = $message['clientmsgid'];
            }
            if ($success) {
                $resultmsg['msgid'] = $success;
                $resultmsg['timecreated'] = time();
                $messageids[] = $success;
            } else {
                // WARNINGS: for backward compatibility we return this errormessage.
                //          We should have thrown exceptions as these errors prevent results to be returned.
                // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
                $resultmsg['msgid'] = -1;
                $resultmsg['errormessage'] = $errormessage;
            }

            $resultmessages[] = $resultmsg;
        }

        if (!empty($messageids)) {
            $messagerecords = $DB->get_records_list(
                'messages',
                'id',
                $messageids,
                '',
                'id, conversationid, smallmessage, fullmessageformat, fullmessagetrust');
            $resultmessages = array_map(function($resultmessage) use ($messagerecords, $USER) {
                $id = $resultmessage['msgid'];
                $resultmessage['conversationid'] = isset($messagerecords[$id]) ? $messagerecords[$id]->conversationid : null;
                $resultmessage['useridfrom'] = $USER->id;
                $resultmessage['text'] = message_format_message_text((object) [
                    'smallmessage' => $messagerecords[$id]->smallmessage,
                    'fullmessageformat' => external_validate_format($messagerecords[$id]->fullmessageformat),
                    'fullmessagetrust' => $messagerecords[$id]->fullmessagetrust
                ]);
                return $resultmessage;
            }, $resultmessages);
        }

        return $resultmessages;
    }
352726
public function sendID($info = null)
    {
        if (!$this->_capability('ID')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ID');
        }

        $this->_sendID(is_null($info) ? ($this->getParam('id') ?: array()) : $info);
    }
1270136
public static function get_last_completed($feedbackid, $courseid = 0) {
        global $PAGE;

        $params = array('feedbackid' => $feedbackid, 'courseid' => $courseid);
        $params = self::validate_parameters(self::get_last_completed_parameters(), $params);
        $warnings = array();

        list($feedback, $course, $cm, $context, $completioncourse) = self::validate_feedback($params['feedbackid'],
            $params['courseid']);
        $feedbackcompletion = new mod_feedback_completion($feedback, $cm, $completioncourse->id);

        if ($feedbackcompletion->is_anonymous()) {
             throw new moodle_exception('anonymous', 'feedback');
        }
        if ($completed = $feedbackcompletion->find_last_completed()) {
            $exporter = new feedback_completed_exporter($completed);
            return array(
                'completed' => $exporter->export($PAGE->get_renderer('core')),
                'warnings' => $warnings,
            );
        }
        throw new moodle_exception('not_completed_yet', 'feedback');
    }
251287
public function rssAction($rssId)
    {
        $notificationManager = $this->getNotificationManager();
        try {
            $result = $notificationManager->getUserNotificationsListRss($rssId);
            $result['systemName'] = $notificationManager->getPlatformName();
        } catch (NoResultException $nre) {
            $result = ['error' => 'no_rss_defined'];
        } catch (NotFoundHttpException $nfe) {
            $result = ['error' => 'zero_notifications'];
        }

        return $this->render('IcapNotificationBundle:notification:rss.xml.twig', $result);
    }
355208
public function run()
    {
        if (PHP_SAPI === 'cli' && is_subclass_of($this, ConsoleAppInterface::class))
        {
            $this->execConsoleApp();
        }
        else if (is_subclass_of($this, WebAppInterface::class))
        {
            $this->execWebApp();
        }
        else
        {
            throw new \Exception("No interface was implemented");
        }
    }
389502
public function subscribe_user($courseid, $cmid, $userid = 0) {
        global $USER;

        if ($this->courseid != $courseid && $this->courseid != 0) {
            // Trying to subscribe to a rule that belongs to a different course. Should never happen.
            throw new \coding_exception('Can not subscribe to rules from a different course');
        }
        if ($cmid !== 0) {
            $cms = get_fast_modinfo($courseid);
            $cminfo = $cms->get_cm($cmid);
            if (!$cminfo->uservisible || !$cminfo->available) {
                // Trying to subscribe to a hidden or restricted cm. Should never happen.
                throw new \coding_exception('You cannot do that');
            }
        }
        $userid = empty($userid) ? $USER->id : $userid;

        subscription_manager::create_subscription($this->id, $courseid, $cmid, $userid);
    }