/**
 * Report user's activities to INTUITEL.
 * @param unknown $cmid
 * @param unknown $courseid
 * @param unknown $user_id
 * @param boolean $ignorelo whether to send LoId to INTUITEL (ignored in simulation mode)
 * @return Ambigous <string, lang_string, unknown, mixed>
 */
function block_intuitel_forward_learner_update_request($cmid, $courseid, $user_id, $ignorelo = false)
{
    $debug = optional_param('debug', false, PARAM_BOOL);
    $debug_response = optional_param('debugresponse', null, PARAM_ALPHANUM);
    // this param instruct Intuitel mock objects to respond with a pre-recorded response.
    $mmid = Intuitel::getIDFactory()->getNewMessageUUID();
    if (empty($cmid)) {
        $loId = Intuitel::getIDFactory()->getLoIdfromId('course', $courseid);
    } else {
        $loId = Intuitel::getIDFactory()->getLoIdfromId('module', $cmid);
    }
    // GET CURRENT USER id
    $userId = Intuitel::getIDFactory()->getUserId($user_id);
    global $CFG, $log;
    if ($ignorelo == true && get_config('block_intuitel', 'debug_server') == true) {
        $log->LogDebug("LMS send refreshing Learner message. Normal Learner procedure because in SIMULATED mode.");
    }
    if ($ignorelo == true && get_config('block_intuitel', 'debug_server') == false) {
        // Ignore reporting to INTUITEL. Just send a Learner message with no LoId to repeat reasoning
        // But simulated mode need loid to be sent
        $learnerUpdateMessage = '<INTUITEL>';
        $learnerUpdateMessage .= '	<Learner mId="' . $mmid . '" uId="' . $userId->id . '"  time="' . time() . '"/>';
        $learnerUpdateMessage .= '</INTUITEL>';
        $log->LogDebug("LMS send refreshing Learner message.");
    } else {
        // normal reporting of current and unreported events
        $log->LogDebug("LMS send normal Learner message for user {$userId->id}");
        if (get_config('block_intuitel', 'report_from_logevent')) {
            // get events unreported since last polling
            $events_user = Intuitel::getAdaptorInstance()->getLearnerUpdateData(array($user_id));
            $events = key_exists($userId->id, $events_user) ? $events_user[$userId->id] : null;
        }
        if (!get_config('block_intuitel', 'report_from_logevent') || !$events) {
            $event = new VisitEvent($userId, $loId, time());
            $events = array($event);
        }
        $debug_param = get_config('block_intuitel', 'debug_server') ? 'debugcourse="' . $courseid . '"' : '';
        // when using mock REST service help it with native courseid.
        $learnerUpdateMessage = '<INTUITEL>';
        $log->LogDebug("LearnerUpdate: LMS has found " . count($events) . " events regarding user {$userId} .");
        foreach ($events as $ev) {
            $learnerUpdateMessage .= '	<Learner mId="' . $mmid . '" uId="' . $ev->userId . '" loId="' . $ev->loId->id() . '" time="' . $ev->time . '" ' . $debug_param . '/>';
        }
        $learnerUpdateMessage .= '</INTUITEL>';
    }
    //  disable_moodle_page_exception_handler();
    $return = "No response from Intuitel";
    $log->LogDebug("LMS sending: {$learnerUpdateMessage}");
    try {
        $return = block_intuitel_submit_to_intuitel($learnerUpdateMessage, array('debugresponse' => $debug_response));
        if ($debug) {
            debugging("<p> Response from INTUITEL was: <p><pre>{$return}</pre>", DEBUG_DEVELOPER);
        }
        $log->LogDebug("LearnerUpdate: INTUITEL response was: {$return}.");
        // parse and generate TUG AND LORE html and messages
        list($html, $intuitel_elements) = IntuitelController::ProcessUpdateLearnerRequest($return, $courseid);
        if (count($intuitel_elements->Learner->Tug) > 0) {
            $response = IntuitelXMLSerializer::getIntuitelXMLTemplate();
            foreach ($intuitel_elements->Learner->Tug as $tug) {
                $mid = IntuitelXMLSerializer::get_required_attribute($tug, 'mId');
                $text = str_replace('<![CDATA[', '', $tug->MData);
                $text = str_replace(']]>', '', $tug->MData);
                $text = strip_tags($text);
                Intuitel::getAdaptorInstance()->logTugView($courseid, $user_id, $mid, substr('mId=' . $mid . ' ' . $text, 0, 255));
                IntuitelController::addTUGInmediateResponse($response, IntuitelXMLSerializer::get_required_attribute($tug, 'uId'), IntuitelXMLSerializer::get_required_attribute($tug, 'mId'), "OK");
            }
            $xml = $response->asXML();
            block_intuitel_submit_to_intuitel($xml);
            $log->LogDebug("TUG inmediate response sent: {$xml}");
        }
        if (count($intuitel_elements->Learner->Lore) > 0) {
            $response = IntuitelXMLSerializer::getIntuitelXMLTemplate();
            foreach ($intuitel_elements->Learner->Lore as $lore) {
                $mid = IntuitelXMLSerializer::get_required_attribute($lore, 'mId');
                $lores = array();
                foreach ($lore->LorePrio as $lorePrio) {
                    try {
                        $loid = IntuitelXMLSerializer::get_required_attribute($lorePrio, 'loId');
                        $cmid = Intuitel::getIDFactory()->getIdfromLoId(new LOId($loid));
                        $lo = Intuitel::getAdaptorInstance()->createLO(new LOId($loid));
                        $lores[] = "({$cmid})\"{$lo->loName}\"";
                    } catch (Exception $ex) {
                        $lores[] = $loid;
                    }
                }
                if (count($lores)) {
                    // log activity
                    Intuitel::getAdaptorInstance()->logLoreView($courseid, $user_id, $mid, substr(join(',', $lores), 0, 255));
                }
                $xml = IntuitelController::addLOREInmediateResponse($response, IntuitelXMLSerializer::get_required_attribute($lore, 'uId'), IntuitelXMLSerializer::get_required_attribute($lore, 'mId'), "OK");
            }
            $xml = $response->asXML();
            block_intuitel_submit_to_intuitel($xml);
        }
        $html = '<div>' . $html . '</div>';
    } catch (ProtocolErrorException $exception) {
        // error
        $a = new stdClass();
        $a->service_point = block_intuitel_get_service_endpoint();
        $a->status_code = $exception->getStatusCode();
        $a->message = $exception->getMessage();
        $html = get_string('protocol_error_intuitel_node_malfunction', 'block_intuitel', $a);
        $log->LogError("INTUITEL error: {$a->message} Return value:" . $return);
    }
    return $html;
}
     $tugcancelledfield = optional_param('_intuitel_TUG_cancel', null, PARAM_ALPHA);
     if ($tugcancelledfield !== '') {
         // The browser use Javascript.
         if ($tugcancelledfield === 'true') {
             $_REQUEST['_intuitel_user_intent'] = 'cancel';
         } else {
             $_REQUEST['_intuitel_user_intent'] = 'submit';
         }
     }
     // JPC: end of workaround for YUI bug with forms.
     if ($_REQUEST['_intuitel_user_intent'] === 'submit') {
         // Ignore cancellation of the TUG messages.
         // TODO: Avoid sending this form in the User Interface but find a way to work without javascript too.
         $message = IntuitelController::ProcessTUGResponse($USER->id, $_REQUEST, $courseid);
         $log->LogDebug("LMS sends TUG answer: {$message}");
         block_intuitel_submit_to_intuitel($message);
     } else {
         $mid = required_param('mId', PARAM_ALPHANUMEXT);
         Intuitel::getAdaptorInstance()->logTugDismiss($courseid, $USER->id, $mid, 'DISMISS mId=' . $mid);
     }
 } else {
     if ($action == 'GEOLOCATION') {
         require_login();
         session_write_close();
         // Release the session to avoid block requests while waiting intuitel response.
         $adaptor = Intuitel::getAdaptorInstance();
         // Location.
         $lat = required_param('lat', PARAM_FLOAT);
         $lon = required_param('lon', PARAM_FLOAT);
         $adaptor->registerEnvironment('dLocation', "EPSG:4326;POINT({$lat} {$lon})", $USER, time());
     }