/** * Execute client WS request with token authentication * @param string $functionname * @param array $params * @return mixed */ public function call($functionname, $params) { global $DB, $CFG; $result = download_file_content($this->serverurl . '?wstoken=' . $this->token . '&wsfunction=' . $functionname, null, $params); //TODO : transform the XML result into PHP values - MDL-22965 return $result; }
/** * Returns location information * @param string $ip * @return array */ function iplookup_find_location($ip) { global $CFG; $info = array('city' => null, 'country' => null, 'longitude' => null, 'latitude' => null, 'error' => null, 'note' => '', 'title' => array()); if (!empty($CFG->geoip2file) and file_exists($CFG->geoip2file)) { $reader = new GeoIp2\Database\Reader($CFG->geoip2file); $record = $reader->city($ip); if (empty($record)) { $info['error'] = get_string('iplookupfailed', 'error', $ip); return $info; } $info['city'] = core_text::convert($record->city->name, 'iso-8859-1', 'utf-8'); $info['title'][] = $info['city']; $countrycode = $record->country->isoCode; $countries = get_string_manager()->get_list_of_countries(true); if (isset($countries[$countrycode])) { // Prefer our localized country names. $info['country'] = $countries[$countrycode]; } else { $info['country'] = $record->country->names['en']; } $info['title'][] = $info['country']; $info['longitude'] = $record->location->longitude; $info['latitude'] = $record->location->latitude; $info['note'] = get_string('iplookupmaxmindnote', 'admin'); return $info; } else { require_once $CFG->libdir . '/filelib.php'; if (strpos($ip, ':') !== false) { // IPv6 is not supported by geoplugin.net. $info['error'] = get_string('invalidipformat', 'error'); return $info; } $ipdata = download_file_content('http://www.geoplugin.net/json.gp?ip=' . $ip); if ($ipdata) { $ipdata = preg_replace('/^geoPlugin\\((.*)\\)\\s*$/s', '$1', $ipdata); $ipdata = json_decode($ipdata, true); } if (!is_array($ipdata)) { $info['error'] = get_string('cannotgeoplugin', 'error'); return $info; } $info['latitude'] = (double) $ipdata['geoplugin_latitude']; $info['longitude'] = (double) $ipdata['geoplugin_longitude']; $info['city'] = s($ipdata['geoplugin_city']); $countrycode = $ipdata['geoplugin_countryCode']; $countries = get_string_manager()->get_list_of_countries(true); if (isset($countries[$countrycode])) { // prefer our localized country names $info['country'] = $countries[$countrycode]; } else { $info['country'] = s($ipdata['geoplugin_countryName']); } $info['note'] = get_string('iplookupgeoplugin', 'admin'); $info['title'][] = $info['city']; $info['title'][] = $info['country']; return $info; } }
function bootstrap($wwwroot, $pubkey = null, $application) { global $DB; if (substr($wwwroot, -1, 1) == '/') { $wwwroot = substr($wwwroot, 0, -1); } // If a peer record already exists for this address, // load that info and return if ($this->set_wwwroot($wwwroot)) { return true; } $hostname = mnet_get_hostname_from_uri($wwwroot); // Get the IP address for that host - if this fails, it will return the hostname string $ip_address = gethostbyname($hostname); // Couldn't find the IP address? if ($ip_address === $hostname && !preg_match('/^\\d+\\.\\d+\\.\\d+.\\d+$/', $hostname)) { throw new moodle_exception('noaddressforhost', 'mnet', '', $hostname); } $this->name = $wwwroot; // TODO: In reality, this will be prohibitively slow... need another // default - maybe blank string $homepage = download_file_content($wwwroot); if (!empty($homepage)) { $count = preg_match("@<title>(.*)</title>@siU", $homepage, $matches); if ($count > 0) { $this->name = $matches[1]; } } $this->wwwroot = $wwwroot; $this->ip_address = $ip_address; $this->deleted = 0; $this->application = $DB->get_record('mnet_application', array('name' => $application)); if (empty($this->application)) { $this->application = $DB->get_record('mnet_application', array('name' => 'moodle')); } $this->applicationid = $this->application->id; if (empty($pubkey)) { $this->public_key = clean_param(mnet_get_public_key($this->wwwroot, $this->application), PARAM_PEM); } else { $this->public_key = clean_param($pubkey, PARAM_PEM); } $this->public_key_expires = $this->check_common_name($this->public_key); $this->last_connect_time = 0; $this->last_log_id = 0; if ($this->public_key_expires == false) { $this->public_key == ''; return false; } $this->bootstrapped = true; }
/** * Afterburner upgrades. * * @package theme_afterburner * @copyright 2013 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ function xmldb_theme_afterburner_upgrade($oldversion) { global $CFG, $DB, $OUTPUT; $dbman = $DB->get_manager(); if ($oldversion < 2013041200) { // Migrate logo URL. $logo = get_config('theme_afterburner', 'logo'); if ($logo === '') { // No logo means nothing to do. } else if ($logo = clean_param($logo, PARAM_URL)) { require_once("$CFG->libdir/filelib.php"); if ($content = download_file_content($logo)) { $filename = preg_replace('/^.*\//', '', $logo); if (!$filename = clean_param($filename, PARAM_FILE)) { // Some name is better than no name... $filename = 'logo.jpg'; } $fs = get_file_storage(); $record = array( 'contextid' => context_system::instance()->id, 'component' => 'theme_afterburner', 'filearea' => 'logo', 'itemid'=>0, 'filepath'=>'/', 'filename'=>$filename); $fs->create_file_from_string($record, $content); set_config('logo', '/'.$filename, 'theme_afterburner'); unset($content); } else { unset_config('theme_afterburner', 'logo'); } } else { // Prompt for new logo, the old setting was invalid. unset_config('theme_afterburner', 'logo'); } upgrade_plugin_savepoint(true, 2013041200, 'theme', 'afterburner'); } // Moodle v2.5.0 release upgrade line. // Put any upgrade step following this. return true; }
/** * Execute client WS request with token authentication * * @param string $functionname the function name * @param array $params An associative array containing the the parameters of the function being called. * @return mixed The decoded XML RPC response. * @throws moodle_exception */ public function call($functionname, $params = array()) { if ($this->token) { $this->serverurl->param('wstoken', $this->token); } // Set output options. $outputoptions = array('encoding' => 'utf-8'); // Encode the request. $request = xmlrpc_encode_request($functionname, $params, $outputoptions); // Set the headers. $headers = array('Content-Length' => strlen($request), 'Content-Type' => 'text/xml; charset=utf-8', 'Host' => $this->serverurl->get_host(), 'User-Agent' => 'Moodle XML-RPC Client/1.0'); // Get the response. $response = download_file_content($this->serverurl, $headers, $request); // Decode the response. $result = xmlrpc_decode($response); if (is_array($result) && xmlrpc_is_fault($result)) { throw new Exception($result['faultString'], $result['faultCode']); } return $result; }
/** * Execute client WS request with token authentication * * @param string $functionname the function name * @param array $params the parameters of the function * @return mixed */ public function call($functionname, $params) { global $DB, $CFG; if ($this->format == 'json') { $formatparam = '&moodlewsrestformat=json'; $this->serverurl->param('moodlewsrestformat', 'json'); } else { $formatparam = ''; //to keep retro compability with old server that only support xml (they don't expect this param) } $this->serverurl->param('wstoken', $this->token); $this->serverurl->param('wsfunction', $functionname); //you could also use params(). $result = download_file_content($this->serverurl->out(false), null, $params); //TODO MDL-22965 transform the XML result into PHP values if ($this->format == 'json') { $result = json_decode($result); } return $result; }
public function test_geoip() { global $CFG; require_once "{$CFG->libdir}/filelib.php"; require_once "{$CFG->dirroot}/iplookup/lib.php"; if (!PHPUNIT_LONGTEST) { // this may take a long time return; } $this->resetAfterTest(); // let's store the file somewhere $gzfile = "{$CFG->dataroot}/phpunit/geoip/GeoLiteCity.dat.gz"; check_dir_exists(dirname($gzfile)); if (file_exists($gzfile) and filemtime($gzfile) < time() - 60 * 60 * 24 * 30) { // delete file if older than 1 month unlink($gzfile); } if (!file_exists($gzfile)) { download_file_content('http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz', null, null, false, 300, 20, false, $gzfile); } $this->assertTrue(file_exists($gzfile)); $zd = gzopen($gzfile, "r"); $contents = gzread($zd, 50000000); gzclose($zd); $geoipfile = "{$CFG->dataroot}/geoip/GeoLiteCity.dat"; check_dir_exists(dirname($geoipfile)); $fp = fopen($geoipfile, 'w'); fwrite($fp, $contents); fclose($fp); $this->assertTrue(file_exists($geoipfile)); $CFG->geoipfile = $geoipfile; $result = iplookup_find_location('147.230.16.1'); $this->assertEquals('array', gettype($result)); $this->assertEquals('Liberec', $result['city']); $this->assertEquals(15.0653, $result['longitude'], '', 0.001); $this->assertEquals(50.7639, $result['latitude'], '', 0.001); $this->assertNull($result['error']); $this->assertEquals('array', gettype($result['title'])); $this->assertEquals('Liberec', $result['title'][0]); $this->assertEquals('Czech Republic', $result['title'][1]); }
public function setUp() { global $CFG; require_once "{$CFG->libdir}/filelib.php"; require_once "{$CFG->dirroot}/iplookup/lib.php"; if (!PHPUNIT_LONGTEST) { // this may take a long time $this->markTestSkipped('PHPUNIT_LONGTEST is not defined'); } $this->resetAfterTest(); // let's store the file somewhere $gzfile = "{$CFG->dataroot}/phpunit/geoip/GeoLite2-City.mmdb.gz"; check_dir_exists(dirname($gzfile)); if (file_exists($gzfile) and filemtime($gzfile) < time() - 60 * 60 * 24 * 30) { // delete file if older than 1 month unlink($gzfile); } if (!file_exists($gzfile)) { download_file_content('http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz', null, null, false, 300, 20, false, $gzfile); } $this->assertTrue(file_exists($gzfile)); $geoipfile = str_replace('.gz', '', $gzfile); // Open our files (in binary mode). $file = gzopen($gzfile, 'rb'); $geoipfilebuf = fopen($geoipfile, 'wb'); // Keep repeating until the end of the input file. while (!gzeof($file)) { // Read buffer-size bytes. // Both fwrite and gzread and binary-safe. fwrite($geoipfilebuf, gzread($file, 4096)); } // Files are done, close files. fclose($geoipfilebuf); gzclose($file); $this->assertTrue(file_exists($geoipfile)); $CFG->geoip2file = $geoipfile; }
/** * Sets up SCORM 1.2/2004 packages using the manifest file. * Called whenever SCORM changes * @param object $scorm instance - fields are updated and changes saved into database * @param stored_file|string $manifest - path to manifest file or stored_file. * @return bool */ function scorm_parse_scorm(&$scorm, $manifest) { global $CFG, $DB; // load manifest into string if ($manifest instanceof stored_file) { $xmltext = $manifest->get_content(); } else { require_once "{$CFG->libdir}/filelib.php"; $xmltext = download_file_content($manifest); } $defaultorgid = 0; $firstinorg = 0; $pattern = '/&(?!\\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objXML = new xml2Array(); $manifests = $objXML->parse($xmltext); $scoes = new stdClass(); $scoes->version = ''; $scoes = scorm_get_manifest($manifests, $scoes); $newscoes = array(); $sortorder = 0; if (count($scoes->elements) > 0) { $olditems = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id)); foreach ($scoes->elements as $manifest => $organizations) { foreach ($organizations as $organization => $items) { foreach ($items as $identifier => $item) { $sortorder++; // This new db mngt will support all SCORM future extensions $newitem = new stdClass(); $newitem->scorm = $scorm->id; $newitem->manifest = $manifest; $newitem->organization = $organization; $newitem->sortorder = $sortorder; $standarddatas = array('parent', 'identifier', 'launch', 'scormtype', 'title'); foreach ($standarddatas as $standarddata) { if (isset($item->{$standarddata})) { $newitem->{$standarddata} = $item->{$standarddata}; } else { $newitem->{$standarddata} = ''; } } if (!empty($defaultorgid) && !empty($scoes->defaultorg) && empty($firstinorg) && $newitem->parent == $scoes->defaultorg) { $firstinorg = $sortorder; } if (!empty($olditems) && ($olditemid = scorm_array_search('identifier', $newitem->identifier, $olditems))) { $newitem->id = $olditemid; // Update the Sco sortorder but keep id so that user tracks are kept against the same ids. $DB->update_record('scorm_scoes', $newitem); $id = $olditemid; // Remove all old data so we don't duplicate it. $DB->delete_records('scorm_scoes_data', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_objective', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_mapinfo', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_ruleconds', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rulecond', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rolluprule', array('scoid' => $olditemid)); $DB->delete_records('scorm_seq_rolluprulecond', array('scoid' => $olditemid)); // Now remove this SCO from the olditems object as we have dealt with it. unset($olditems[$olditemid]); } else { // Insert the new SCO, and retain the link between the old and new for later adjustment $id = $DB->insert_record('scorm_scoes', $newitem); } $newscoes[$id] = $newitem; // Save this sco in memory so we can use it later. if ($optionaldatas = scorm_optionals_data($item, $standarddatas)) { $data = new stdClass(); $data->scoid = $id; foreach ($optionaldatas as $optionaldata) { if (isset($item->{$optionaldata})) { $data->name = $optionaldata; $data->value = $item->{$optionaldata}; $dataid = $DB->insert_record('scorm_scoes_data', $data); } } } if (isset($item->sequencingrules)) { foreach ($item->sequencingrules as $sequencingrule) { $rule = new stdClass(); $rule->scoid = $id; $rule->ruletype = $sequencingrule->type; $rule->conditioncombination = $sequencingrule->conditioncombination; $rule->action = $sequencingrule->action; $ruleid = $DB->insert_record('scorm_seq_ruleconds', $rule); if (isset($sequencingrule->ruleconditions)) { foreach ($sequencingrule->ruleconditions as $rulecondition) { $rulecond = new stdClass(); $rulecond->scoid = $id; $rulecond->ruleconditionsid = $ruleid; $rulecond->referencedobjective = $rulecondition->referencedobjective; $rulecond->measurethreshold = $rulecondition->measurethreshold; $rulecond->operator = $rulecondition->operator; $rulecond->cond = $rulecondition->cond; $rulecondid = $DB->insert_record('scorm_seq_rulecond', $rulecond); } } } } if (isset($item->rolluprules)) { foreach ($item->rolluprules as $rolluprule) { $rollup = new stdClass(); $rollup->scoid = $id; $rollup->childactivityset = $rolluprule->childactivityset; $rollup->minimumcount = $rolluprule->minimumcount; $rollup->minimumpercent = $rolluprule->minimumpercent; $rollup->rollupruleaction = $rolluprule->rollupruleaction; $rollup->conditioncombination = $rolluprule->conditioncombination; $rollupruleid = $DB->insert_record('scorm_seq_rolluprule', $rollup); if (isset($rollup->conditions)) { foreach ($rollup->conditions as $condition) { $cond = new stdClass(); $cond->scoid = $rollup->scoid; $cond->rollupruleid = $rollupruleid; $cond->operator = $condition->operator; $cond->cond = $condition->cond; $conditionid = $DB->insert_record('scorm_seq_rolluprulecond', $cond); } } } } if (isset($item->objectives)) { foreach ($item->objectives as $objective) { $obj = new stdClass(); $obj->scoid = $id; $obj->primaryobj = $objective->primaryobj; $obj->satisfiedbumeasure = $objective->satisfiedbymeasure; $obj->objectiveid = $objective->objectiveid; $obj->minnormalizedmeasure = trim($objective->minnormalizedmeasure); $objectiveid = $DB->insert_record('scorm_seq_objective', $obj); if (isset($objective->mapinfos)) { foreach ($objective->mapinfos as $objmapinfo) { $mapinfo = new stdClass(); $mapinfo->scoid = $id; $mapinfo->objectiveid = $objectiveid; $mapinfo->targetobjectiveid = $objmapinfo->targetobjectiveid; $mapinfo->readsatisfiedstatus = $objmapinfo->readsatisfiedstatus; $mapinfo->writesatisfiedstatus = $objmapinfo->writesatisfiedstatus; $mapinfo->readnormalizedmeasure = $objmapinfo->readnormalizedmeasure; $mapinfo->writenormalizedmeasure = $objmapinfo->writenormalizedmeasure; $mapinfoid = $DB->insert_record('scorm_seq_mapinfo', $mapinfo); } } } } if (empty($defaultorgid) && (empty($scoes->defaultorg) || $scoes->defaultorg == $identifier)) { $defaultorgid = $id; } } } } if (!empty($olditems)) { foreach ($olditems as $olditem) { $DB->delete_records('scorm_scoes', array('id' => $olditem->id)); $DB->delete_records('scorm_scoes_data', array('scoid' => $olditem->id)); $DB->delete_records('scorm_scoes_track', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_objective', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_mapinfo', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_ruleconds', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rulecond', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprule', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprulecond', array('scoid' => $olditem->id)); } } if (empty($scoes->version)) { $scoes->version = 'SCORM_1.2'; } $DB->set_field('scorm', 'version', $scoes->version, array('id' => $scorm->id)); $scorm->version = $scoes->version; } $scorm->launch = 0; // Check launch sco is valid. if (!empty($defaultorgid) && isset($newscoes[$defaultorgid]) && !empty($newscoes[$defaultorgid]->launch)) { // Launch param is valid - do nothing. $scorm->launch = $defaultorgid; } else { if (!empty($defaultorgid) && isset($newscoes[$defaultorgid]) && empty($newscoes[$defaultorgid]->launch)) { // The launch is probably the default org so we need to find the first launchable item inside this org. $sqlselect = 'scorm = ? AND sortorder >= ? AND ' . $DB->sql_isnotempty('scorm_scoes', 'launch', false, true); // We use get_records here as we need to pass a limit in the query that works cross db. $scoes = $DB->get_records_select('scorm_scoes', $sqlselect, array($scorm->id, $firstinorg), 'sortorder', 'id', 0, 1); if (!empty($scoes)) { $sco = reset($scoes); // We only care about the first record - the above query only returns one. $scorm->launch = $sco->id; } } } if (empty($scorm->launch)) { // No valid Launch is specified - find the first launchable sco instead. $sqlselect = 'scorm = ? AND ' . $DB->sql_isnotempty('scorm_scoes', 'launch', false, true); // We use get_records here as we need to pass a limit in the query that works cross db. $scoes = $DB->get_records_select('scorm_scoes', $sqlselect, array($scorm->id), 'sortorder', 'id', 0, 1); if (!empty($scoes)) { $sco = reset($scoes); // We only care about the first record - the above query only returns one. $scorm->launch = $sco->id; } } return true; }
/** * Get the actual json from content provider * * @param string $www * @return array */ protected function oembed_curlcall($www) { $ret = download_file_content($www, null, null, true, 300, 20, false, NULL, false); $this->providerurl = $www; $this->providerjson = $ret->results; $result = json_decode($ret->results, true); return $result; }
function scorm_check_package($data) { global $CFG, $COURSE; require_once $CFG->libdir . '/filelib.php'; $courseid = $data->course; // Course Module ID $reference = $data->reference; // Package path $scormid = $data->instance; // scorm ID $validation = new stdClass(); if (!empty($courseid) && !empty($reference)) { $externalpackage = scorm_external_link($reference); $validation->launch = 0; $referencefield = $reference; if (empty($reference)) { $validation = null; } else { if ($reference[0] == '#') { if (isset($CFG->repositoryactivate) && $CFG->repositoryactivate) { $referencefield = $reference . '/imsmanifest.xml'; $reference = $CFG->repository . substr($reference, 1) . '/imsmanifest.xml'; } else { $validation = null; } } else { if (!$externalpackage) { $reference = $CFG->dataroot . '/' . $courseid . '/' . $reference; } } } if (!empty($scormid)) { // // SCORM Update // if (!empty($validation) && (is_file($reference) || $externalpackage)) { if (!$externalpackage) { $mdcheck = md5_file($reference); } else { if ($externalpackage) { if ($scormdir = make_upload_directory("{$courseid}/{$CFG->moddata}/scorm")) { if ($tempdir = scorm_tempdir($scormdir)) { $content = download_file_content($reference); $file = fopen($tempdir . '/' . basename($reference), 'x'); fwrite($file, $content); fclose($file); $mdcheck = md5_file($tempdir . '/' . basename($reference)); scorm_delete_files($tempdir); } } } } if ($scorm = get_record('scorm', 'id', $scormid)) { if ($scorm->reference[0] == '#') { if (isset($CFG->repositoryactivate) && $CFG->repositoryactivate) { $oldreference = $CFG->repository . substr($scorm->reference, 1) . '/imsmanifest.xml'; } else { $oldreference = $scorm->reference; } } else { if (!scorm_external_link($scorm->reference)) { $oldreference = $CFG->dataroot . '/' . $courseid . '/' . $scorm->reference; } else { $oldreference = $scorm->reference; } } $validation->launch = $scorm->launch; if ($oldreference == $reference && $mdcheck != $scorm->md5hash || $oldreference != $reference) { // This is a new or a modified package $validation->launch = 0; } else { // Old package already validated if (strpos($scorm->version, 'AICC') !== false) { $validation->pkgtype = 'AICC'; } else { $validation->pkgtype = 'SCORM'; } } } else { $validation = null; } } else { $validation = null; } } //$validation->launch = 0; if ($validation != null && $validation->launch == 0) { // // Package must be validated // $ext = strtolower(substr(basename($reference), strrpos(basename($reference), '.'))); $tempdir = ''; switch ($ext) { case '.pif': case '.zip': // Create a temporary directory to unzip package and validate package $scormdir = ''; if ($scormdir = make_upload_directory("{$courseid}/{$CFG->moddata}/scorm")) { if ($tempdir = scorm_tempdir($scormdir)) { if ($externalpackage) { $content = download_file_content($reference); $file = fopen($tempdir . '/' . basename($reference), 'x'); fwrite($file, $content); fclose($file); } else { copy("{$reference}", $tempdir . '/' . basename($reference)); } unzip_file($tempdir . '/' . basename($reference), $tempdir, false); if (!$externalpackage) { unlink($tempdir . '/' . basename($reference)); } if (is_file($tempdir . '/imsmanifest.xml')) { $validation = scorm_validate_manifest($tempdir . '/imsmanifest.xml'); $validation->pkgtype = 'SCORM'; } else { $validation = scorm_validate_aicc($tempdir); $validation->pkgtype = 'AICC'; } } else { $validation = null; } } else { $validation = null; } break; case '.xml': if (basename($reference) == 'imsmanifest.xml') { if ($externalpackage) { if ($scormdir = make_upload_directory("{$courseid}/{$CFG->moddata}/scorm")) { if ($tempdir = scorm_tempdir($scormdir)) { $content = download_file_content($reference); $file = fopen($tempdir . '/' . basename($reference), 'x'); fwrite($file, $content); fclose($file); if (is_file($tempdir . '/' . basename($reference))) { $validation = scorm_validate_manifest($tempdir . '/' . basename($reference)); } else { $validation = null; } } } } else { $validation = scorm_validate_manifest($reference); } $validation->pkgtype = 'SCORM'; } else { $validation = null; } break; default: $validation = null; break; } if ($validation == null) { if (is_dir($tempdir)) { // Delete files and temporary directory scorm_delete_files($tempdir); } } else { if ($ext == '.xml' && !$externalpackage) { $validation->datadir = dirname($referencefield); } else { $validation->datadir = substr($tempdir, strlen($scormdir)); } $validation->launch = 0; } } } else { $validation = null; } return $validation; }
$url->param('feedback', $feedback); } $PAGE->set_url($url); if (!($course = $DB->get_record('course', array('id' => $id)))) { print_error('nocourseid'); } require_login($course); $context = get_context_instance(CONTEXT_COURSE, $id); require_capability('moodle/grade:import', $context); require_capability('gradeimport/xml:view', $context); // Large files are likely to take their time and memory. Let PHP know // that we'll take longer, and that the process should be recycled soon // to free up memory. @set_time_limit(0); raise_memory_limit(MEMORY_EXTRA); $text = download_file_content($url); if ($text === false) { print_error('cannotreadfile'); } $error = ''; $importcode = import_xml_grades($text, $course, $error); if ($importcode !== false) { /// commit the code if we are up this far if (defined('USER_KEY_LOGIN')) { if (grade_import_commit($id, $importcode, $feedback, false)) { echo 'ok'; die; } else { print_error('cannotimportgrade'); //TODO: localize }
/** * Add new local file. * * @param stdClass|array $filerecord object or array describing file * @param string $url the URL to the file * @param array $options {@link download_file_content()} options * @param bool $usetempfile use temporary file for download, may prevent out of memory problems * @return stored_file */ public function create_file_from_url($filerecord, $url, array $options = null, $usetempfile = false) { $filerecord = (array) $filerecord; // Do not modify the submitted record, this cast unlinks objects. $filerecord = (object) $filerecord; // We support arrays too. $headers = isset($options['headers']) ? $options['headers'] : null; $postdata = isset($options['postdata']) ? $options['postdata'] : null; $fullresponse = isset($options['fullresponse']) ? $options['fullresponse'] : false; $timeout = isset($options['timeout']) ? $options['timeout'] : 300; $connecttimeout = isset($options['connecttimeout']) ? $options['connecttimeout'] : 20; $skipcertverify = isset($options['skipcertverify']) ? $options['skipcertverify'] : false; $calctimeout = isset($options['calctimeout']) ? $options['calctimeout'] : false; if (!isset($filerecord->filename)) { $parts = explode('/', $url); $filename = array_pop($parts); $filerecord->filename = clean_param($filename, PARAM_FILE); } $source = !empty($filerecord->source) ? $filerecord->source : $url; $filerecord->source = clean_param($source, PARAM_URL); if ($usetempfile) { check_dir_exists($this->tempdir); $tmpfile = tempnam($this->tempdir, 'newfromurl'); $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, $tmpfile, $calctimeout); if ($content === false) { throw new file_exception('storedfileproblem', 'Can not fetch file form URL'); } try { $newfile = $this->create_file_from_pathname($filerecord, $tmpfile); @unlink($tmpfile); return $newfile; } catch (Exception $e) { @unlink($tmpfile); throw $e; } } else { $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, NULL, $calctimeout); if ($content === false) { throw new file_exception('storedfileproblem', 'Can not fetch file form URL'); } return $this->create_file_from_string($filerecord, $content); } }
$u->lang = 'en'; $u->description = 'Who\'s your daddy?'; $u->url = 'http://moodle.org'; $u->idnumber = ''; $u->institution = 'Moodle HQ'; $u->department = 'Rock on!'; $u->phone1 = ''; $u->phone2 = ''; $u->address = ''; // Adds an avatar to the user. Will slow down the process. if (MDK_AVATAR) { $params = array('size' => 160, 'force' => 'y', 'default' => 'wavatar'); $url = new moodle_url('http://www.gravatar.com/avatar/' . md5($u->id . ':' . $u->username), $params); // Temporary file name if (empty($CFG->tempdir)) { $tempdir = $CFG->dataroot . "/temp"; } else { $tempdir = $CFG->tempdir; } $picture = $tempdir . '/' . 'mdk_script_users.jpg'; download_file_content($url->out(false), null, null, false, 5, 2, false, $picture); // Ensures retro compatibility if (class_exists('context_user')) { $context = context_user::instance($u->id); } else { $context = get_context_instance(CONTEXT_USER, $u->id, MUST_EXIST); } $u->picture = process_new_icon($context, 'user', 'icon', 0, $picture); } $DB->update_record('user', $u); }
/** * Implements fetchExternalData * * @param string $url Url starting with http(s):// * @return bool|null|\stdClass|string Data object if successful fetch */ public function fetchExternalData($url, $data = null) { $response = download_file_content($url, null, $data); return $response === false ? null : $response; }
/** * Returns the list of available language packs from download.moodle.org * * @return array|bool false if can not download */ public function get_remote_list_of_languages() { $source = 'http://download.moodle.org/langpack/' . $this->version . '/languages.md5'; $availablelangs = array(); if ($content = download_file_content($source)) { $alllines = explode("\n", $content); foreach ($alllines as $line) { if (!empty($line)) { $availablelangs[] = explode(',', $line); } } return $availablelangs; } else { return false; } }
function fetch_request($request) { global $CFG; make_upload_directory('/cache/youtube'); $cache = new RSSCache($CFG->dataroot . '/cache/youtube', YOUTUBE_CACHE_EXPIRATION); $cache_status = $cache->check_cache($request); if ($cache_status == 'HIT') { $cached_response = $cache->get($request); $xmlobj = XML_unserialize($cached_response); return $this->render_video_list($xmlobj); } if ($cache_status == 'STALE') { $cached_response = $cache->get($request); } $response = download_file_content($request); if (empty($response)) { $response = $cached_response; } else { $cache->set($request, $response); } $xmlobj = XML_unserialize($response); return $this->render_video_list($xmlobj); }
/** * Given the text of a link, download the linked file and return the contents. * * This is a helper method used by {@link following_should_download_bytes()} * and {@link following_should_download_between_and_bytes()} * * @param string $link the text of the link. * @return string the content of the downloaded file. */ protected function download_file_from_link($link) { // Find the link. $linknode = $this->find_link($link); $this->ensure_node_is_visible($linknode); // Get the href and check it. $url = $linknode->getAttribute('href'); if (!$url) { throw new ExpectationException('Download link does not have href attribute', $this->getSession()); } if (!preg_match('~^https?://~', $url)) { throw new ExpectationException('Download link not an absolute URL: ' . $url, $this->getSession()); } // Download the URL and check the size. $session = $this->getSession()->getCookie('MoodleSession'); return download_file_content($url, array('Cookie' => 'MoodleSession=' . $session)); }
public function test_download_file_content() { global $CFG; // Test http success first. $testhtml = $this->getExternalTestFileUrl('/test.html'); $contents = download_file_content($testhtml); $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents)); $tofile = "{$CFG->tempdir}/test.html"; @unlink($tofile); $result = download_file_content($testhtml, null, null, false, 300, 20, false, $tofile); $this->assertTrue($result); $this->assertFileExists($tofile); $this->assertSame(file_get_contents($tofile), $contents); @unlink($tofile); $result = download_file_content($testhtml, null, null, false, 300, 20, false, null, true); $this->assertSame($contents, $result); $response = download_file_content($testhtml, null, null, true); $this->assertInstanceOf('stdClass', $response); $this->assertSame('200', $response->status); $this->assertTrue(is_array($response->headers)); $this->assertRegExp('|^HTTP/1\\.[01] 200 OK$|', rtrim($response->response_code)); $this->assertSame($contents, $response->results); $this->assertSame('', $response->error); // Test https success. $testhtml = $this->getExternalTestFileUrl('/test.html', true); $contents = download_file_content($testhtml, null, null, false, 300, 20, true); $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents)); $contents = download_file_content($testhtml); $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents)); // Now 404. $testhtml = $this->getExternalTestFileUrl('/test.html_nonexistent'); $contents = download_file_content($testhtml); $this->assertFalse($contents); $this->assertDebuggingCalled(); $response = download_file_content($testhtml, null, null, true); $this->assertInstanceOf('stdClass', $response); $this->assertSame('404', $response->status); $this->assertTrue(is_array($response->headers)); $this->assertRegExp('|^HTTP/1\\.[01] 404 Not Found$|', rtrim($response->response_code)); // Do not test the response starts with DOCTYPE here because some servers may return different headers. $this->assertSame('', $response->error); // Invalid url. $testhtml = $this->getExternalTestFileUrl('/test.html'); $testhtml = str_replace('http://', 'ftp://', $testhtml); $contents = download_file_content($testhtml); $this->assertFalse($contents); // Test standard redirects. $testurl = $this->getExternalTestFileUrl('/test_redir.php'); $contents = download_file_content("{$testurl}?redir=2"); $this->assertSame('done', $contents); $response = download_file_content("{$testurl}?redir=2", null, null, true); $this->assertInstanceOf('stdClass', $response); $this->assertSame('200', $response->status); $this->assertTrue(is_array($response->headers)); $this->assertRegExp('|^HTTP/1\\.[01] 200 OK$|', rtrim($response->response_code)); $this->assertSame('done', $response->results); $this->assertSame('', $response->error); // Commented out this block if there are performance problems. /* $contents = download_file_content("$testurl?redir=6"); $this->assertFalse(false, $contents); $this->assertDebuggingCalled(); $response = download_file_content("$testurl?redir=6", null, null, true); $this->assertInstanceOf('stdClass', $response); $this->assertSame('0', $response->status); $this->assertTrue(is_array($response->headers)); $this->assertFalse($response->results); $this->assertNotEmpty($response->error); */ // Test relative redirects. $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php'); $contents = download_file_content("{$testurl}"); $this->assertSame('done', $contents); $contents = download_file_content("{$testurl}?unused=xxx"); $this->assertSame('done', $contents); }
/** * Gets the challenge HTML (javascript and non-javascript version). * This is called from the browser, and the resulting reCAPTCHA HTML widget * is embedded within the HTML form it was called from. * * @global object * @param string $pubkey A public key for reCAPTCHA * @param string $error The error given by reCAPTCHA (optional, default is null) * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false) * @return string - The HTML to be embedded in the user's form. */ function recaptcha_get_html($pubkey, $error = null, $use_ssl = false) { global $CFG, $PAGE; $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT); if ($pubkey == null || $pubkey == '') { die("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ($use_ssl) { $server = RECAPTCHA_API_SECURE_SERVER; } else { $server = RECAPTCHA_API_SERVER; } $errorpart = ""; if ($error) { $errorpart = "&error=" . $error; } require_once $CFG->libdir . '/filelib.php'; $html = download_file_content($server . '/noscript?k=' . $pubkey . $errorpart, null, null, false, 300, 20, true); preg_match('/image\\?c\\=([A-Za-z0-9\\-\\_]*)\\"/', $html, $matches); $challenge_hash = $matches[1]; $image_url = $server . '/image?c=' . $challenge_hash; $strincorrectpleasetryagain = get_string('incorrectpleasetryagain', 'auth'); $strenterthewordsabove = get_string('enterthewordsabove', 'auth'); $strenterthenumbersyouhear = get_string('enterthenumbersyouhear', 'auth'); $strgetanothercaptcha = get_string('getanothercaptcha', 'auth'); $strgetanaudiocaptcha = get_string('getanaudiocaptcha', 'auth'); $strgetanimagecaptcha = get_string('getanimagecaptcha', 'auth'); $return = html_writer::script('', $server . '/challenge?k=' . $pubkey . $errorpart); $return .= '<noscript> <div id="recaptcha_widget_noscript"> <div id="recaptcha_image_noscript"><img src="' . $image_url . '" alt="reCAPTCHA"/></div>'; if ($error == 'incorrect-captcha-sol') { $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>'; } if ($recaptchatype == 'image') { $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>'; } elseif ($recaptchatype == 'audio') { $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>'; } $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />'; $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challenge_hash . '" />'; $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>'; // Disabling audio recaptchas for now: not language-independent /* if ($recaptchatype == 'image') { $return .= '<div class="recaptcha_only_if_image"><a href="signup.php?recaptcha=audio">' . $strgetanaudiocaptcha . '</a></div>'; } elseif ($recaptchatype == 'audio') { $return .= '<div class="recaptcha_only_if_audio"><a href="signup.php?recaptcha=image">' . $strgetanimagecaptcha . '</a></div>'; } */ $return .= ' </div> </noscript>'; return $return; }
/** * Execute test client WS request * @param string $serverurl server url (including token parameter or username/password parameters) * @param string $function function name * @param array $params parameters of the called function * @return mixed */ public function simpletest($serverurl, $function, $params) { return download_file_content($serverurl . '&wsfunction=' . $function, null, $params); }
function issue_info($issueid) { static $cache = array(); if (array_key_exists($issueid, $cache)) { return $cache[$issueid]; } $xmlurl = 'http://tracker.moodle.org/si/jira.issueviews:issue-xml/' . $issueid . '/' . $issueid . '.xml'; $content = download_file_content($xmlurl); // Get the status. $open = preg_match('/Unresolved<\\/resolution>/', $content); // Get the summary. $matches = array(); preg_match('/<title>\\[' . $issueid . '\\]\\s+(.*?)<\\/title>/', $content, $matches); $summary = $matches[1]; preg_match('/<assignee[^>]*>(.*?)<\\/assignee>/', $content, $matches); $summary .= ' - Assignee: ' . $matches[1]; $cache[$issueid] = array($open, $summary); return $cache[$issueid]; }
public function add_file($section, $name, $path, $display = 0) { global $DB, $CFG, $USER; $section = (int) $section; $display = (int) $display; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/mod/resource/lib.php'; require_once $CFG->dirroot . '/mod/resource/locallib.php'; $params = self::validate_parameters(self::add_file_parameters(), array('section' => $section, 'name' => $name, 'path' => $path, 'display' => $display)); $section = $DB->get_record('course_sections', array('id' => $section), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $section->course), '*', MUST_EXIST); self::require_access($course->id); // finally create the file item // first add course_module record because we need the context $newcm = new stdClass(); $newcm->course = $course->id; $newcm->module = $DB->get_field('modules', 'id', array('name' => 'resource')); // not known yet, will be updated later (this is similar to restore code) $newcm->instance = 0; $newcm->section = $params['section']; $newcm->visible = 1; $newcm->groupmode = 0; $newcm->groupingid = 0; $newcm->groupmembersonly = 0; if (!($coursemodule = add_course_module($newcm))) { throw new invalid_parameter_exception('Error creating course module'); } $config = get_config('resource'); $module = new stdClass(); $module->course = $course->id; $module->name = format_string($params['name']); $module->intro = '<p></p>'; $module->introformat = 1; $module->coursemodule = $coursemodule; if (!$display) { $module->display = $config->display; } else { $module->display = $display; } $module->popupwidth = $config->popupwidth; $module->popupheight = $config->popupheight; $module->printheading = $config->printheading; $module->printintro = $config->printintro; // 'Show size' support only from Moodle 2.3 / OU moodle April 2012 if (isset($config->showsize)) { $module->showsize = $config->showsize; $module->showtype = $config->showtype; } $module->filterfiles = $config->filterfiles; $module->section = $section->section; //check $params['path'] and create files based on that and attach to $module->files //now check $path and obtain $filename and $filepath $contextuser = get_context_instance(CONTEXT_USER, $USER->id); $fs = get_file_storage(); $module->files = 0; file_prepare_draft_area($module->files, null, null, null, null); $fileinfo = array('contextid' => $contextuser->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $module->files, 'filepath' => '/', 'filename' => basename($params['path']), 'timecreated' => time(), 'timemodified' => time(), 'mimetype' => mimeinfo('type', $path), 'userid' => $USER->id); if (strpos($params['path'], '://') === false) { //this is a path if (!file_exists($params['path'])) { throw new invalid_parameter_exception('Error accessing filepath - file may not exist.'); } $fs->create_file_from_pathname($fileinfo, $params['path']); } else { //this is a URL - download the file first. $content = download_file_content($params['path']); if ($content === false) { throw new invalid_parameter_exception('Error accessing file - url may not exist.'); } $fs->create_file_from_string($fileinfo, $content); } $module->instance = resource_add_instance($module, array()); $DB->set_field('course_modules', 'instance', $module->instance, array('id' => $coursemodule)); add_mod_to_section($module); rebuild_course_cache($course->id, true); return array('id' => $coursemodule); }
function scorm_parse_scorm($scorm, $manifest) { global $CFG, $DB; // load manifest into string if ($manifest instanceof stored_file) { $xmltext = $manifest->get_content(); } else { require_once "{$CFG->libdir}/filelib.php"; $xmltext = download_file_content($manifest); } $launch = 0; $pattern = '/&(?!\\w{2,6};)/'; $replacement = '&'; $xmltext = preg_replace($pattern, $replacement, $xmltext); $objXML = new xml2Array(); $manifests = $objXML->parse($xmltext); //print_object($manifests); $scoes = new stdClass(); $scoes->version = ''; $scoes = scorm_get_manifest($manifests, $scoes); //print_object($scoes); if (count($scoes->elements) > 0) { $olditems = $DB->get_records('scorm_scoes', array('scorm' => $scorm->id)); foreach ($scoes->elements as $manifest => $organizations) { foreach ($organizations as $organization => $items) { foreach ($items as $identifier => $item) { // This new db mngt will support all SCORM future extensions $newitem = new stdClass(); $newitem->scorm = $scorm->id; $newitem->manifest = $manifest; $newitem->organization = $organization; $standarddatas = array('parent', 'identifier', 'launch', 'scormtype', 'title'); foreach ($standarddatas as $standarddata) { if (isset($item->{$standarddata})) { $newitem->{$standarddata} = $item->{$standarddata}; } } // Insert the new SCO, and retain the link between the old and new for later adjustment $id = $DB->insert_record('scorm_scoes', $newitem); if (!empty($olditems) && ($olditemid = scorm_array_search('identifier', $newitem->identifier, $olditems))) { $olditems[$olditemid]->newid = $id; } if ($optionaldatas = scorm_optionals_data($item, $standarddatas)) { $data = new stdClass(); $data->scoid = $id; foreach ($optionaldatas as $optionaldata) { if (isset($item->{$optionaldata})) { $data->name = $optionaldata; $data->value = $item->{$optionaldata}; $dataid = $DB->insert_record('scorm_scoes_data', $data); } } } if (isset($item->sequencingrules)) { foreach ($item->sequencingrules as $sequencingrule) { $rule = new stdClass(); $rule->scoid = $id; $rule->ruletype = $sequencingrule->type; $rule->conditioncombination = $sequencingrule->conditioncombination; $rule->action = $sequencingrule->action; $ruleid = $DB->insert_record('scorm_seq_ruleconds', $rule); if (isset($sequencingrule->ruleconditions)) { foreach ($sequencingrule->ruleconditions as $rulecondition) { $rulecond = new stdClass(); $rulecond->scoid = $id; $rulecond->ruleconditionsid = $ruleid; $rulecond->referencedobjective = $rulecondition->referencedobjective; $rulecond->measurethreshold = $rulecondition->measurethreshold; $rulecond->cond = $rulecondition->cond; $rulecondid = $DB->insert_record('scorm_seq_rulecond', $rulecond); } } } } if (isset($item->rolluprules)) { foreach ($item->rolluprules as $rolluprule) { $rollup = new stdClass(); $rollup->scoid = $id; $rollup->childactivityset = $rolluprule->childactivityset; $rollup->minimumcount = $rolluprule->minimumcount; $rollup->minimumpercent = $rolluprule->minimumpercent; $rollup->rollupruleaction = $rolluprule->rollupruleaction; $rollup->conditioncombination = $rolluprule->conditioncombination; $rollupruleid = $DB->insert_record('scorm_seq_rolluprule', $rollup); if (isset($rollup->conditions)) { foreach ($rollup->conditions as $condition) { $cond = new stdClass(); $cond->scoid = $rollup->scoid; $cond->rollupruleid = $rollupruleid; $cond->operator = $condition->operator; $cond->cond = $condition->cond; $conditionid = $DB->insert_record('scorm_seq_rolluprulecond', $cond); } } } } if (isset($item->objectives)) { foreach ($item->objectives as $objective) { $obj = new stdClass(); $obj->scoid = $id; $obj->primaryobj = $objective->primaryobj; $obj->satisfiedbumeasure = $objective->satisfiedbymeasure; $obj->objectiveid = $objective->objectiveid; $obj->minnormalizedmeasure = $objective->minnormalizedmeasure; $objectiveid = $DB->insert_record('scorm_seq_objective', $obj); if (isset($objective->mapinfos)) { //print_object($objective->mapinfos); foreach ($objective->mapinfos as $objmapinfo) { $mapinfo = new stdClass(); $mapinfo->scoid = $id; $mapinfo->objectiveid = $objectiveid; $mapinfo->targetobjectiveid = $objmapinfo->targetobjectiveid; $mapinfo->readsatisfiedstatus = $objmapinfo->readsatisfiedstatus; $mapinfo->writesatisfiedstatus = $objmapinfo->writesatisfiedstatus; $mapinfo->readnormalizedmeasure = $objmapinfo->readnormalizedmeasure; $mapinfo->writenormalizedmeasure = $objmapinfo->writenormalizedmeasure; $mapinfoid = $DB->insert_record('scorm_seq_mapinfo', $mapinfo); } } } } //print_object($item); if ($launch == 0 && (empty($scoes->defaultorg) || $scoes->defaultorg == $identifier)) { $launch = $id; } } } } if (!empty($olditems)) { foreach ($olditems as $olditem) { $DB->delete_records('scorm_scoes', array('id' => $olditem->id)); $DB->delete_records('scorm_scoes_data', array('scoid' => $olditem->id)); if (isset($olditem->newid)) { $DB->set_field('scorm_scoes_track', 'scoid', $olditem->newid, array('scoid' => $olditem->id)); } $DB->delete_records('scorm_scoes_track', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_objective', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_mapinfo', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_ruleconds', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rulecond', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprule', array('scoid' => $olditem->id)); $DB->delete_records('scorm_seq_rolluprulecond', array('scoid' => $olditem->id)); } } if (empty($scoes->version)) { $scoes->version = 'SCORM_1.2'; } $DB->set_field('scorm', 'version', $scoes->version, array('id' => $scorm->id)); $scorm->version = $scoes->version; } $scorm->launch = $launch; return true; }
/** * Returns the latest list of available language packs from * moodle.org * @return array or false if can not download */ function get_remote_list_of_languages() { $source = 'http://download.moodle.org/lang16/languages.md5'; $availablelangs = array(); if ($content = download_file_content($source)) { $alllines = split("\n", $content); foreach ($alllines as $line) { if (!empty($line)) { $availablelangs[] = split(',', $line); } } return $availablelangs; } else { return false; } }
if ($timezones = olson_to_timezones($source)) { update_timezone_records($timezones); $importdone = $source; } } /// Next, look for a CSV file locally $source = $CFG->dataroot . '/temp/timezone.txt'; if (!$importdone and is_readable($source)) { if ($timezones = get_records_csv($source, 'timezone')) { update_timezone_records($timezones); $importdone = $source; } } /// Otherwise, let's try moodle.org's copy $source = 'http://download.moodle.org/timezone/'; if (!$importdone && ($content = download_file_content($source))) { if ($file = fopen($CFG->dataroot . '/temp/timezone.txt', 'w')) { // Make local copy fwrite($file, $content); fclose($file); if ($timezones = get_records_csv($CFG->dataroot . '/temp/timezone.txt', 'timezone')) { // Parse it update_timezone_records($timezones); $importdone = $source; } unlink($CFG->dataroot . '/temp/timezone.txt'); } } /// Final resort, use the copy included in Moodle $source = $CFG->dirroot . '/lib/timezone.txt'; if (!$importdone and is_readable($source)) {
/** * Parse moss result page and store to DB * * @param string $url moss result page url * @param int $configid * @return true or false */ protected function save_results($url, $configid) { global $DB, $UNITTEST; mtrace("\tProcessing $url"); if (!$result_page = download_file_content($url)) { mtrace("\tcan not read $url"); return false; } preg_match_all( '/(?P<link>http:\/\/moss\.stanford\.edu\/results\/\d+\/match\d+\.html)">.+\/(?P<user1>\d+)\/ \((?P<percentage1>\d+)%\).+\/(?P<user2>\d+)\/ \((?P<percentage2>\d+)%\).+right>(?P<linesmatched>\d+)\\n/Us', $result_page, $matches, PREG_SET_ORDER ); if (empty($matches)) { mtrace("\tcan not parse $url"); return false; } if (!isset($UNITTEST)) { // testcase can not construct course structure $context = get_context_instance(CONTEXT_COURSE, $this->moss->course); } $filepatterns = $DB->get_field('moss_configs', 'filepatterns', array('id' => $configid)); $filepatterns = explode(' ', $filepatterns); $fs = get_file_storage(); $rank = 1; foreach ($matches as $result) { $result['moss'] = $this->moss->id; $result['config'] = $configid; $result['rank'] = $rank + 1; $result1 = (object)$result; $result1->userid = $result['user1']; $result1->percentage = $result['percentage1']; $result2 = (object)$result; $result2->userid = $result['user2']; $result2->percentage = $result['percentage2']; if (!isset($UNITTEST)) { // testcase can not construct course structure // skip unenrolled users if (!is_enrolled($context, $result1->userid) and !is_enrolled($context, $result2->userid)) { continue; } } $result1->id = $DB->insert_record('moss_results', $result1); $result2->pair = $result1->id; $result2->id = $DB->insert_record('moss_results', $result2); $result1->pair = $result2->id; $DB->update_record('moss_results', $result1); // update moss_matched_files db for ($i=1; $i<=2; $i++) { $userid = eval('return $result'.$i.'->userid;'); $resultid = eval('return $result'.$i.'->id;'); $files = $fs->get_directory_files(get_system_context()->id, 'plagiarism_moss', 'files', $this->moss->cmid, "/$userid/"); foreach ($files as $file) { foreach ($filepatterns as $pattern) { if (fnmatch($pattern, $file->get_filename())) { $obj = new stdClass(); $obj->result = $resultid; $obj->contenthash = $file->get_contenthash(); $DB->insert_record('moss_matched_files', $obj); } } } } $rank++; } mtrace("\tGot $rank pairs"); return true; }
/** * Authentication hook - is called every time user hit the login page * The code is run only if the param code is mentionned. */ public function loginpage_hook() { global $USER, $SESSION, $CFG, $DB; // Check the Google authorization code. $authorizationcode = optional_param('code', '', PARAM_TEXT); if (!empty($authorizationcode)) { $authprovider = required_param('authprovider', PARAM_ALPHANUMEXT); require_once $CFG->dirroot . '/auth/googleoauth2/classes/provider/' . $authprovider . '.php'; $providerclassname = 'provideroauth2' . $authprovider; $provider = new $providerclassname(); // Try to get an access token (using the authorization code grant). $token = $provider->getAccessToken('authorization_code', ['code' => $authorizationcode]); $accesstoken = $token->accessToken; $refreshtoken = $token->refreshToken; $tokenexpires = $token->expires; // With access token request by curl the email address. if (!empty($accesstoken)) { try { // We got an access token, let's now get the user's details. $userdetails = $provider->getUserDetails($token); // Use these details to create a new profile. switch ($authprovider) { case 'battlenet': // Battlenet as no email notion. // TODO: need to check the idp table for matching user and request user to add his email. // TODO: It will be similar logic for twitter. $useremail = $userdetails->id . '@fakebattle.net'; break; case 'github': $useremails = $provider->getUserEmails($token); // Going to try to find someone with a similar email using googleoauth2 auth. $fallbackuseremail = ''; foreach ($useremails as $githubuseremail) { if ($githubuseremail->verified) { if ($DB->record_exists('user', array('auth' => 'googleoauth2', 'email' => $githubuseremail->email))) { $useremail = $githubuseremail->email; } $fallbackuseremail = $githubuseremail->email; } } // If we didn't find anyone then we take a verified email address. if (empty($useremail)) { $useremail = $fallbackuseremail; } break; case 'vk': // VK doesn't return the email address? if ($userdetails->uid) { $useremail = 'id' . $userdetails->uid . '@vkmessenger.com'; } break; default: $useremail = $userdetails->email; break; } $verified = 1; } catch (Exception $e) { // Failed to get user details. throw new moodle_exception('faileduserdetails', 'auth_googleoauth2'); } // Throw an error if the email address is not verified. if (!$verified) { throw new moodle_exception('emailaddressmustbeverified', 'auth_googleoauth2'); } // Prohibit login if email belongs to the prohibited domain. if ($err = email_is_not_allowed($useremail)) { throw new moodle_exception($err, 'auth_googleoauth2'); } // If email not existing in user database then create a new username (userX). if (empty($useremail) or $useremail != clean_param($useremail, PARAM_EMAIL)) { throw new moodle_exception('couldnotgetuseremail', 'auth_googleoauth2'); // TODO: display a link for people to retry. } // Get the user. // Don't bother with auth = googleoauth2 because authenticate_user_login() will fail it if it's not 'googleoauth2'. $user = $DB->get_record('user', array('email' => $useremail, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id)); // Create the user if it doesn't exist. if (empty($user)) { // Deny login if setting "Prevent account creation when authenticating" is on. if ($CFG->authpreventaccountcreation) { throw new moodle_exception("noaccountyet", "auth_googleoauth2"); } // Get following incremented username. $googleuserprefix = core_text::strtolower(get_config('auth/googleoauth2', 'googleuserprefix')); $lastusernumber = get_config('auth/googleoauth2', 'lastusernumber'); $lastusernumber = empty($lastusernumber) ? 1 : $lastusernumber + 1; // Check the user doesn't exist. $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber)); while ($nextuser) { $lastusernumber++; $nextuser = $DB->record_exists('user', array('username' => $googleuserprefix . $lastusernumber)); } set_config('lastusernumber', $lastusernumber, 'auth/googleoauth2'); $username = $googleuserprefix . $lastusernumber; // Retrieve more information from the provider. $newuser = new stdClass(); $newuser->email = $useremail; switch ($authprovider) { case 'battlenet': // Battlenet as no firstname/lastname notion. $newuser->firstname = $userdetails->display_name; $newuser->lastname = '[' . $userdetails->clan_tag . ']'; break; case 'github': case 'dropbox': // As Github/Dropbox doesn't provide firstname/lastname, we'll split the name at the first whitespace. $githubusername = explode(' ', $userdetails->name, 2); $newuser->firstname = $githubusername[0]; $newuser->lastname = $githubusername[1]; break; default: $newuser->firstname = $userdetails->firstName; $newuser->lastname = $userdetails->lastName; break; } // Some providers allow empty firstname and lastname. if (empty($newuser->firstname)) { $newuser->firstname = get_string('unknownfirstname', 'auth_googleoauth2'); } if (empty($newuser->lastname)) { $newuser->lastname = get_string('unknownlastname', 'auth_googleoauth2'); } // Retrieve country and city if the provider failed to give it. if (!isset($newuser->country) or !isset($newuser->city)) { $googleipinfodbkey = get_config('auth/googleoauth2', 'googleipinfodbkey'); if (!empty($googleipinfodbkey)) { require_once $CFG->libdir . '/filelib.php'; $curl = new curl(); $locationdata = $curl->get('http://api.ipinfodb.com/v3/ip-city/?key=' . $googleipinfodbkey . '&ip=' . getremoteaddr() . '&format=json'); $locationdata = json_decode($locationdata); } if (!empty($locationdata)) { // TODO: check that countryCode does match the Moodle country code. $newuser->country = isset($newuser->country) ? isset($newuser->country) : $locationdata->countryCode; $newuser->city = isset($newuser->city) ? isset($newuser->city) : $locationdata->cityName; } } create_user_record($username, '', 'googleoauth2'); } else { $username = $user->username; } // Authenticate the user. // TODO: delete this log later. require_once $CFG->dirroot . '/auth/googleoauth2/lib.php'; $userid = empty($user) ? 'new user' : $user->id; oauth_add_to_log(SITEID, 'auth_googleoauth2', '', '', $username . '/' . $useremail . '/' . $userid); $user = authenticate_user_login($username, null); if ($user) { // Set a cookie to remember what auth provider was selected. setcookie('MOODLEGOOGLEOAUTH2_' . $CFG->sessioncookie, $authprovider, time() + DAYSECS * 60, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly); // Prefill more user information if new user. if (!empty($newuser)) { $newuser->id = $user->id; $DB->update_record('user', $newuser); $user = (object) array_merge((array) $user, (array) $newuser); } complete_user_login($user); // Let's save/update the access token for this user. $cansaveaccesstoken = get_config('auth/googleoauth2', 'saveaccesstoken'); if (!empty($cansaveaccesstoken)) { $existingaccesstoken = $DB->get_record('auth_googleoauth2_user_idps', array('userid' => $user->id, 'provider' => $authprovider)); if (empty($existingaccesstoken)) { $accesstokenrow = new stdClass(); $accesstokenrow->userid = $user->id; switch ($authprovider) { case 'battlenet': $accesstokenrow->provideruserid = $userdetails->id; break; default: $accesstokenrow->provideruserid = $userdetails->uid; break; } $accesstokenrow->provider = $authprovider; $accesstokenrow->accesstoken = $accesstoken; $accesstokenrow->refreshtoken = $refreshtoken; $accesstokenrow->expires = $tokenexpires; $DB->insert_record('auth_googleoauth2_user_idps', $accesstokenrow); } else { $existingaccesstoken->accesstoken = $accesstoken; $DB->update_record('auth_googleoauth2_user_idps', $existingaccesstoken); } } // Check if the user picture is the default and retrieve the provider picture. if (empty($user->picture)) { switch ($authprovider) { case 'battlenet': require_once $CFG->libdir . '/filelib.php'; require_once $CFG->libdir . '/gdlib.php'; $imagefilename = $CFG->tempdir . '/googleoauth2-portrait-' . $user->id; $imagecontents = download_file_content($userdetails->portrait_url); file_put_contents($imagefilename, $imagecontents); if ($newrev = process_new_icon(context_user::instance($user->id), 'user', 'icon', 0, $imagefilename)) { $DB->set_field('user', 'picture', $newrev, array('id' => $user->id)); } unlink($imagefilename); break; default: // TODO retrieve other provider profile pictures. break; } } // Create event for authenticated user. $event = \auth_googleoauth2\event\user_loggedin::create(array('context' => context_system::instance(), 'objectid' => $user->id, 'relateduserid' => $user->id, 'other' => array('accesstoken' => $accesstoken))); $event->trigger(); // Redirection. if (user_not_fully_set_up($USER)) { $urltogo = $CFG->wwwroot . '/user/edit.php'; // We don't delete $SESSION->wantsurl yet, so we get there later. } else { if (isset($SESSION->wantsurl) and strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) { $urltogo = $SESSION->wantsurl; // Because it's an address in this site. unset($SESSION->wantsurl); } else { // No wantsurl stored or external - go to homepage. $urltogo = $CFG->wwwroot . '/'; unset($SESSION->wantsurl); } } $loginrecord = array('userid' => $USER->id, 'time' => time(), 'auth' => 'googleoauth2', 'subtype' => $authprovider); $DB->insert_record('auth_googleoauth2_logins', $loginrecord); redirect($urltogo); } else { // Authenticate_user_login() failure, probably email registered by another auth plugin. // Do a check to confirm this hypothesis. $userexist = $DB->get_record('user', array('email' => $useremail)); if (!empty($userexist) and $userexist->auth != 'googleoauth2') { $a = new stdClass(); $a->loginpage = (string) new moodle_url(empty($CFG->alternateloginurl) ? '/login/index.php' : $CFG->alternateloginurl); $a->forgotpass = (string) new moodle_url('/login/forgot_password.php'); throw new moodle_exception('couldnotauthenticateuserlogin', 'auth_googleoauth2', '', $a); } else { throw new moodle_exception('couldnotauthenticate', 'auth_googleoauth2'); } } } else { throw new moodle_exception('couldnotgetgoogleaccesstoken', 'auth_googleoauth2'); } } else { // If you are having issue with the display buttons option, add the button code directly in the theme login page. if (get_config('auth/googleoauth2', 'oauth2displaybuttons') and empty($_POST['username']) and empty($_POST['password'])) { // Display the button on the login page. require_once $CFG->dirroot . '/auth/googleoauth2/lib.php'; // Insert the html code below the login field. // Code/Solution from Elcentra plugin: https://moodle.org/plugins/view/auth_elcentra. global $PAGE, $CFG; $PAGE->requires->jquery(); $content = str_replace(array("\n", "\r"), array("\\\n", "\\\r"), auth_googleoauth2_display_buttons(false)); $PAGE->requires->css('/auth/googleoauth2/style.css'); $PAGE->requires->js_init_code("buttonsCodeOauth2 = '{$content}';"); $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/googleoauth2/script.js")); } } }
/** * Performs an action on authorize.net and updates/inserts records. If record update fails, * sends email to admin. * * @param object &$order Which transaction data will be sent. See enrol_authorize table. * @param string &$message Information about error message. * @param object &$extra Extra data that used for refunding and credit card information. * @param int $action Which action will be performed. See AN_ACTION_* * @param string $cctype Used internally to configure credit types automatically. * @return int AN_APPROVED Transaction was successful, AN_RETURNZERO otherwise. Use $message for reason. */ public static function process(&$order, &$message, &$extra, $action = AN_ACTION_NONE, $cctype = NULL) { global $CFG, $DB; static $constpd = array(); require_once $CFG->libdir . '/filelib.php'; $mconfig = get_config('enrol_authorize'); if (empty($constpd)) { $mconfig = get_config('enrol_authorize'); $constpd = array('x_version' => '3.1', 'x_delim_data' => 'True', 'x_delim_char' => self::AN_DELIM, 'x_encap_char' => self::AN_ENCAP, 'x_relay_response' => 'FALSE', 'x_login' => $mconfig->an_login); if (!empty($mconfig->an_tran_key)) { $constpd['x_tran_key'] = $mconfig->an_tran_key; } else { $constpd['x_password'] = $mconfig->an_password; } } if (empty($order) or empty($order->id)) { $message = "Check order->id!"; return AN_RETURNZERO; } $method = $order->paymentmethod; if (empty($method)) { $method = AN_METHOD_CC; } elseif ($method != AN_METHOD_CC && $method != AN_METHOD_ECHECK) { $message = "Invalid method: {$method}"; return AN_RETURNZERO; } $action = intval($action); if ($method == AN_METHOD_ECHECK) { if ($action != AN_ACTION_AUTH_CAPTURE && $action != AN_ACTION_CREDIT) { $message = "Please perform AUTH_CAPTURE or CREDIT for echecks"; return AN_RETURNZERO; } } $pd = $constpd; $pd['x_method'] = $method; $test = !empty($mconfig->an_test); $pd['x_test_request'] = $test ? 'TRUE' : 'FALSE'; switch ($action) { case AN_ACTION_AUTH_ONLY: case AN_ACTION_CAPTURE_ONLY: case AN_ACTION_AUTH_CAPTURE: if ($order->status != AN_STATUS_NONE) { $message = "Order status must be AN_STATUS_NONE(0)!"; return AN_RETURNZERO; } elseif (empty($extra)) { $message = "Need extra fields!"; return AN_RETURNZERO; } elseif ($action == AN_ACTION_CAPTURE_ONLY and empty($extra->x_auth_code)) { $message = "x_auth_code is required for capture only transactions!"; return AN_RETURNZERO; } $ext = (array) $extra; $pd['x_type'] = $action == AN_ACTION_AUTH_ONLY ? 'AUTH_ONLY' : ($action == AN_ACTION_CAPTURE_ONLY ? 'CAPTURE_ONLY' : 'AUTH_CAPTURE'); foreach ($ext as $k => $v) { $pd[$k] = $v; } break; case AN_ACTION_PRIOR_AUTH_CAPTURE: if ($order->status != AN_STATUS_AUTH) { $message = "Order status must be authorized!"; return AN_RETURNZERO; } if (self::expired($order)) { $message = "Transaction must be captured within 30 days. EXPIRED!"; return AN_RETURNZERO; } $pd['x_type'] = 'PRIOR_AUTH_CAPTURE'; $pd['x_trans_id'] = $order->transid; break; case AN_ACTION_CREDIT: if ($order->status != AN_STATUS_AUTHCAPTURE) { $message = "Order status must be authorized/captured!"; return AN_RETURNZERO; } if (!self::settled($order)) { $message = "Order must be settled. Try VOID, check Cut-Off time if it fails!"; return AN_RETURNZERO; } if (empty($extra->amount)) { $message = "No valid amount!"; return AN_RETURNZERO; } $timenowsettle = self::getsettletime(time()); $timediff = $timenowsettle - 120 * 3600 * 24; if ($order->settletime < $timediff) { $message = "Order must be credited within 120 days!"; return AN_RETURNZERO; } $pd['x_type'] = 'CREDIT'; $pd['x_trans_id'] = $order->transid; $pd['x_currency_code'] = $order->currency; $pd['x_invoice_num'] = $extra->orderid; $pd['x_amount'] = $extra->amount; if ($method == AN_METHOD_CC) { $pd['x_card_num'] = sprintf("%04d", intval($order->refundinfo)); } elseif ($method == AN_METHOD_ECHECK && empty($order->refundinfo)) { $message = "Business checkings can be refunded only."; return AN_RETURNZERO; } break; case AN_ACTION_VOID: if (self::expired($order) || self::settled($order)) { $message = "The transaction cannot be voided due to the fact that it is expired or settled."; return AN_RETURNZERO; } $pd['x_type'] = 'VOID'; $pd['x_trans_id'] = $order->transid; break; default: $message = "Invalid action: {$action}"; return AN_RETURNZERO; } $headers = array('Connection' => 'close'); if (!(empty($mconfig->an_referer) || $mconfig->an_referer == "http://")) { $headers['Referer'] = $mconfig->an_referer; } @ignore_user_abort(true); if (intval(ini_get('max_execution_time')) > 0) { @set_time_limit(300); } $host = $test ? 'test.authorize.net' : 'secure.authorize.net'; $data = download_file_content("https://{$host}:443/gateway/transact.dll", $headers, $pd, false, 300, 60, true); if (!$data) { $message = "No connection to https://{$host}:443"; return AN_RETURNZERO; } $response = explode(self::AN_ENCAP . self::AN_DELIM . self::AN_ENCAP, $data); if ($response === false) { $message = "response error"; return AN_RETURNZERO; } $rcount = count($response) - 1; if ($response[0][0] == self::AN_ENCAP) { $response[0] = substr($response[0], 1); } if (substr($response[$rcount], -1) == self::AN_ENCAP) { $response[$rcount] = substr($response[$rcount], 0, -1); } $responsecode = intval($response[0]); if ($responsecode == AN_APPROVED || $responsecode == AN_REVIEW) { $transid = floatval($response[6]); if ($test || $transid == 0) { return $responsecode; // don't update original transaction in test mode. } switch ($action) { case AN_ACTION_AUTH_ONLY: case AN_ACTION_CAPTURE_ONLY: case AN_ACTION_AUTH_CAPTURE: case AN_ACTION_PRIOR_AUTH_CAPTURE: $order->transid = $transid; if ($method == AN_METHOD_CC) { if ($action == AN_ACTION_AUTH_ONLY || $responsecode == AN_REVIEW) { $order->status = AN_STATUS_AUTH; } else { $order->status = AN_STATUS_AUTHCAPTURE; $order->settletime = self::getsettletime(time()); } } elseif ($method == AN_METHOD_ECHECK) { $order->status = AN_STATUS_UNDERREVIEW; } $DB->update_record('enrol_authorize', $order); break; case AN_ACTION_CREDIT: // Credit generates new transaction id. // So, $extra must be updated, not $order. $extra->status = AN_STATUS_CREDIT; $extra->transid = $transid; $extra->settletime = self::getsettletime(time()); $extra->id = $DB->insert_record('enrol_authorize_refunds', $extra); break; case AN_ACTION_VOID: $tableupdate = 'enrol_authorize'; if ($order->status == AN_STATUS_CREDIT) { $tableupdate = 'enrol_authorize_refunds'; unset($order->paymentmethod); } $order->status = AN_STATUS_VOID; $DB->update_record($tableupdate, $order); break; } } else { $reasonno = $response[2]; $reasonstr = "reason" . $reasonno; $message = get_string($reasonstr, "enrol_authorize"); if ($message == '[[' . $reasonstr . ']]') { $message = isset($response[3]) ? $response[3] : 'unknown error'; } if ($method == AN_METHOD_CC && !empty($mconfig->an_avs) && $response[5] != "P") { $avs = "avs" . strtolower($response[5]); $stravs = get_string($avs, "enrol_authorize"); $message .= "<br />" . get_string("avsresult", "enrol_authorize", $stravs); } if (!$test) { // Autoconfigure :) switch ($reasonno) { // Credit card type isn't accepted case self::AN_REASON_NOCCTYPE: case self::AN_REASON_NOCCTYPE2: if (!empty($cctype)) { $ccaccepts = get_list_of_creditcards(); unset($ccaccepts[$cctype]); set_config("an_acceptcc_{$cctype}", 0, 'enrol_authorize'); foreach ($ccaccepts as $key => $val) { set_config("an_acceptcc_{$key}", 1, 'enrol_authorize'); } message_to_admin("{$message} ({$cctype}) This is new config(an_acceptccs):", $ccaccepts); } break; // Echecks only // Echecks only case self::AN_REASON_ACHONLY: set_config("an_acceptmethod_" . AN_METHOD_ECHECK, 1, 'enrol_authorize'); message_to_admin("{$message} This is new config(an_acceptmethods):", array(AN_METHOD_ECHECK)); break; // Echecks aren't accepted // Echecks aren't accepted case self::AN_REASON_NOACH: set_config("an_acceptmethod_" . AN_METHOD_CC, 1, 'enrol_authorize'); message_to_admin("{$message} This is new config(an_acceptmethods):", array(AN_METHOD_CC)); break; // This echeck type isn't accepted // This echeck type isn't accepted case self::AN_REASON_NOACHTYPE: case self::AN_REASON_NOACHTYPE2: if (!empty($extra->x_echeck_type)) { switch ($extra->x_echeck_type) { // CCD=BUSINESSCHECKING case 'CCD': set_config('an_acceptecheck_CHECKING', 1, 'enrol_authorize'); set_config('an_acceptecheck_SAVINGS', 1, 'enrol_authorize'); message_to_admin("{$message} This is new config(an_acceptechecktypes):", array('CHECKING', 'SAVINGS')); break; // WEB=CHECKING or SAVINGS // WEB=CHECKING or SAVINGS case 'WEB': set_config('an_acceptecheck_BUSINESSCHECKING', 1, 'enrol_authorize'); message_to_admin("{$message} This is new config(an_acceptechecktypes):", array('BUSINESSCHECKING')); break; } } break; } } } return $responsecode; }
function fetch_request($request) { global $CFG; make_upload_directory('/cache/flickr'); $cache = new RSSCache($CFG->dataroot . '/cache/flickr', FLICKR_CACHE_EXPIRATION); $cache_status = $cache->check_cache($request); if ($cache_status == 'HIT') { $cached_response = $cache->get($request); return $cached_response; } if ($cache_status == 'STALE') { $cached_response = $cache->get($request); } $response = download_file_content($request); if (empty($response)) { $response = $cached_response; } else { $cache->set($request, $response); } return $response; }