Exemple #1
0
 /**
  * Return user information including profile picture + basic site information
  * Note:
  * - no capability checking because we return just known information by logged user
  * @param array $serviceshortnames of service shortnames - the functions of these services will be returned
  * @return array
  */
 public function get_site_info($serviceshortnames = array())
 {
     global $USER, $SITE, $CFG;
     $params = self::validate_parameters(self::get_site_info_parameters(), array('serviceshortnames' => $serviceshortnames));
     $profileimageurl = moodle_url::make_pluginfile_url(get_context_instance(CONTEXT_USER, $USER->id)->id, 'user', 'icon', NULL, '/', 'f1');
     require_once $CFG->dirroot . "/webservice/lib.php";
     $webservice = new webservice();
     //If no service listed always return the mobile one by default
     if (empty($params['serviceshortnames']) and $CFG->enablewebservices) {
         $mobileservice = $webservice->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
         if ($mobileservice->enabled) {
             $params['serviceshortnames'] = array(MOODLE_OFFICIAL_MOBILE_SERVICE);
             //return mobile service by default
         }
     }
     //retrieve the functions related to the services
     $functions = $webservice->get_external_functions_by_enabled_services($params['serviceshortnames']);
     //built up the returned values of the list of functions
     $componentversions = array();
     $avalaiblefunctions = array();
     foreach ($functions as $function) {
         $functioninfo = array();
         $functioninfo['name'] = $function->name;
         if ($function->component == 'moodle') {
             $version = $CFG->version;
             //moodle version
         } else {
             $versionpath = get_component_directory($function->component) . '/version.php';
             if (is_readable($versionpath)) {
                 //we store the component version once retrieved (so we don't load twice the version.php)
                 if (!isset($componentversions[$function->component])) {
                     include $versionpath;
                     $componentversions[$function->component] = $plugin->version;
                     $version = $plugin->version;
                 } else {
                     $version = $componentversions[$function->component];
                 }
             } else {
                 //function component should always have a version.php,
                 //otherwise the function should have been described with component => 'moodle'
                 throw new moodle_exception('missingversionfile', 'webservice', '', $function->component);
             }
         }
         $functioninfo['version'] = $version;
         $avalaiblefunctions[] = $functioninfo;
     }
     return array('sitename' => $SITE->fullname, 'siteurl' => $CFG->wwwroot, 'username' => $USER->username, 'firstname' => $USER->firstname, 'lastname' => $USER->lastname, 'fullname' => fullname($USER), 'userid' => $USER->id, 'userpictureurl' => $profileimageurl->out(false), 'functions' => $avalaiblefunctions);
 }
Exemple #2
0
 public static function get_cuentas()
 {
     $db = new db_core();
     $webservice = new webservice();
     $cuentas = array();
     $consulta[0] = $db->db_query("SELECT * FROM cuentas_bancarias AS c WHERE c.id_user='******'token']) . "'");
     while ($consulta[1] = mysql_fetch_array($consulta[0])) {
         $cantidad = $db->reg_one("SELECT COUNT(*) FROM inversion_proyecto AS i WHERE i.id_cuenta_bancaria='" . $consulta[1][0] . "' AND i.confirmado='1'");
         if ($consulta[1]['tipo_de_cuenta'] == 0) {
             $consulta[1]['tipo_de_cuenta'] = "Cuenta Corriente";
         } elseif ($consulta[1]['tipo_de_cuenta'] == 1) {
             $consulta[1]['tipo_de_cuenta'] = "Cuenta Vista";
         }
         $consulta[1]['banco'] = utf8_encode($consulta[1]['banco']);
         $consulta[1]['cantidad'] = $cantidad[0];
         $cuentas[] = $consulta[1];
     }
     return $cuentas;
 }
 function definition()
 {
     global $USER, $CFG;
     $mform = $this->_form;
     $mform->setDisableShortforms(true);
     $mform->addElement('header', 'changepassword', get_string('changepassword'), '');
     // visible elements
     $mform->addElement('static', 'username', get_string('username'), $USER->username);
     $policies = array();
     if (!empty($CFG->passwordpolicy)) {
         $policies[] = print_password_policy();
     }
     if (!empty($CFG->passwordreuselimit) and $CFG->passwordreuselimit > 0) {
         $policies[] = get_string('informminpasswordreuselimit', 'auth', $CFG->passwordreuselimit);
     }
     if ($policies) {
         $mform->addElement('static', 'passwordpolicyinfo', '', implode('<br />', $policies));
     }
     $mform->addElement('password', 'password', get_string('oldpassword'));
     $mform->addRule('password', get_string('required'), 'required', null, 'client');
     $mform->setType('password', PARAM_RAW);
     $mform->addElement('password', 'newpassword1', get_string('newpassword'));
     $mform->addRule('newpassword1', get_string('required'), 'required', null, 'client');
     $mform->setType('newpassword1', PARAM_RAW);
     $mform->addElement('password', 'newpassword2', get_string('newpassword') . ' (' . get_String('again') . ')');
     $mform->addRule('newpassword2', get_string('required'), 'required', null, 'client');
     $mform->setType('newpassword2', PARAM_RAW);
     if (empty($CFG->passwordchangetokendeletion) and !empty(webservice::get_active_tokens($USER->id))) {
         $mform->addElement('advcheckbox', 'signoutofotherservices', get_string('signoutofotherservices'));
         $mform->addHelpButton('signoutofotherservices', 'signoutofotherservices');
         $mform->setDefault('signoutofotherservices', 1);
     }
     // hidden optional params
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     // buttons
     if (get_user_preferences('auth_forcepasswordchange')) {
         $this->add_action_buttons(false);
     } else {
         $this->add_action_buttons(true);
     }
 }
Exemple #4
0
 /**
  * this method checks for each cache entry of
  * a webservice if it has to be deleted
  *
  * @param webservice $ws
  */
 private function cleanWSCacheEntries($ws)
 {
     $log = SGAGardeningIssuesAccess::getGardeningIssuesAccess();
     if ($ws->getSpanOfLife() != "0") {
         $cacheResults = WSStorage::getDatabase()->getResultsFromCache($ws->getArticleID());
         $this->addSubTask(sizeof($cacheResults) + 1);
         //echo($ws->getArticleID());
         $deletedCacheEntries = 0;
         foreach ($cacheResults as $cacheResult) {
             if ($ws->doesExpireAfterUpdate() == "false") {
                 if ($cacheResult["lastAccess"]) {
                     if (wfTimestamp(TS_UNIX, $cacheResult["lastAccess"]) < wfTimestamp(TS_UNIX, $cacheResult["lastUpdate"])) {
                         $compareTS = $cacheResult["lastUpdate"];
                     } else {
                         $compareTS = $cacheResult["lastAccess"];
                     }
                 } else {
                     $compareTS = $cacheResult["lastUpdate"];
                 }
             } else {
                 $compareTS = $cacheResult["lastUpdate"];
             }
             //todo: change to days again
             if (wfTime() - wfTimestamp(TS_UNIX, $compareTS) > $ws->getSpanOfLife() * 24 * 60 * 60) {
                 WSStorage::getDatabase()->removeWSEntryFromCache($ws->getArticleID(), $cacheResult["paramSetId"]);
                 $deletedCacheEntries += 1;
             }
             $this->worked(1);
         }
         // echo($ws->getName()."-".$deletedCacheEntries);
         if ($deletedCacheEntries > 0) {
             $log->addGardeningIssueAboutValue($this->id, SMW_GARDISSUE__REMOVED_WSCACHE_ENTRIES, Title::newFromText($ws->getName()), $deletedCacheEntries);
         }
     } else {
         $this->addSubTask(1);
         $this->worked(1);
     }
 }
Exemple #5
0
$PAGE->set_url('/user/wsdoc.php');
$PAGE->set_title(get_string('documentation', 'webservice'));
$PAGE->set_heading(get_string('documentation', 'webservice'));
$PAGE->set_pagelayout('standard');
//nav bar
$PAGE->navbar->ignore_active(true);
$PAGE->navbar->add(get_string('usercurrentsettings'));
$PAGE->navbar->add(get_string('securitykeys', 'webservice'), new moodle_url('/user/managetoken.php', array('id' => $tokenid, 'sesskey' => sesskey())));
$PAGE->navbar->add(get_string('documentation', 'webservice'));
//check web service are enabled
if (empty($CFG->enablewsdocumentation)) {
    echo get_string('wsdocumentationdisable', 'webservice');
    die;
}
//check that the current user is the token user
$webservice = new webservice();
$token = $webservice->get_token_by_id($tokenid);
if (empty($token) or empty($token->userid) or empty($USER->id) or $token->userid != $USER->id) {
    throw new moodle_exception('docaccessrefused', 'webservice');
}
// get the list of all functions related to the token
$functions = $webservice->get_external_functions(array($token->externalserviceid));
// get all the function descriptions
$functiondescs = array();
foreach ($functions as $function) {
    $functiondescs[$function->name] = external_function_info($function);
}
//get activated protocol
$activatedprotocol = array();
$activatedprotocol['rest'] = webservice_protocol_is_enabled('rest');
$activatedprotocol['xmlrpc'] = webservice_protocol_is_enabled('xmlrpc');
require_once $CFG->dirroot . '/webservice/lib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/webservice/forms.php';
$serviceid = required_param('serviceid', PARAM_INT);
$userid = required_param('userid', PARAM_INT);
admin_externalpage_setup('externalserviceusersettings');
//define nav bar
$PAGE->set_url('/' . $CFG->admin . '/webservice/service_user_settings.php', array('id' => $serviceid, 'userid' => $userid));
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
    $node->make_active();
}
$PAGE->navbar->add(get_string('serviceusers', 'webservice'), new moodle_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $serviceid)));
$PAGE->navbar->add(get_string('serviceusersettings', 'webservice'));
$formaction = new moodle_url('', array('id' => $serviceid, 'userid' => $userid));
$returnurl = new moodle_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $serviceid));
$webservicemanager = new webservice();
$serviceuser = $webservicemanager->get_ws_authorised_user($serviceid, $userid);
$usersettingsform = new external_service_authorised_user_settings_form($formaction, $serviceuser);
$settingsformdata = $usersettingsform->get_data();
if ($usersettingsform->is_cancelled()) {
    redirect($returnurl);
} else {
    if (!empty($settingsformdata) and confirm_sesskey()) {
        /// save user settings (administrator clicked on update button)
        $settingsformdata = (object) $settingsformdata;
        $serviceuserinfo = new stdClass();
        $serviceuserinfo->id = $serviceuser->serviceuserid;
        $serviceuserinfo->iprestriction = $settingsformdata->iprestriction;
        $serviceuserinfo->validuntil = $settingsformdata->validuntil;
        $webservicemanager->update_ws_authorised_user($serviceuserinfo);
        //TODO: assign capability
require_once $CFG->libdir . '/externallib.php';
$action = optional_param('action', '', PARAM_ACTION);
$tokenid = optional_param('tokenid', '', PARAM_SAFEDIR);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
admin_externalpage_setup('addwebservicetoken');
//Deactivate the second 'Manage token' navigation node, and use the main 'Manage token' navigation node
$node = $PAGE->settingsnav->find('addwebservicetoken', navigation_node::TYPE_SETTING);
$newnode = $PAGE->settingsnav->find('webservicetokens', navigation_node::TYPE_SETTING);
if ($node && $newnode) {
    $node->display = false;
    $newnode->make_active();
}
require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM));
$tokenlisturl = new moodle_url("/" . $CFG->admin . "/settings.php", array('section' => 'webservicetokens'));
require_once $CFG->dirroot . "/webservice/lib.php";
$webservicemanager = new webservice();
switch ($action) {
    case 'create':
        $mform = new web_service_token_form(null, array('action' => 'create'));
        $data = $mform->get_data();
        if ($mform->is_cancelled()) {
            redirect($tokenlisturl);
        } else {
            if ($data and confirm_sesskey()) {
                ignore_user_abort(true);
                //check the the user is allowed for the service
                $selectedservice = $webservicemanager->get_external_service_by_id($data->service);
                if ($selectedservice->restrictedusers) {
                    $restricteduser = $webservicemanager->get_ws_authorised_user($data->service, $data->user);
                    if (empty($restricteduser)) {
                        $allowuserurl = new moodle_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $selectedservice->id));
Exemple #8
0
    /**
     * Load the virtual class needed for the web service.
     *
     * Initialises the virtual class that contains the web service functions that the user is allowed to use.
     * The web service function will be available if the user:
     * - is validly registered in the external_services_users table.
     * - has the required capability.
     * - meets the IP restriction requirement.
     * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
     * NOTE: The implementation of this method has been mostly copied from webservice_zend_server::init_server_class().
     */
    protected function init_service_class()
    {
        global $USER, $DB;
        // Initialise service methods and struct classes.
        $this->servicemethods = array();
        $this->servicestructs = array();
        $params = array();
        $wscond1 = '';
        $wscond2 = '';
        if ($this->restricted_serviceid) {
            $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
            $wscond1 = 'AND s.id = :sid1';
            $wscond2 = 'AND s.id = :sid2';
        }
        $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)\n                 WHERE s.enabled = 1 {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n                 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) {$wscond2}";
        $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
        $serviceids = array();
        $remoteaddr = getremoteaddr();
        // Query list of external services for the user.
        $rs = $DB->get_recordset_sql($sql, $params);
        // Check which service ID to include.
        foreach ($rs as $service) {
            if (isset($serviceids[$service->id])) {
                continue;
                // Service already added.
            }
            if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
                continue;
                // Cap required, sorry.
            }
            if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
                continue;
                // Wrong request source ip, sorry.
            }
            $serviceids[$service->id] = $service->id;
        }
        $rs->close();
        // Generate the virtual class name.
        $classname = 'webservices_virtual_class_000000';
        while (class_exists($classname)) {
            $classname++;
        }
        $this->serviceclass = $classname;
        // Get the list of all available external functions.
        $wsmanager = new webservice();
        $functions = $wsmanager->get_external_functions($serviceids);
        // Generate code for the virtual methods for this web service.
        $methods = '';
        foreach ($functions as $function) {
            $methods .= $this->get_virtual_method_code($function);
        }
        $code = <<<EOD
/**
 * Virtual class web services for user id {$USER->id} in context {$this->restricted_context->id}.
 */
class {$classname} {
{$methods}
}
EOD;
        // Load the virtual class definition into memory.
        eval($code);
    }
Exemple #9
0
 function definition()
 {
     global $CFG;
     $mform = $this->_form;
     $data = $this->_customdata;
     $mform->addElement('header', 'addfunction', get_string('addfunctions', 'webservice'));
     require_once $CFG->dirroot . "/webservice/lib.php";
     $webservicemanager = new webservice();
     $functions = $webservicemanager->get_not_associated_external_functions($data['id']);
     //we add the descriptions to the functions
     foreach ($functions as $functionid => $functionname) {
         //retrieve full function information (including the description)
         $function = external_function_info($functionname);
         $functions[$functionid] = $function->name . ':' . $function->description;
     }
     $mform->addElement('searchableselector', 'fids', get_string('name'), $functions, array('multiple'));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'action');
     $mform->setType('action', PARAM_ACTION);
     $this->add_action_buttons(true, get_string('addfunctions', 'webservice'));
     $this->set_data($data);
 }
Exemple #10
0
    /**
     * Load virtual class needed for Zend api
     * @return void
     */
    protected function init_service_class()
    {
        global $USER, $DB;
        // first ofall get a complete list of services user is allowed to access
        if ($this->restricted_serviceid) {
            $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
            $wscond1 = 'AND s.id = :sid1';
            $wscond2 = 'AND s.id = :sid2';
        } else {
            $params = array();
            $wscond1 = '';
            $wscond2 = '';
        }
        // now make sure the function is listed in at least one service user is allowed to use
        // allow access only if:
        //  1/ entry in the external_services_users table if required
        //  2/ validuntil not reached
        //  3/ has capability if specified in service desc
        //  4/ iprestriction
        $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)\n                 WHERE s.enabled = 1 {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)\n                 WHERE s.enabled = 1 AND su.validuntil IS NULL OR su.validuntil < :now {$wscond2}";
        $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
        $serviceids = array();
        $rs = $DB->get_recordset_sql($sql, $params);
        // now make sure user may access at least one service
        $remoteaddr = getremoteaddr();
        $allowed = false;
        foreach ($rs as $service) {
            if (isset($serviceids[$service->id])) {
                continue;
            }
            if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
                continue;
                // cap required, sorry
            }
            if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
                continue;
                // wrong request source ip, sorry
            }
            $serviceids[$service->id] = $service->id;
        }
        $rs->close();
        // now get the list of all functions
        $wsmanager = new webservice();
        $functions = $wsmanager->get_external_functions($serviceids);
        // now make the virtual WS class with all the fuctions for this particular user
        $methods = '';
        foreach ($functions as $function) {
            $methods .= $this->get_virtual_method_code($function);
        }
        // let's use unique class name, there might be problem in unit tests
        $classname = 'webservices_virtual_class_000000';
        while (class_exists($classname)) {
            $classname++;
        }
        $code = '
/**
 * Virtual class web services for user id ' . $USER->id . ' in context ' . $this->restricted_context->id . '.
 */
class ' . $classname . ' {
' . $methods . '
}
';
        // load the virtual class definition into memory
        eval($code);
        $this->service_class = $classname;
    }
Exemple #11
0
 /**
  * Define the form.
  */
 public function definition()
 {
     global $USER, $CFG, $COURSE;
     $mform = $this->_form;
     $editoroptions = null;
     $filemanageroptions = null;
     if (!is_array($this->_customdata)) {
         throw new coding_exception('invalid custom data for user_edit_form');
     }
     $editoroptions = $this->_customdata['editoroptions'];
     $filemanageroptions = $this->_customdata['filemanageroptions'];
     $user = $this->_customdata['user'];
     $userid = $user->id;
     // Accessibility: "Required" is bad legend text.
     $strgeneral = get_string('general');
     $strrequired = get_string('required');
     // Add some extra hidden fields.
     $mform->addElement('hidden', 'id');
     $mform->setType('id', core_user::get_property_type('id'));
     $mform->addElement('hidden', 'course', $COURSE->id);
     $mform->setType('course', PARAM_INT);
     // Print the required moodle fields first.
     $mform->addElement('header', 'moodle', $strgeneral);
     $auths = core_component::get_plugin_list('auth');
     $enabled = get_string('pluginenabled', 'core_plugin');
     $disabled = get_string('plugindisabled', 'core_plugin');
     $authoptions = array($enabled => array(), $disabled => array());
     $cannotchangepass = array();
     $cannotchangeusername = array();
     foreach ($auths as $auth => $unused) {
         $authinst = get_auth_plugin($auth);
         if (!$authinst->is_internal()) {
             $cannotchangeusername[] = $auth;
         }
         $passwordurl = $authinst->change_password_url();
         if (!($authinst->can_change_password() && empty($passwordurl))) {
             if ($userid < 1 and $authinst->is_internal()) {
                 // This is unlikely but we can not create account without password
                 // when plugin uses passwords, we need to set it initially at least.
             } else {
                 $cannotchangepass[] = $auth;
             }
         }
         if (is_enabled_auth($auth)) {
             $authoptions[$enabled][$auth] = get_string('pluginname', "auth_{$auth}");
         } else {
             $authoptions[$disabled][$auth] = get_string('pluginname', "auth_{$auth}");
         }
     }
     $mform->addElement('text', 'username', get_string('username'), 'size="20"');
     $mform->addHelpButton('username', 'username', 'auth');
     $mform->setType('username', PARAM_RAW);
     if ($userid !== -1) {
         $mform->disabledIf('username', 'auth', 'in', $cannotchangeusername);
     }
     $mform->addElement('selectgroups', 'auth', get_string('chooseauthmethod', 'auth'), $authoptions);
     $mform->addHelpButton('auth', 'chooseauthmethod', 'auth');
     $mform->addElement('advcheckbox', 'suspended', get_string('suspended', 'auth'));
     $mform->addHelpButton('suspended', 'suspended', 'auth');
     $mform->addElement('checkbox', 'createpassword', get_string('createpassword', 'auth'));
     $mform->disabledIf('createpassword', 'auth', 'in', $cannotchangepass);
     if (!empty($CFG->passwordpolicy)) {
         $mform->addElement('static', 'passwordpolicyinfo', '', print_password_policy());
     }
     $mform->addElement('passwordunmask', 'newpassword', get_string('newpassword'), 'size="20"');
     $mform->addHelpButton('newpassword', 'newpassword');
     $mform->setType('newpassword', core_user::get_property_type('password'));
     $mform->disabledIf('newpassword', 'createpassword', 'checked');
     $mform->disabledIf('newpassword', 'auth', 'in', $cannotchangepass);
     // Check if the user has active external tokens.
     if ($userid and empty($CFG->passwordchangetokendeletion)) {
         if ($tokens = webservice::get_active_tokens($userid)) {
             $services = '';
             foreach ($tokens as $token) {
                 $services .= format_string($token->servicename) . ',';
             }
             $services = get_string('userservices', 'webservice', rtrim($services, ','));
             $mform->addElement('advcheckbox', 'signoutofotherservices', get_string('signoutofotherservices'), $services);
             $mform->addHelpButton('signoutofotherservices', 'signoutofotherservices');
             $mform->disabledIf('signoutofotherservices', 'newpassword', 'eq', '');
             $mform->setDefault('signoutofotherservices', 1);
         }
     }
     $mform->addElement('advcheckbox', 'preference_auth_forcepasswordchange', get_string('forcepasswordchange'));
     $mform->addHelpButton('preference_auth_forcepasswordchange', 'forcepasswordchange');
     $mform->disabledIf('preference_auth_forcepasswordchange', 'createpassword', 'checked');
     // Shared fields.
     useredit_shared_definition($mform, $editoroptions, $filemanageroptions, $user);
     // Next the customisable profile fields.
     profile_definition($mform, $userid);
     if ($userid == -1) {
         $btnstring = get_string('createuser');
     } else {
         $btnstring = get_string('updatemyprofile');
     }
     $this->add_action_buttons(false, $btnstring);
     $this->set_data($user);
 }
Exemple #12
0
require_login();
require_sesskey();
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$PAGE->set_context($usercontext);
$PAGE->set_url('/user/managetoken.php');
$PAGE->set_title(get_string('securitykeys', 'webservice'));
$PAGE->set_heading(get_string('securitykeys', 'webservice'));
$PAGE->set_pagelayout('standard');
$rsstokenboxhtml = $webservicetokenboxhtml = '';
/// Manage user web service tokens
if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $usercontext)) {
    require $CFG->dirroot . '/webservice/lib.php';
    $action = optional_param('action', '', PARAM_ACTION);
    $tokenid = optional_param('tokenid', '', PARAM_SAFEDIR);
    $confirm = optional_param('confirm', 0, PARAM_BOOL);
    $webservice = new webservice();
    //load the webservice library
    $wsrenderer = $PAGE->get_renderer('core', 'webservice');
    if ($action == 'resetwstoken') {
        $token = $webservice->get_created_by_user_ws_token($USER->id, $tokenid);
        /// Display confirmation page to Reset the token
        if (!$confirm) {
            $resetconfirmation = $wsrenderer->user_reset_token_confirmation($token);
        } else {
            /// Delete the token that need to be regenerated
            $webservice->delete_user_ws_token($tokenid);
        }
    }
    //no point creating the table is we're just displaying a confirmation screen
    if (empty($resetconfirmation)) {
        $webservice->generate_user_ws_tokens($USER->id);
 /**
  * Unregister site
  * @return bool 1 if unregistration was successfull
  */
 public static function unregister_site()
 {
     global $DB, $CFG;
     // Ensure the current user is allowed to run this function
     $context = context_system::instance();
     self::validate_context($context);
     require_capability('local/hub:updateinfo', $context);
     //clean params
     $params = self::validate_parameters(self::unregister_site_parameters(), array());
     //retieve the site communication
     $token = optional_param('wstoken', '', PARAM_ALPHANUM);
     $hub = new local_hub();
     $communication = $hub->get_communication(WSSERVER, REGISTEREDSITE, null, $token);
     //retrieve the site
     $siteurl = $communication->remoteurl;
     $site = $hub->get_site_by_url($siteurl);
     //unregister the site
     if (!empty($site)) {
         $hub->unregister_site($site);
     }
     //delete the web service token
     require_once $CFG->dirroot . '/webservice/lib.php';
     $webservice_manager = new webservice();
     $tokentodelete = $webservice_manager->get_user_ws_token($communication->token);
     $webservice_manager->delete_user_ws_token($tokentodelete->id);
     //delete the site communication
     $hub->delete_communication($communication);
     return true;
 }
Exemple #14
0
<?php

include_once '../../includes/class.init.php';
include_once '../../includes/class.webservice.php';
$init = new init(0, 0, 0);
//echo json_encode($_GET);
//exit();
$data = file_get_contents("php://input");
$objData = json_decode($data);
$data = json_decode(json_encode($_GET), FALSE);
$data = $objData;
//Extra security due to public webservice without login
if ($data->method != "GET") {
    echo json_encode(array("status" => array("code" => "403", "text" => "Alleen GET-acties zijn toegestaan")));
} else {
    $webservice = new webservice($init);
    echo json_encode($webservice->execute($data));
}
require_once $CFG->dirroot . '/webservice/lib.php';
require_once 'forms.php';
$serviceid = required_param('id', PARAM_INT);
$functionid = optional_param('fid', 0, PARAM_INT);
$action = optional_param('action', '', PARAM_ACTION);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
admin_externalpage_setup('externalservicefunctions');
//define nav bar
$PAGE->set_url('/' . $CFG->admin . '/webservice/service_functions.php', array('id' => $serviceid));
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
    $node->make_active();
}
$PAGE->navbar->add(get_string('functions', 'webservice'), new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php', array('id' => $serviceid)));
$service = $DB->get_record('external_services', array('id' => $serviceid), '*', MUST_EXIST);
$webservicemanager = new webservice();
$renderer = $PAGE->get_renderer('core', 'webservice');
$functionlisturl = new moodle_url('/' . $CFG->admin . '/webservice/service_functions.php', array('id' => $serviceid));
// Add or Delete operations
switch ($action) {
    case 'add':
        $PAGE->navbar->add(get_string('addfunctions', 'webservice'));
        /// Add function operation
        if (confirm_sesskey() and $service and empty($service->component)) {
            $mform = new external_service_functions_form(null, array('action' => 'add', 'id' => $service->id));
            //cancelled add operation, redirect to function list page
            if ($mform->is_cancelled()) {
                redirect($functionlisturl);
            }
            //add the function to the service then redirect to function list page
            if ($data = $mform->get_data()) {
Exemple #16
0
    $roleid = create_role('Web Service', 'testtete', 'MDK: All permissions given by default.', '');
}
$context = context_system::instance();
set_role_contextlevels($roleid, array($context->contextlevel));
role_assign($roleid, $user->id, $context->id);
if (method_exists($context, 'get_capabilities')) {
    $capabilities = $context->get_capabilities();
} else {
    $capabilities = fetch_context_capabilities($context);
}
foreach ($capabilities as $capability) {
    assign_capability($capability->name, CAP_ALLOW, $roleid, $context->id, true);
}
$context->mark_dirty();
// Create a new service with all functions for the user.
$webservicemanager = new webservice();
if (!($service = $DB->get_record('external_services', array('shortname' => 'mdk_all')))) {
    $service = new stdClass();
    $service->name = 'MDK: All functions';
    $service->shortname = 'mdk_all';
    $service->enabled = 1;
    $service->restrictedusers = 1;
    $service->downloadfiles = 1;
    $service->id = $webservicemanager->add_external_service($service);
}
$functions = $webservicemanager->get_not_associated_external_functions($service->id);
foreach ($functions as $function) {
    $webservicemanager->add_external_function_to_service($function->name, $service->id);
}
if (!$webservicemanager->get_ws_authorised_user($service->id, $user->id)) {
    $adduser = new stdClass();
 /**
  * Creates tokens.
  *
  * @Given /^the following tokens exist:$/
  * @param TableNode $data
  */
 public function the_following_tokens_exist(TableNode $data)
 {
     global $DB, $CFG;
     foreach ($data->getHash() as $datahash) {
         $service = $this->get_service_id($datahash['service']);
         $userid = $this->get_user_id($datahash['user']);
         $validuntil = !empty($datahash['validuntil']) ? $datahash['validuntil'] : '';
         $iprestriction = !empty($datahash['iprestriction']) ? $datahash['iprestriction'] : '';
         require_once "{$CFG->dirroot}/webservice/lib.php";
         $webservicemanager = new webservice();
         // Check the the user is allowed for the service.
         $selectedservice = $webservicemanager->get_external_service_by_id($service);
         if ($selectedservice->restrictedusers) {
             $restricteduser = $webservicemanager->get_ws_authorised_user($service, $userid);
             if (empty($restricteduser)) {
                 throw new moodle_exception('usernotallowed', 'webservice');
             }
         }
         // Check if the user is deleted. unconfirmed, suspended or guest.
         $user = $DB->get_record('user', array('id' => $userid));
         if ($user->id == $CFG->siteguest or $user->deleted or !$user->confirmed or $user->suspended) {
             throw new moodle_exception('forbiddenwsuser', 'webservice');
         }
         external_generate_token(EXTERNAL_TOKEN_PERMANENT, $service, $userid, context_system::instance(), $validuntil, $iprestriction);
     }
 }
Exemple #18
0
    if (!$force) {
        $function = 'hubdirectory_unregister_hub';
        $params = array();
        $serverurl = HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/webservices.php";
        require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
        $xmlrpcclient = new webservice_xmlrpc_client($serverurl, $hubtodirectorycommunication->token);
        try {
            $result = $xmlrpcclient->call($function, $params);
        } catch (Exception $e) {
            $error = get_string('errorunregistration', 'local_hub', $e->getMessage());
        }
    }
    if (empty($error)) {
        if (!empty($directorytohubcommunication)) {
            //delete the web service token
            $webservice_manager = new webservice();
            $tokentodelete = $webservice_manager->get_user_ws_token($directorytohubcommunication->token);
            $webservice_manager->delete_user_ws_token($tokentodelete->id);
            //delete the communication
            $hub->delete_communication($directorytohubcommunication);
        }
        if (!empty($hubtodirectorycommunication)) {
            $hub->delete_communication($hubtodirectorycommunication);
        }
    }
    redirect(new moodle_url('/local/hub/admin/register.php', array('sesskey' => sesskey(), 'error' => $error)));
}
/////// UPDATE ACTION ////////
// update the hub registration (in fact it is a new registration)
$update = optional_param('update', 0, PARAM_INT);
if ($update && confirm_sesskey()) {
Exemple #19
0
 /**
  * Fetches the function description from database,
  * verifies user is allowed to use this function and
  * loads all paremeters and return descriptions.
  * @return void
  */
 protected function load_function_info()
 {
     global $USER;
     if (empty($this->functionname)) {
         throw new WebserviceInvalidParameterException(get_string('missingfuncname', 'webserivce'));
     }
     // function must exist
     $function = webservice_function_info($this->functionname);
     if (!$function) {
         throw new WebserviceAccessException(get_string('accessextfunctionnotconf', 'auth.webservice'));
     }
     // first ofall get a complete list of services user is allowed to access
     if ($this->restricted_serviceid) {
         $wscond1 = 'AND s.id = ? ';
         $wscond2 = 'AND s.id = ? ';
     } else {
         $wscond1 = '';
         $wscond2 = '';
     }
     // now let's verify access control
     // now make sure the function is listed in at least one service user is allowed to use
     // allow access only if:
     //  1/ entry in the external_services_users table if required
     //  2/ validuntil not reached
     //  3/ has capability if specified in service desc
     //  4/ iprestriction
     $sql = "SELECT s.*, NULL AS iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND (s.restrictedusers = ? OR s.tokenusers = ?) AND sf.functionname = ?)\n                 WHERE s.enabled = ? {$wscond1}\n\n                 UNION\n\n                SELECT s.*, su.iprestriction\n                  FROM {external_services} s\n                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = ? AND sf.functionname = ?)\n                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = ?)\n                 WHERE s.enabled = ? AND su.validuntil IS NULL OR su.validuntil < ? {$wscond2}";
     $params = array(0, 1, $function->name, 1);
     $wscond1 && ($params[] = $this->restricted_serviceid);
     $params[] = 1;
     $params[] = $function->name;
     $params[] = $USER->get('id');
     $params[] = 1;
     $params[] = time();
     $wscond2 && ($params[] = $this->restricted_serviceid);
     $rs = get_recordset_sql($sql, $params);
     // now make sure user may access at least one service
     $remoteaddr = getremoteaddr();
     $allowed = false;
     $serviceids = array();
     foreach ($rs as $service) {
         $serviceids[] = $service['id'];
         if ($service['iprestriction'] and !address_in_subnet($remoteaddr, $service['iprestriction'])) {
             // wrong request source ip, sorry
             continue;
         }
         $allowed = true;
         // one service is enough, no need to continue
         break;
     }
     $rs->close();
     if (!$allowed) {
         throw new WebserviceAccessException(get_string('accesstofunctionnotallowed', 'auth.webservice', $this->functionname));
     }
     // now get the list of all functions - this triggers the stashing of
     // functions in the context
     $wsmanager = new webservice();
     $functions = $wsmanager->get_external_functions($serviceids);
     // we have all we need now
     $this->function = $function;
 }
Exemple #20
0
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once '../../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/webservice/lib.php';
require_once $CFG->dirroot . '/webservice/lib.php';
$id = required_param('id', PARAM_INT);
admin_externalpage_setup('externalserviceusers');
//define nav bar
$PAGE->set_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $id));
$node = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node) {
    $node->make_active();
}
$PAGE->navbar->add(get_string('serviceusers', 'webservice'), new moodle_url('/' . $CFG->admin . '/webservice/service_users.php', array('id' => $id)));
$webservicemanager = new webservice();
/// Get the user_selector we will need.
$potentialuserselector = new service_user_selector('addselect', array('serviceid' => $id, 'displayallowedusers' => 0));
$alloweduserselector = new service_user_selector('removeselect', array('serviceid' => $id, 'displayallowedusers' => 1));
/// Process incoming user assignments to the service
if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
    $userstoassign = $potentialuserselector->get_selected_users();
    if (!empty($userstoassign)) {
        foreach ($userstoassign as $adduser) {
            $serviceuser = new stdClass();
            $serviceuser->externalserviceid = $id;
            $serviceuser->userid = $adduser->id;
            $webservicemanager->add_ws_authorised_user($serviceuser);
            add_to_log(SITEID, 'core', 'assign', $CFG->admin . '/webservice/service_users.php?id=' . $id, 'add', '', $adduser->id);
        }
        $potentialuserselector->invalidate_selected_users();
Exemple #21
0
     user_update_user($usernew, false, false);
     // Set new password if specified.
     if (!empty($usernew->newpassword)) {
         if ($authplugin->can_change_password()) {
             if (!$authplugin->user_update_password($usernew, $usernew->newpassword)) {
                 print_error('cannotupdatepasswordonextauth', '', '', $usernew->auth);
             }
             unset_user_preference('create_password', $usernew);
             // Prevent cron from generating the password.
             if (!empty($CFG->passwordchangelogout)) {
                 // We can use SID of other user safely here because they are unique,
                 // the problem here is we do not want to logout admin here when changing own password.
                 \core\session\manager::kill_user_sessions($usernew->id, session_id());
             }
             if (!empty($usernew->signoutofotherservices)) {
                 webservice::delete_user_ws_tokens($usernew->id);
             }
         }
     }
     // Force logout if user just suspended.
     if (isset($usernew->suspended) and $usernew->suspended and !$user->suspended) {
         \core\session\manager::kill_user_sessions($user->id);
     }
 }
 $usercontext = context_user::instance($usernew->id);
 // Update preferences.
 useredit_update_user_preference($usernew);
 // Update tags.
 if (empty($USER->newadminuser) && isset($usernew->interests)) {
     useredit_update_interests($usernew, $usernew->interests);
 }
Exemple #22
0
 * @author Bobby Allen (ballen@bobbyallen.me)
 * @copyright ZPanel Project (http://www.zpanelcp.com/)
 * @link http://www.zpanelcp.com/
 * @license GPL (http://www.gnu.org/licenses/gpl.html)
 */
$rawPath = str_replace("\\", "/", dirname(__FILE__));
$rootPath = str_replace("/bin", "/", $rawPath);
chdir($rootPath);
require_once 'dryden/loader.inc.php';
require_once 'cnf/db.php';
require_once 'inc/dbc.inc.php';
debug_phperrors::SetMode('dev');
if (file_exists('modules/' . fs_protector::SanitiseFolderName($_GET['m']) . '/code/webservice.ext.php')) {
    include 'modules/' . fs_protector::SanitiseFolderName($_GET['m']) . '/code/controller.ext.php';
    include 'modules/' . fs_protector::SanitiseFolderName($_GET['m']) . '/code/webservice.ext.php';
    $api = new webservice();
    if ($api->wsdataarray['request'] == '') {
        $response_nomethod = new runtime_dataobject();
        $response_nomethod->addItemValue('response', '1106');
        $response_nomethod->addItemValue('content', 'No \'request\' method was recieved');
        $api->SendResponse($response_nomethod->getDataObject());
        die;
    }
    if ($api->CheckServerAPIKey()) {
        if (method_exists($api, $api->wsdataarray['request'])) {
            $api->SendResponse(call_user_func(array($api, '' . $api->wsdataarray['request'] . '')));
        } else {
            $response_nomethod = new runtime_dataobject();
            $response_nomethod = new runtime_dataobject();
            $response_nomethod->addItemValue('response', '1102');
            $response_nomethod->addItemValue('content', 'Request not found');
Exemple #23
0
require_login();
require_sesskey();
$usercontext = context_user::instance($USER->id);
$PAGE->set_context($usercontext);
$PAGE->set_url('/user/managetoken.php');
$PAGE->set_title(get_string('securitykeys', 'webservice'));
$PAGE->set_heading(get_string('securitykeys', 'webservice'));
$PAGE->set_pagelayout('admin');
$rsstokenboxhtml = $webservicetokenboxhtml = '';
// Manage user web service tokens.
if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', $usercontext)) {
    require $CFG->dirroot . '/webservice/lib.php';
    $action = optional_param('action', '', PARAM_ALPHANUMEXT);
    $tokenid = optional_param('tokenid', '', PARAM_SAFEDIR);
    $confirm = optional_param('confirm', 0, PARAM_BOOL);
    $webservice = new webservice();
    // Load the webservice library.
    $wsrenderer = $PAGE->get_renderer('core', 'webservice');
    if ($action == 'resetwstoken') {
        $token = $webservice->get_created_by_user_ws_token($USER->id, $tokenid);
        // Display confirmation page to Reset the token.
        if (!$confirm) {
            $resetconfirmation = $wsrenderer->user_reset_token_confirmation($token);
        } else {
            // Delete the token that need to be regenerated.
            $webservice->delete_user_ws_token($tokenid);
        }
    }
    // No point creating the table is we're just displaying a confirmation screen.
    if (empty($resetconfirmation)) {
        $webservice->generate_user_ws_tokens($USER->id);
Exemple #24
0
/**
 * Update password hash in user object (if necessary).
 *
 * The password is updated if:
 * 1. The password has changed (the hash of $user->password is different
 *    to the hash of $password).
 * 2. The existing hash is using an out-of-date algorithm (or the legacy
 *    md5 algorithm).
 *
 * Updating the password will modify the $user object and the database
 * record to use the current hashing algorithm.
 * It will remove Web Services user tokens too.
 *
 * @param stdClass $user User object (password property may be updated).
 * @param string $password Plain text password.
 * @param bool $fasthash If true, use a low cost factor when generating the hash
 *                       This is much faster to generate but makes the hash
 *                       less secure. It is used when lots of hashes need to
 *                       be generated quickly.
 * @return bool Always returns true.
 */
function update_internal_user_password($user, $password, $fasthash = false)
{
    global $CFG, $DB;
    // Figure out what the hashed password should be.
    if (!isset($user->auth)) {
        debugging('User record in update_internal_user_password() must include field auth', DEBUG_DEVELOPER);
        $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
    }
    $authplugin = get_auth_plugin($user->auth);
    if ($authplugin->prevent_local_passwords()) {
        $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
    } else {
        $hashedpassword = hash_internal_user_password($password, $fasthash);
    }
    $algorithmchanged = false;
    if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
        // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
        $passwordchanged = $user->password !== $hashedpassword;
    } else {
        if (isset($user->password)) {
            // If verification fails then it means the password has changed.
            $passwordchanged = !password_verify($password, $user->password);
            $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
        } else {
            // While creating new user, password in unset in $user object, to avoid
            // saving it with user_create()
            $passwordchanged = true;
        }
    }
    if ($passwordchanged || $algorithmchanged) {
        $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
        $user->password = $hashedpassword;
        // Trigger event.
        $user = $DB->get_record('user', array('id' => $user->id));
        \core\event\user_password_updated::create_from_user($user)->trigger();
        // Remove WS user tokens.
        if (!empty($CFG->passwordchangetokendeletion)) {
            require_once $CFG->dirroot . '/webservice/lib.php';
            webservice::delete_user_ws_tokens($user->id);
        }
    }
    return true;
}
Exemple #25
0
require_once 'forms.php';
require_once $CFG->dirroot . '/webservice/lib.php';
admin_externalpage_setup('externalservice');
//define nav bar
$node = $PAGE->settingsnav->find('externalservice', navigation_node::TYPE_SETTING);
$newnode = $PAGE->settingsnav->find('externalservices', navigation_node::TYPE_SETTING);
if ($node && $newnode) {
    $node->display = false;
    $newnode->make_active();
}
$PAGE->navbar->add(get_string('externalservice', 'webservice'));
//Retrieve few general parameters
$id = required_param('id', PARAM_INT);
$action = optional_param('action', '', PARAM_ALPHANUMEXT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$webservicemanager = new webservice();
$renderer = $PAGE->get_renderer('core', 'webservice');
$returnurl = $CFG->wwwroot . "/" . $CFG->admin . "/settings.php?section=externalservices";
$service = $id ? $webservicemanager->get_external_service_by_id($id, MUST_EXIST) : null;
/// DELETE operation
if ($action == 'delete' and confirm_sesskey() and $service and empty($service->component)) {
    //Display confirmation Page
    if (!$confirm) {
        echo $OUTPUT->header();
        echo $renderer->admin_remove_service_confirmation($service);
        echo $OUTPUT->footer();
        die;
    }
    //The user has confirmed the deletion, delete and redirect
    $webservicemanager->delete_service($service->id);
    add_to_log(SITEID, 'webservice', 'delete', $returnurl, get_string('deleteservice', 'webservice', $service));
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * A script to serve files from web service client
 *
 * @package    core_webservice
 * @copyright  2011 Dongsheng Cai <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
/**
 * AJAX_SCRIPT - exception will be converted into JSON
 */
define('AJAX_SCRIPT', true);
/**
 * NO_MOODLE_COOKIES - we don't want any cookie
 */
define('NO_MOODLE_COOKIES', true);
require_once dirname(dirname(__FILE__)) . '/config.php';
require_once $CFG->libdir . '/filelib.php';
require_once $CFG->dirroot . '/webservice/lib.php';
//authenticate the user
$token = required_param('token', PARAM_ALPHANUM);
$webservicelib = new webservice();
$authenticationinfo = $webservicelib->authenticate_user($token);
//check the service allows file download
$enabledfiledownload = (int) $authenticationinfo['service']->downloadfiles;
if (empty($enabledfiledownload)) {
    throw new webservice_access_exception('Web service file downloading must be enabled in external service settings');
}
//finally we can serve the file :)
$relativepath = get_file_argument();
file_pluginfile($relativepath, 0);
Exemple #27
0
 function delete_site($id, $unregistercourses = false)
 {
     global $CFG;
     require_once $CFG->dirroot . '/local/hub/locallib.php';
     $sitetodelete = $this->get_site($id);
     //unregister the courses first
     if (!empty($unregistercourses)) {
         $this->delete_courses($sitetodelete->id);
     }
     $sitetohubcommunication = $this->get_communication(WSSERVER, REGISTEREDSITE, $sitetodelete->url);
     if (!empty($sitetohubcommunication)) {
         //delete the token for this site
         require_once $CFG->dirroot . '/webservice/lib.php';
         $webservice_manager = new webservice();
         $tokentodelete = $webservice_manager->get_user_ws_token($sitetohubcommunication->token);
         $webservice_manager->delete_user_ws_token($tokentodelete->id);
         //delete the communications to this hub
         $this->delete_communication($sitetohubcommunication);
     }
     // Send email to the site administrator.
     $contactuser = local_hub_create_contact_user($sitetodelete->contactemail ? $sitetodelete->contactemail : $CFG->noreplyaddress, $sitetodelete->contactname ? $sitetodelete->contactname : get_string('noreplyname'));
     $emailinfo = new stdClass();
     $hubinfo = $this->get_info();
     $emailinfo->hubname = $hubinfo['name'];
     $emailinfo->huburl = $hubinfo['url'];
     $emailinfo->sitename = $sitetodelete->name;
     $emailinfo->siteurl = $sitetodelete->url;
     $emailinfo->unregisterpagelink = $sitetodelete->url . '/admin/registration/index.php?huburl=' . $hubinfo['url'] . '&force=1&unregistration=1';
     email_to_user($contactuser, get_admin(), get_string('emailtitlesitedeleted', 'local_hub', $emailinfo), get_string('emailmessagesitedeleted', 'local_hub', $emailinfo));
     $this->unregister_site($sitetodelete);
 }
Exemple #28
0
 /**
  * Builds the XHTML to display the control
  *
  * @param string $data Unused
  * @param string $query
  * @return string
  */
 public function output_html($data, $query = '')
 {
     global $CFG, $OUTPUT, $DB, $USER;
     // display strings
     $stroperation = get_string('operation', 'webservice');
     $strtoken = get_string('token', 'webservice');
     $strservice = get_string('service', 'webservice');
     $struser = get_string('user');
     $strcontext = get_string('context', 'webservice');
     $strvaliduntil = get_string('validuntil', 'webservice');
     $striprestriction = get_string('iprestriction', 'webservice');
     $return = $OUTPUT->box_start('generalbox webservicestokenui');
     $table = new html_table();
     $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
     $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
     $table->width = '100%';
     $table->data = array();
     $tokenpageurl = "{$CFG->wwwroot}/{$CFG->admin}/webservice/tokens.php?sesskey=" . sesskey();
     //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
     //here retrieve token list (including linked users firstname/lastname and linked services name)
     $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid\n                  FROM {external_tokens} t, {user} u, {external_services} s\n                 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
     $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
     if (!empty($tokens)) {
         foreach ($tokens as $token) {
             //TODO: retrieve context
             $delete = "<a href=\"" . $tokenpageurl . "&amp;action=delete&amp;tokenid=" . $token->id . "\">";
             $delete .= get_string('delete') . "</a>";
             $validuntil = '';
             if (!empty($token->validuntil)) {
                 $validuntil = date("F j, Y");
                 //TODO: language support (look for moodle function)
             }
             $iprestriction = '';
             if (!empty($token->iprestriction)) {
                 $iprestriction = $token->iprestriction;
             }
             $userprofilurl = new moodle_url('/user/profile.php?id=' . $token->userid);
             $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
             $useratag .= $token->firstname . " " . $token->lastname;
             $useratag .= html_writer::end_tag('a');
             //check user missing capabilities
             require_once $CFG->dirroot . '/webservice/lib.php';
             $webservicemanager = new webservice();
             $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(array(array('id' => $token->userid)), $token->serviceid);
             if (!is_siteadmin($token->userid) and key_exists($token->userid, $usermissingcaps)) {
                 $missingcapabilities = implode(', ', $usermissingcaps[$token->userid]);
                 if (!empty($missingcapabilities)) {
                     $useratag .= html_writer::tag('div', get_string('usermissingcaps', 'webservice', $missingcapabilities) . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'), array('class' => 'missingcaps'));
                 }
             }
             $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
         }
         $return .= html_writer::table($table);
     } else {
         $return .= get_string('notoken', 'webservice');
     }
     $return .= $OUTPUT->box_end();
     // add a token to the table
     $return .= "<a href=\"" . $tokenpageurl . "&amp;action=create\">";
     $return .= get_string('add') . "</a>";
     return highlight($query, $return);
 }
Exemple #29
0
$mform->set_data(array('id' => $course->id));
$navlinks = array();
$navlinks[] = array('name' => $strparticipants, 'link' => "{$CFG->wwwroot}/user/index.php?id={$course->id}", 'type' => 'misc');
if ($mform->is_cancelled()) {
    redirect($CFG->wwwroot . '/user/preferences.php?userid=' . $USER->id . '&amp;course=' . $course->id);
} else {
    if ($data = $mform->get_data()) {
        if (!$userauth->user_update_password($USER, $data->newpassword1)) {
            print_error('errorpasswordupdate', 'auth');
        }
        user_add_password_history($USER->id, $data->newpassword1);
        if (!empty($CFG->passwordchangelogout)) {
            \core\session\manager::kill_user_sessions($USER->id, session_id());
        }
        if (!empty($data->signoutofotherservices)) {
            webservice::delete_user_ws_tokens($USER->id);
        }
        // Reset login lockout - we want to prevent any accidental confusion here.
        login_unlock_account($USER);
        // register success changing password
        unset_user_preference('auth_forcepasswordchange', $USER);
        unset_user_preference('create_password', $USER);
        $strpasswordchanged = get_string('passwordchanged');
        $fullname = fullname($USER, true);
        $PAGE->set_title($strpasswordchanged);
        $PAGE->set_heading(fullname($USER));
        echo $OUTPUT->header();
        notice($strpasswordchanged, new moodle_url($PAGE->url, array('return' => 1)));
        echo $OUTPUT->footer();
        exit;
    }