Trigger the course module viewed event.

@param int $scormid the SCORM instance id
@param int $scoid the SCO id
@return array of warnings and status result
@since Moodle 3.1
@throws moodle_exception
499867
public static function launch_sco($scormid, $scoid = 0) {
        global $DB;

        $params = self::validate_parameters(self::launch_sco_parameters(),
                                            array(
                                                'scormid' => $scormid,
                                                'scoid' => $scoid
                                            ));
        $warnings = array();

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

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

        // If the SCORM is not open this function will throw exceptions.
        scorm_require_available($scorm);

        if (!empty($params['scoid']) and !($sco = scorm_get_sco($params['scoid'], SCO_ONLY))) {
            throw new moodle_exception('cannotfindsco', 'scorm');
        }

        list($sco, $scolaunchurl) = scorm_get_sco_and_launch_url($scorm, $params['scoid'], $context);
        // Trigger the SCO launched event.
        scorm_launch_sco($scorm, $sco, $cm, $context, $scolaunchurl);

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }
903566
@Override
	public ScopDomain getDomainByScopID(String scopId) {

		try {
			ensureClaInstalled();
		} catch (IOException e) {
			throw new ScopIOException(e);
		}

		if ( scopId.length() < 6) {
			throw new ScopIOException("Does not look like a scop ID! " + scopId);
		}
		String pdbId = scopId.substring(1,5);
		List<ScopDomain> doms = getDomainsForPDB(pdbId);
		if ( doms == null)
			return null;
		for ( ScopDomain d : doms){
			if ( d.getScopId().equalsIgnoreCase(scopId))
				return d;
		}

		return null;
	}
980291
private function _scsi()
    {
        foreach ($this->readaixdata() as $line) {
            if (preg_match("/^[\*\+]\s\S+\s+\S+\s+(.*SCSI.*)/", $line, $ar_buf)) {
                $dev = new HWDevice();
                $dev->setName(trim($ar_buf[1]));
                $this->sys->setScsiDevices($dev);
            }
        }
    }
862947
public static function get_scorm_scoes($scormid, $organization = '') {
        global $DB;

        $params = self::validate_parameters(self::get_scorm_scoes_parameters(),
                                            array('scormid' => $scormid, 'organization' => $organization));

        $scoes = array();
        $warnings = array();

        $scorm = $DB->get_record('scorm', array('id' => $params['scormid']), '*', MUST_EXIST);
        $cm = get_coursemodule_from_instance('scorm', $scorm->id);

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

        // Check settings / permissions to view the SCORM.
        scorm_require_available($scorm, true, $context);

        if (!$scoes = scorm_get_scoes($scorm->id, $params['organization'])) {
            // Function scorm_get_scoes return false, not an empty array.
            $scoes = array();
        } else {
            $scoreturnstructure = self::get_scorm_scoes_returns();
            foreach ($scoes as $sco) {
                $extradata = array();
                foreach ($sco as $element => $value) {
                    // Check if the element is extra data (not a basic SCO element).
                    if (!isset($scoreturnstructure->keys['scoes']->content->keys[$element])) {
                        $extradata[] = array(
                            'element' => $element,
                            'value' => $value
                        );
                    }
                }
                $sco->extradata = $extradata;
            }
        }

        $result = array();
        $result['scoes'] = $scoes;
        $result['warnings'] = $warnings;
        return $result;
    }
665230
public static function update_entry($entryid, $data) {
        global $DB;

        $params = array('entryid' => $entryid, 'data' => $data);
        $params = self::validate_parameters(self::update_entry_parameters(), $params);
        $warnings = array();
        $fieldnotifications = array();
        $updated = false;

        $record = $DB->get_record('data_records', array('id' => $params['entryid']), '*', MUST_EXIST);
        list($database, $course, $cm, $context) = self::validate_database($record->dataid);
        // Check database is open in time.
        data_require_time_available($database, null, $context);

        if (!data_user_can_manage_entry($record, $database, $context)) {
            throw new moodle_exception('noaccess', 'data');
        }

        // Prepare the data as is expected by the API.
        $datarecord = new stdClass;
        foreach ($params['data'] as $data) {
            $subfield = ($data['subfield'] !== '') ? '_' . $data['subfield'] : '';
            // We ask for JSON encoded values because of multiple choice forms or checkboxes that use array parameters.
            $datarecord->{'field_' . $data['fieldid'] . $subfield} = json_decode($data['value']);
        }
        // Validate to ensure that enough data was submitted.
        $fields = $DB->get_records('data_fields', array('dataid' => $database->id));
        $processeddata = data_process_submission($database, $fields, $datarecord);

        // Format notifications.
        if (!empty($processeddata->fieldnotifications)) {
            foreach ($processeddata->fieldnotifications as $field => $notififications) {
                foreach ($notififications as $notif) {
                    $fieldnotifications[] = [
                        'fieldname' => $field,
                        'notification' => $notif,
                    ];
                }
            }
        }

        if ($processeddata->validated) {
            // Now update the fields contents.
            data_update_record_fields_contents($database, $record, $context, $datarecord, $processeddata);
            $updated = true;
        }

        $result = array(
            'updated' => $updated,
            'generalnotifications' => $processeddata->generalnotifications,
            'fieldnotifications' => $fieldnotifications,
            'warnings' => $warnings,
        );
        return $result;
    }
1133081
private function copySco(Sco $sco, Scorm $resource, Sco $scoParent = null)
    {
        $scoCopy = new Sco();
        $scoCopy->setScorm($resource);
        $scoCopy->setScoParent($scoParent);

        $scoCopy->setEntryUrl($sco->getEntryUrl());
        $scoCopy->setIdentifier($sco->getIdentifier());
        $scoCopy->setTitle($sco->getTitle());
        $scoCopy->setVisible($sco->isVisible());
        $scoCopy->setParameters($sco->getParameters());
        $scoCopy->setLaunchData($sco->getLaunchData());
        $scoCopy->setMaxTimeAllowed($sco->getMaxTimeAllowed());
        $scoCopy->setTimeLimitAction($sco->getTimeLimitAction());
        $scoCopy->setBlock($sco->isBlock());
        $scoCopy->setScoreToPassInt($sco->getScoreToPassInt());
        $scoCopy->setScoreToPassDecimal($sco->getScoreToPassDecimal());
        $scoCopy->setCompletionThreshold($sco->getCompletionThreshold());
        $scoCopy->setPrerequisites($sco->getPrerequisites());
        $this->om->persist($scoCopy);

        foreach ($sco->getScoChildren() as $scoChild) {
            $this->copySco($scoChild, $resource, $scoCopy);
        }
    }
456333
private function notification(\context $context, \stdClass $user, \moodle_url $insighturl, string $fullmessage, string $fullmessagehtml) {

        $message = new \core\message\message();
        $message->component = 'moodle';
        $message->name = 'insights';

        $message->userfrom = \core_user::get_noreply_user();
        $message->userto = $user;

        $message->subject = $this->target->get_insight_subject($this->modelid, $context);

        // Same than the subject.
        $message->contexturlname = $message->subject;
        $message->courseid = $this->get_context_courseid($context);

        $message->fullmessage = $fullmessage;
        $message->fullmessageformat = FORMAT_PLAIN;
        $message->fullmessagehtml = $fullmessagehtml;
        $message->smallmessage = $fullmessage;
        $message->contexturl = $insighturl->out(false);

        message_send($message);
    }
114148
public static function competency_framework_viewed($frameworkorid) {
        static::require_enabled();
        $framework = $frameworkorid;
        if (!is_object($framework)) {
            $framework = new competency_framework($framework);
        }
        if (!has_any_capability(array('moodle/competency:competencyview', 'moodle/competency:competencymanage'),
                $framework->get_context())) {
            throw new required_capability_exception($framework->get_context(), 'moodle/competency:competencyview',
                'nopermissions', '');
        }
        \core\event\competency_framework_viewed::create_from_framework($framework)->trigger();
        return true;
    }
68984
public function subscribe($obEvent)
    {
        $sModelClass = $this->getModelClass();
        $sModelClass::extend(function ($obElement) {

            /** @var \Model $obElement */
            $obElement->bindEvent('model.afterCreate', function () use ($obElement) {
                $this->obElement = $obElement;
                $this->init();
                $this->afterCreate();
            }, $this->iPriority);

            /** @var \Model $obElement */
            $obElement->bindEvent('model.afterSave', function () use ($obElement) {
                $this->obElement = $obElement;
                $this->init();
                $this->afterSave();
            }, $this->iPriority);

            /** @var \Model $obElement */
            $obElement->bindEvent('model.afterDelete', function () use ($obElement) {
                $this->obElement = $obElement;
                $this->init();
                $this->afterDelete();
            }, $this->iPriority);

            if ($this->bWithRestore) {
                /** @var \Model $obElement */
                $obElement->bindEvent('model.afterRestore', function () use ($obElement) {
                    $this->obElement = $obElement;
                    $this->init();
                    $this->afterRestore();
                }, $this->iPriority);
            }
        });
    }
739204
public function getByCode($sCode)
    {
        $aCountries = $this->getAll();

        return ! empty($aCountries[$sCode]) ? $aCountries[$sCode] : false;
    }
206788
@Override
	public List<ScopDomain> getScopDomainsBySunid(Integer sunid)
	{

		try {
			ensureClaInstalled();
		} catch (IOException e) {
			throw new ScopIOException(e);
		}

		List<ScopDomain> domains = new ArrayList<ScopDomain>();

		for (String pdbId: domainMap.keySet()){
			for (ScopDomain d : domainMap.get(pdbId)){
				try {
					if ( d.getPx() == sunid) {
						domains.add((ScopDomain)d.clone());
					} else if ( d.getSpeciesId() == sunid ){
						domains.add((ScopDomain)d.clone());
					}else if ( d.getDomainId() == sunid ){
						domains.add((ScopDomain)d.clone());
					}else if ( d.getFamilyId() == sunid ){
						domains.add((ScopDomain)d.clone());
					}else if ( d.getSuperfamilyId() == sunid ){
						domains.add((ScopDomain)d.clone());
					}else if ( d.getFoldId() == sunid ){
						domains.add((ScopDomain)d.clone());
					}else if ( d.getClassId() == sunid ){
						domains.add((ScopDomain)d.clone());
					} else {
						throw new RuntimeException("Type " + d + " not recognized"); // only possible if SCOP changes
					}
				} catch (CloneNotSupportedException e){
					throw new RuntimeException(ScopDomain.class + " subclass does not support clone()", e);
				}
			}
		}
		return domains;

	}
1322159
public function set_module_viewed() {
        global $CFG;
        require_once($CFG->libdir . '/completionlib.php');

        // Mark viewed.
        $completion = new completion_info($this->course);
        $completion->set_module_viewed($this->cm);

        $eventdata = array();
        $eventdata['objectid'] = $this->id;
        $eventdata['context'] = $this->context;

        // Trigger module viewed event.
        $event = \mod_workshop\event\course_module_viewed::create($eventdata);
        $event->add_record_snapshot('course', $this->course);
        $event->add_record_snapshot('workshop', $this->dbrecord);
        $event->add_record_snapshot('course_modules', $this->cm);
        $event->trigger();
    }
657916
public function onSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (null === $data) {
            $data = array();
        }

        if (!is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) {
            throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)');
        }

        foreach ($this->schema->getGroups() as $schemaGroup) {
            foreach ($schemaGroup->getDefinitions() as $schemaDefinition) {
                if (true === $schemaDefinition->getVirtual()) {
                    continue;
                }
                $identifier = $schemaDefinition->getIdentifier();
                if ($data->offsetExists($identifier)) {
                    /** @var CharacteristicInterface $characteristic */
                    $characteristic = $data->offsetGet($identifier);
                    if ($this->isNullOrEqualsParentData($characteristic)) {
                        $data->offsetUnset($identifier);
                        $this->em->remove($characteristic);
                    } else {
                        $characteristic->setIdentifier($identifier);
                    }
                } else {
                    throw new \RuntimeException(sprintf('Missing [%s] characteristic data.', $identifier));
                }
            }
        }

        $event->setData($data);
    }
928858
public function process_scorm($data) {
        global $CFG;

        // get the course module id and context id
        $instanceid     = $data['id'];
        $currentcminfo  = $this->get_cminfo($instanceid);
        $this->moduleid = $currentcminfo['id'];
        $contextid      = $this->converter->get_contextid(CONTEXT_MODULE, $this->moduleid);

        // conditionally migrate to html format in intro
        if ($CFG->texteditors !== 'textarea') {
            $data['intro']       = text_to_html($data['intro'], false, false, true);
            $data['introformat'] = FORMAT_HTML;
        }

        // get a fresh new file manager for this instance
        $this->fileman = $this->converter->get_file_manager($contextid, 'mod_scorm');

        // convert course files embedded into the intro
        $this->fileman->filearea = 'intro';
        $this->fileman->itemid   = 0;
        $data['intro'] = moodle1_converter::migrate_referenced_files($data['intro'], $this->fileman);

        // check 1.9 version where backup was created
        $backupinfo = $this->converter->get_stash('backup_info');
        if ($backupinfo['moodle_version'] < 2007110503) {
            // as we have no module version data, assume $currmodule->version <= $module->version
            // - fix data as the source 1.9 build hadn't yet at time of backing up.
            $data['grademethod'] = $data['grademethod']%10;
        }

        // update scormtype (logic is consistent as done in scorm/db/upgrade.php)
        $ismanifest = preg_match('/imsmanifest\.xml$/', $data['reference']);
        $iszippif = preg_match('/.(zip|pif)$/', $data['reference']);
        $isurl = preg_match('/^((http|https):\/\/|www\.)/', $data['reference']);
        if ($isurl) {
            if ($ismanifest) {
                $data['scormtype'] = 'external';
            } else if ($iszippif) {
                $data['scormtype'] = 'localtype';
            }
        }

        // migrate scorm package file
        $this->fileman->filearea = 'package';
        $this->fileman->itemid   = 0;
        $this->fileman->migrate_file('course_files/'.$data['reference']);

        // start writing scorm.xml
        $this->open_xml_writer("activities/scorm_{$this->moduleid}/scorm.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $this->moduleid,
            'modulename' => 'scorm', 'contextid' => $contextid));
        $this->xmlwriter->begin_tag('scorm', array('id' => $instanceid));

        foreach ($data as $field => $value) {
            if ($field <> 'id') {
                $this->xmlwriter->full_tag($field, $value);
            }
        }

        $this->xmlwriter->begin_tag('scoes');

        return $data;
    }
199701
public static function list_course_module_competencies_in_course_module($cmorid) {
        static::require_enabled();
        $cm = $cmorid;
        if (!is_object($cmorid)) {
            $cm = get_coursemodule_from_id('', $cmorid, 0, true, MUST_EXIST);
        }

        // Check the user have access to the course module.
        self::validate_course_module($cm);
        $context = context_module::instance($cm->id);

        $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
        if (!has_any_capability($capabilities, $context)) {
            throw new required_capability_exception($context, 'moodle/competency:coursecompetencyview', 'nopermissions', '');
        }

        $result = array();

        $cmclist = course_module_competency::list_course_module_competencies($cm->id);
        foreach ($cmclist as $id => $cmc) {
            array_push($result, $cmc);
        }

        return $result;
    }
893756
public function replaceBy($sContent, $sFormat = '"%b %e, %Y"') 
	{
		$aTransformFormat = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
		$aTransformFormatFinal = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');

		if (strpos($sFormat, '%e') !== false) {

			$aTransformFormat[] = '%e';
			$aTransformFormatFinal[] = sprintf('%\' 2d', date('j', $sContent));
		}

		if (strpos($sFormat, '%l') !== false) {

			$aTransformFormat[] = '%l';
			$aTransformFormatFinal[] = sprintf('%\' 2d', date('h', $sContent));
		}

		$sFormat = str_replace($aTransformFormat, $aTransformFormatFinal, $sFormat);

		return '{strftime('.$sFormat.', '.$sContent.')}';
	}
1004345
public function trigger($config = array())
    {
        // Can't put arguments through KObjectConfig as it loses referenced variables
        $attributes = isset($config['attributes']) ? $config['attributes'] : array();
        $config     = new KObjectConfig($config);
        $config->append(array(
            'name'         => null,
            'import_group' => null
        ));

        if (empty($config->name)) {
            throw new InvalidArgumentException('Event name is required');
        }

        if(!(count($attributes) > 1)) {
            throw new InvalidArgumentException('Event requires at least 2 attributes');
        }

        if ($config->import_group) {
            JPluginHelper::importPlugin($config->import_group);
        }

        $results = JEventDispatcher::getInstance()->trigger($config->name, $attributes);

        if($config->name == 'onContentPrepare')
        {
            if(isset($attributes[1]) && isset($attributes[1]->text)) {
                $result = $attributes[1]->text;
            }
        }
        else $result = trim(implode("\n", $results));

        // Leave third party JavaScript as-is
        $result = str_replace('<script', '<script data-inline', $result);

        return $result;
    }