/** * Provides a basic text field input. * * @todo this is just lies ... * @param array $element The element to render * @param Pieform $form The form to render the element for * @return string The HTML for the element */ function pieform_element_userlist(Pieform $form, $element) { $smarty = smarty_core(); $smarty->left_delimiter = '{{'; $smarty->right_delimiter = '}}'; $value = $form->get_value($element); if (!is_array($value) && isset($element['defaultvalue']) && is_array($element['defaultvalue'])) { $value = $element['defaultvalue']; } if (is_array($value) && count($value)) { $orderby = isset($element['searchparams']['orderby']) && $element['searchparams']['orderby'] == 'lastname' ? 'lastname,firstname,id' : 'firstname,lastname,id'; $members = get_records_select_assoc('usr', 'id IN (' . join(',', array_map('intval', $value)) . ')', null, $orderby, 'id,username,firstname,lastname,preferredname,staff'); foreach ($members as &$member) { $member = display_name($member); } $smarty->assign('options', $members); $smarty->assign('value', join(',', $value)); } $smarty->assign('name', $element['name']); if (!empty($element['lefttitle'])) { $smarty->assign('lefttitle', $element['lefttitle']); } if (!empty($element['righttitle'])) { $smarty->assign('righttitle', $element['righttitle']); } if (!empty($element['leftarrowlabel'])) { $smarty->assign('leftarrowlabel', $element['leftarrowlabel']); } if (!empty($element['rightarrowlabel'])) { $smarty->assign('rightarrowlabel', $element['rightarrowlabel']); } if (!empty($element['group'])) { $smarty->assign('group', $element['group']); $smarty->assign('includeadmins', !isset($element['includeadmins']) || $element['includeadmins'] ? 1 : 0); } if (empty($element['searchscript'])) { $element['searchscript'] = 'json/usersearch.php'; } $smarty->assign('searchscript', $element['searchscript']); if (empty($element['searchparams'])) { $element['searchparams'] = array('query' => '', 'limit' => 100); } $smarty->assign('searchparams', json_encode($element['searchparams'])); $smarty->assign('onlyshowingfirst', json_encode(get_string('onlyshowingfirst', 'admin'))); $smarty->assign('resultsof', json_encode(get_string('resultsof', 'admin'))); return $smarty->fetch('form/userlist.tpl'); }
public function removeMember($user) { if (is_numeric($user)) { $user = get_record('usr', 'id', $user); } db_begin(); // If the user is being authed by the institution they are // being removed from, change them to internal auth, or if // we can't find that, some other no institution auth. $authinstances = get_records_select_assoc('auth_instance', "institution IN ('mahara', ?)", array($this->name), "institution = 'mahara' DESC, authname = 'internal' DESC"); $oldauth = $user->authinstance; if (isset($authinstances[$oldauth]) && $authinstances[$oldauth]->institution == $this->name) { foreach ($authinstances as $ai) { if ($ai->authname == 'internal' && $ai->institution == 'mahara') { $user->authinstance = $ai->id; break; } else { if ($ai->institution == 'mahara') { $user->authinstance = $ai->id; break; } } } delete_records('auth_remote_user', 'authinstance', $oldauth, 'localusr', $user->id); // If the old authinstance was external, the user may need // to set a password if ($user->password == '') { log_debug('resetting pw for ' . $user->id); $this->removeMemberSetPassword($user); } update_record('usr', $user); } delete_records('usr_institution', 'usr', $user->id, 'institution', $this->name); handle_event('updateuser', $user->id); db_commit(); }
function locked_profile_fields() { global $USER, $SESSION; // Profile fields are locked for a user if they are locked by any // institution the user is a member of, but not an admin for. $lockinginstitutions = array_keys($USER->get('institutions')); $lockinginstitutions[] = 'mahara'; $lockinginstitutions = array_diff($lockinginstitutions, $USER->get('admininstitutions')); $locked = get_records_select_assoc('institution_locked_profile_field', 'name IN (' . join(',', array_map('db_quote', $lockinginstitutions)) . ')', null, '', 'profilefield,name'); if ($remotelocked = $SESSION->get('lockedfields')) { foreach ($remotelocked as $f) { if (!isset($locked[$f])) { $locked[$f] = $f; } } } return $locked; }
function progressbarform_submit(Pieform $form, $values) { global $SESSION, $USER, $possibleitems; $institution = $values['institution']; // Pre-fetching the current settings to reduce SELECT queries $currentsettings = get_records_select_assoc('institution_config', 'institution=? and field like \'progressbaritem_%\'', array($institution), 'field', 'field, value'); if (!$currentsettings) { $currentsettings = array(); } foreach ($possibleitems as $plugin => $pluginitems) { foreach ($pluginitems as $artefact) { $itemname = "progressbaritem_{$plugin}_{$artefact->name}"; // Format the value into an integer or 0/1 $val = $values[$itemname]; if ($artefact->iscountable) { $val = (int) $val; } else { $val = (int) (bool) $val; } // Update the record if it already exists, or create the record if it doesn't if (array_key_exists($itemname, $currentsettings)) { if ($val) { set_field('institution_config', 'value', $val, 'institution', $institution, 'field', $itemname); } else { delete_records('institution_config', 'institution', $institution, 'field', $itemname); } } else { if ($val) { insert_record('institution_config', (object) array('institution' => $institution, 'field' => $itemname, 'value' => $val)); } } } } $SESSION->add_ok_msg(get_string('progressbarsaved', 'admin')); redirect('/admin/users/progressbar.php?institution=' . $institution); }
function changeauth_submit(Pieform $form, $values) { global $users, $SESSION, $authinstances, $USER; $newauth = AuthFactory::create($values['authinstance']); $needspassword = method_exists($newauth, 'change_password'); $updated = 0; $needpassword = 0; db_begin(); $newauthinst = get_records_select_assoc('auth_instance', 'id = ?', array($values['authinstance'])); if ($USER->get('admin') || $USER->is_institutional_admin($newauthinst[$values['authinstance']]->institution)) { foreach ($users as $user) { if ($user->authinstance != $values['authinstance']) { // Authinstance can be changed by institutional admins if both the // old and new authinstances belong to the admin's institutions $authinst = get_field('auth_instance', 'institution', 'id', $user->authinstance); if ($USER->get('admin') || $USER->is_institutional_admin($authinst)) { // determine the current remoteusername $current_remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id); if (!$current_remotename) { $current_remotename = $user->username; } // remove row if new authinstance row already exists to avoid doubleups delete_records('auth_remote_user', 'authinstance', $values['authinstance'], 'localusr', $user->id); insert_record('auth_remote_user', (object) array('authinstance' => $values['authinstance'], 'remoteusername' => $current_remotename, 'localusr' => $user->id)); } if ($user->haspassword && !$needspassword) { $user->password = ''; } else { if ($needspassword && !$user->haspassword) { $needpassword++; } } $user->authinstance = $values['authinstance']; update_record('usr', $user, 'id'); $updated++; } } } db_commit(); if ($needpassword) { // Inform the user that they may need to reset passwords $SESSION->add_info_msg(get_string('bulkchangeauthmethodresetpassword', 'admin', $needpassword)); } $message = get_string('bulkchangeauthmethodsuccess', 'admin', $updated); $form->reply(PIEFORM_OK, array('message' => $message)); }
function edituser_site_submit(Pieform $form, $values) { if (!($user = get_record('usr', 'id', $values['id']))) { return false; } if (isset($values['password']) && $values['password'] !== '') { $user->password = $values['password']; $user->salt = ''; } $user->passwordchange = (int) ($values['passwordchange'] == 'on'); $user->quota = $values['quota']; $user->expiry = db_format_timestamp($values['expiry']); global $USER; if ($USER->get('admin')) { // Not editable by institutional admins $user->staff = (int) ($values['staff'] == 'on'); $user->admin = (int) ($values['admin'] == 'on'); if ($user->admin) { activity_add_admin_defaults(array($user->id)); } } if ($values['maildisabled'] == 0 && get_account_preference($user->id, 'maildisabled') == 1) { // Reset the sent and bounce counts otherwise mail will be disabled // on the next send attempt $u = new StdClass(); $u->email = $user->email; $u->id = $user->id; update_bounce_count($u, true); update_send_count($u, true); } set_account_preference($user->id, 'maildisabled', $values['maildisabled']); // Authinstance can be changed by institutional admins if both the // old and new authinstances belong to the admin's institutions $remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id); if (!$remotename) { $remotename = $user->username; } if (isset($values['authinstance']) && ($values['authinstance'] != $user->authinstance || isset($values['remoteusername']) && $values['remoteusername'] != $remotename)) { $authinst = get_records_select_assoc('auth_instance', 'id = ? OR id = ?', array($values['authinstance'], $user->authinstance)); if ($USER->get('admin') || $USER->is_institutional_admin($authinst[$values['authinstance']]->institution) && $USER->is_institutional_admin($authinst[$user->authinstance]->institution)) { delete_records('auth_remote_user', 'localusr', $user->id); if ($authinst[$values['authinstance']]->authname != 'internal') { if (isset($values['remoteusername']) && strlen($values['remoteusername']) > 0) { $un = $values['remoteusername']; } else { $un = $remotename; } insert_record('auth_remote_user', (object) array('authinstance' => $values['authinstance'], 'remoteusername' => $un, 'localusr' => $user->id)); } $user->authinstance = $values['authinstance']; } } update_record('usr', $user); redirect('/admin/users/edit.php?id=' . $user->id); }
/** * Get more info for the collections: owner, url, tags, views * * @param array a list of collections $collectiondata * @return array updated collection data */ public static function get_extra_collection_info(&$collectiondata, $gettags = true) { if ($collectiondata) { // Get view owner details for display $owners = array(); $groups = array(); $institutions = array(); foreach ($collectiondata as $c) { if (!empty($c->owner) && !isset($owners[$c->owner])) { $owners[$c->owner] = (int) $c->owner; } else { if (!empty($c->group) && !isset($groups[$c->group])) { $groups[$c->group] = (int) $c->group; } else { if (!empty($c->institution) && !isset($institutions[$c->institution])) { $institutions[$c->institution] = $c->institution; } } } } if ($gettags) { $collectionidlist = join(',', array_map('intval', array_keys($collectiondata))); $tags = get_records_select_array('collection_tag', 'collection IN (' . $collectionidlist . ')'); if ($tags) { foreach ($tags as &$tag) { $collectiondata[$tag->collection]->tags[] = $tag->tag; } } } if (!empty($owners)) { global $USER; $userid = $USER->get('id'); $fields = array('id', 'username', 'firstname', 'lastname', 'preferredname', 'admin', 'staff', 'studentid', 'email', 'profileicon', 'urlid', 'suspendedctime'); if (count($owners) == 1 && isset($owners[$userid])) { $owners = array($userid => new StdClass()); foreach ($fields as $f) { $owners[$userid]->{$f} = $USER->get($f); } } else { $owners = get_records_select_assoc('usr', 'id IN (' . join(',', array_fill(0, count($owners), '?')) . ')', $owners, '', join(',', $fields)); } } if (!empty($groups)) { $groups = get_records_select_assoc('group', 'id IN (' . join(',', $groups) . ')', null, '', 'id,name,urlid'); } if (!empty($institutions)) { $institutions = get_records_assoc('institution', '', '', '', 'name,displayname'); $institutions['mahara']->displayname = get_config('sitename'); } $wwwroot = get_config('wwwroot'); $needsubdomain = get_config('cleanurlusersubdomains'); foreach ($collectiondata as &$c) { if (!empty($c->owner)) { $c->sharedby = display_name($owners[$c->owner]); $c->user = $owners[$c->owner]; } else { if (!empty($c->group)) { $c->sharedby = $groups[$c->group]->name; $c->groupdata = $groups[$c->group]; } else { if (!empty($c->institution)) { $c->sharedby = $institutions[$c->institution]->displayname; } } } $c = (array) $c; // Now that we have the owner & group records, create a temporary Collection object // so that we can use get_url method. require_once get_config('libroot') . 'collection.php'; $collection = new Collection(0, $c); $c['url'] = $collection->get_url(false); $c['fullurl'] = $needsubdomain ? $collection->get_url(true) : $wwwroot . $c['url']; // Get any views that are part of this collection $c['views'] = get_records_sql_assoc('SELECT v.id, v.title, v.mtime FROM {view} v, {collection_view} cv, {collection} c WHERE cv.collection = c.id AND cv.view = v.id AND c.id = ?', array($c['id'])); // Set the collection modified time as the highest view // modified time if higher than collection modified time foreach ($c['views'] as $view) { $cmodified = new DateTime($c['mtime']); $vmodified = new DateTime($view->mtime); if ($vmodified > $cmodified) { $c['mtime'] = $view->mtime; } } } } }
/** * Deletes a Collection * */ public function delete() { $viewids = get_column('collection_view', 'view', 'collection', $this->id); db_begin(); // Delete navigation blocks within the collection's views which point at this collection. if ($viewids) { $values = $viewids; $values[] = 'navigation'; $navigationblocks = get_records_select_assoc('block_instance', 'view IN (' . join(',', array_fill(0, count($viewids), '?')) . ') AND blocktype = ?', $values); if ($navigationblocks) { safe_require('blocktype', 'navigation'); foreach ($navigationblocks as $b) { $bi = new BlockInstance($b->id, $b); $configdata = $bi->get('configdata'); if (isset($configdata['collection']) && $configdata['collection'] == $this->id) { $bi->delete(); } } } } delete_records('collection_view', 'collection', $this->id); delete_records('collection_tag', 'collection', $this->id); delete_records('collection', 'id', $this->id); // Secret url records belong to the collection, so remove them from the view. // @todo: add user message to whatever calls this. if ($viewids) { delete_records_select('view_access', 'view IN (' . join(',', $viewids) . ') AND token IS NOT NULL'); } db_commit(); }
public static function get_extra_view_info(&$viewdata, $getartefacts = true) { if ($viewdata) { // Get view owner details for display $owners = array(); $groups = array(); $institutions = array(); foreach ($viewdata as $v) { if ($v->owner && !isset($owners[$v->owner])) { $owners[$v->owner] = (int) $v->owner; } else { if ($v->group && !isset($groups[$v->group])) { $groups[$v->group] = (int) $v->group; } else { if (strlen($v->institution) && !isset($institutions[$v->institution])) { $institutions[$v->institution] = $v->institution; } } } } $viewidlist = join(',', array_map('intval', array_keys($viewdata))); if ($getartefacts) { $artefacts = get_records_sql_array('SELECT va.view, va.artefact, a.title, a.artefacttype, t.plugin FROM {view_artefact} va INNER JOIN {artefact} a ON va.artefact = a.id INNER JOIN {artefact_installed_type} t ON a.artefacttype = t.name WHERE va.view IN (' . $viewidlist . ') GROUP BY va.view, va.artefact, a.title, a.artefacttype, t.plugin ORDER BY a.title, va.artefact', ''); if ($artefacts) { foreach ($artefacts as $artefactrec) { safe_require('artefact', $artefactrec->plugin); $classname = generate_artefact_class_name($artefactrec->artefacttype); $artefactobj = new $classname(0, array('title' => $artefactrec->title)); $artefactobj->set('dirty', false); if (!$artefactobj->in_view_list()) { continue; } $artname = $artefactobj->display_title(30); if (strlen($artname)) { $viewdata[$artefactrec->view]->artefacts[] = array('id' => $artefactrec->artefact, 'title' => $artname); } } } } $tags = get_records_select_array('view_tag', 'view IN (' . $viewidlist . ')'); if ($tags) { foreach ($tags as &$tag) { $viewdata[$tag->view]->tags[] = $tag->tag; } } if (!empty($owners)) { $owners = get_records_select_assoc('usr', 'id IN (' . join(',', $owners) . ')', null, '', 'id,username,firstname,lastname,preferredname,admin,staff,studentid,email,profileicon'); } if (!empty($groups)) { $groups = get_records_select_assoc('group', 'id IN (' . join(',', $groups) . ')', null, '', 'id,name'); } if (!empty($institutions)) { $institutions = get_records_assoc('institution', '', '', '', 'name,displayname'); $institutions['mahara']->displayname = get_config('sitename'); } foreach ($viewdata as &$v) { $v->shortdescription = str_shorten_html(str_replace('<br />', ' ', $v->description), 100, true); if ($v->owner) { $v->sharedby = View::owner_name($v->ownerformat, $owners[$v->owner]); $v->user = $owners[$v->owner]; } else { if ($v->group) { $v->sharedby = $groups[$v->group]->name; } else { if ($v->institution) { $v->sharedby = $institutions[$v->institution]->displayname; } } } $v = (array) $v; } } }
$values = array($institution); $params['institution'] = $institution; } else { define('MENUITEM', 'content/notes'); $pageheading = get_string('mynotes', 'artefact.internal'); $where = 'owner = ?'; $values = array($USER->get('id')); } } if ($params) { $baseurl .= '?' . http_build_query($params); } $where .= ' AND artefacttype = ?'; $values[] = 'html'; $count = count_records_select('artefact', $where, $values); $data = get_records_select_assoc('artefact', $where, $values, 'title, id', '*', $offset, $limit); // Get blocks if ($data) { $blocks = get_records_sql_assoc(' SELECT bi.id AS block, bi.title AS blocktitle, va.artefact, va.view, v.title AS viewtitle, v.owner, v.group, v.institution, v.ownerformat, v.urlid FROM {block_instance} bi JOIN {view_artefact} va ON bi.id = va.block JOIN {view} v ON va.view = v.id WHERE va.artefact IN (' . join(',', array_fill(0, count($data), '?')) . ') ORDER BY va.view, bi.title', array_keys($data)); if ($blocks) {
*/ define('INTERNAL', 1); define('JSON', 1); require dirname(dirname(__FILE__)) . '/init.php'; require_once 'group.php'; $data['error'] = false; $data['message'] = null; $initialgroups = param_integer_list('initialgroups', array()); $resultgroups = param_integer_list('resultgroups', array()); $userid = param_integer('userid'); $addtype = param_variable('addtype'); // Prevent group membership changing done by ordinary members, Tutors can only // add members to group and cannot remove anyone. Group admins can do anything. // With regard to invitation, both admins and tutors can invite people. $allgroups = array_unique(array_merge($initialgroups, $resultgroups)); $groupdata = get_records_select_assoc('group', 'id IN (' . join(',', array_fill(0, count($allgroups), '?')) . ')', $allgroups); foreach (group_get_grouptypes() as $grouptype) { safe_require('grouptype', $grouptype); } foreach ($allgroups as $groupid) { if (!($loggedinrole = group_user_access($groupid))) { json_reply('local', get_string('accessdenied', 'error')); } if ($loggedinrole == 'admin') { continue; } if (!in_array($loggedinrole, call_static_method('GroupType' . $groupdata[$groupid]->grouptype, 'get_view_assessing_roles'))) { json_reply('local', get_string('accessdenied', 'error')); } if (group_user_access($groupid, $userid) && in_array($groupid, array_diff($initialgroups, $resultgroups))) { json_reply('local', get_string('cantremovememberfromgroup', 'group', hsc($groupdata[$groupid]->name)));
public static function archive_mime_types() { static $mimetypes = null; if (is_null($mimetypes)) { $descriptions = self::archive_file_descriptions(); $mimetypes = get_records_select_assoc('artefact_file_mime_types', 'description IN (' . join(',', array_map('db_quote', array_keys($descriptions))) . ')'); } return $mimetypes; }
} switch (group_user_access($groupid)) { case 'member': json_reply('local', get_string('accessdenied', 'error')); break; case 'tutor': if ($usertype = group_user_access($groupid, $userid)) { if ($usertype == 'member' && in_array($groupid, array_diff($initialgroups, $resultgroups))) { json_reply('local', get_string('cantremovemember', 'group')); } elseif ($usertype != 'member' && in_array($groupid, array_diff($initialgroups, $resultgroups))) { json_reply('local', get_string('cantremoveuserisadmin', 'group')); } } } } $groupdata = get_records_select_assoc('group', 'id IN (' . join(',', array_unique(array_merge($initialgroups, $resultgroups))) . ')'); if ($jointype == 'controlled') { db_begin(); //remove group membership if ($groupstoremove = array_diff($initialgroups, $resultgroups)) { $groupstoremovemail = ''; foreach ($groupstoremove as $groupid) { group_remove_user($groupid, $userid, $role = null); $groupstoremovemail .= $groupdata[$groupid]->name . "\n"; } } //add group membership if ($groupstoadd = array_diff($resultgroups, $initialgroups)) { $groupstoaddmail = ''; foreach ($groupstoadd as $groupid) { group_add_user($groupid, $userid, $role = null);
function locked_profile_fields() { global $USER; // Profile fields are locked for a user if they are locked by any // institution the user is a member of, but not an admin for. $lockinginstitutions = array_keys($USER->get('institutions')); $lockinginstitutions[] = 'mahara'; $lockinginstitutions = array_diff($lockinginstitutions, $USER->get('admininstitutions')); return get_records_select_assoc('institution_locked_profile_field', 'name IN (' . join(',', array_map('db_quote', $lockinginstitutions)) . ')', null, '', 'profilefield,name'); }
/** * Given a file, returns the folder path for it in the Mahara files area * * The path is pre-sanitised so it can be used when generating the export * * @param $file The file or folder to get the folder path for * @return string */ private function get_folder_path_for_file($file) { if ($this->folderdata === null) { $this->folderdata = get_records_select_assoc('artefact', "artefacttype = 'folder' AND owner = ?", array($file->get('owner'))); if ($this->folderdata) { foreach ($this->folderdata as &$folder) { $folder->title = PluginExportHtml::sanitise_path($folder->title); } } } $folderpath = ArtefactTypeFileBase::get_full_path($file->get('parent'), $this->folderdata); return $folderpath; }
public function removeMember($user) { if (is_numeric($user)) { $user = get_record('usr', 'id', $user); } db_begin(); // If the user is being authed by the institution they are // being removed from, change them to internal auth, or if // we can't find that, some other no institution auth. $authinstances = get_records_select_assoc('auth_instance', "institution IN ('mahara', ?)", array($this->name), "institution = 'mahara' DESC, authname = 'internal' DESC"); $oldauth = $user->authinstance; if (isset($authinstances[$oldauth]) && $authinstances[$oldauth]->institution == $this->name) { foreach ($authinstances as $ai) { if ($ai->authname == 'internal' && $ai->institution == 'mahara') { $user->authinstance = $ai->id; break; } else { if ($ai->institution == 'mahara') { $user->authinstance = $ai->id; break; } } } delete_records('auth_remote_user', 'authinstance', $oldauth, 'localusr', $user->id); // If the old authinstance was external, the user may need // to set a password if ($user->password == '') { log_debug('resetting pw for ' . $user->id); $this->removeMemberSetPassword($user); } else { if ($authinstances[$oldauth]->authname != 'internal') { $sitename = get_config('sitename'); $fullname = display_name($user, null, true); email_user($user, null, get_string('noinstitutionoldpassemailsubject', 'mahara', $sitename, $this->displayname), get_string('noinstitutionoldpassemailmessagetext', 'mahara', $fullname, $this->displayname, $sitename, $user->username, get_config('wwwroot'), get_config('wwwroot'), $sitename, get_config('wwwroot')), get_string('noinstitutionoldpassemailmessagehtml', 'mahara', hsc($fullname), hsc($this->displayname), hsc($sitename), hsc($user->username), get_config('wwwroot'), get_config('wwwroot'), get_config('wwwroot'), hsc($sitename), get_config('wwwroot'), get_config('wwwroot'))); } } update_record('usr', $user); } // If this user has a favourites list which is updated by this institution, remove it // from this institution's control. // Don't delete it in case the user wants to keep it, but move it out of the way, so // another institution can create a new faves list with the same name. execute_sql("\n UPDATE {favorite}\n SET institution = NULL, shortname = substring(shortname from 1 for 100) || '.' || ?\n WHERE owner = ? AND institution = ?", array(substr($this->name, 0, 100) . '.' . get_random_key(), $user->id, $this->name)); execute_sql("\n DELETE FROM {usr_tag}\n WHERE usr = ? AND tag " . db_ilike() . " 'lastinstitution:%'", array($user->id)); insert_record('usr_tag', (object) array('usr' => $user->id, 'tag' => 'lastinstitution:' . strtolower($this->name))); // If the user's license default is set to "institution default", remove the pref delete_records('usr_account_preference', 'usr', $user->id, 'field', 'licensedefault', 'value', LICENSE_INSTITUTION_DEFAULT); delete_records('usr_institution', 'usr', $user->id, 'institution', $this->name); handle_event('updateuser', $user->id); db_commit(); }
function progressbar_sideblock($preview = false) { global $USER; // TODO: Remove this URL param from here, and when previewing pass institution // by function param instead $institution = param_alphanum('i', null); if (is_array($USER->institutions) && count($USER->institutions) > 0) { // Get all institutions where user is member $institutions = array(); foreach ($USER->institutions as $inst) { if (empty($inst->suspended)) { $institutions = array_merge($institutions, array($inst->institution => $inst->displayname)); } } // Set user's first institution in case that institution isn't // set yet or user is not member of currently set institution. if (!$institution || !array_key_exists($institution, $institutions)) { $institution = key(array_slice($institutions, 0, 1)); } } else { $institutions = array(); $institution = 'mahara'; } // Set appropriate preview according to institution, if the institutio is selected // If the institution isn't selected then show preview for first institution, which // is also selected as a default value in institution selection box if ($preview) { $default = get_column('institution', 'name'); // TODO: Remove this URL param from here, and when previewing pass institution // by function param instead $institution = param_alphanum('institution', $default[0]); } // We need to check to see if any of the institutions have profile completeness to allow // the select box to work correctly for users with more than one institution $multiinstitutionprogress = false; $counting = null; if (!empty($institutions)) { foreach ($institutions as $key => $value) { if ($result = get_records_select_assoc('institution_config', 'institution=? and field like \'progressbaritem_%\'', array($key), 'field', 'field, value')) { $multiinstitutionprogress = true; if ($key == $institution) { $counting = $result; break; } } } } else { $counting = get_records_select_assoc('institution_config', 'institution=? and field like \'progressbaritem_%\'', array($institution), 'field', 'field, value'); } // Get artefacts that count towards profile completeness if ($counting) { // Without locked ones (site locked and institution locked) $sitelocked = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', 'mahara'); $instlocked = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', $institution); $locked = $sitelocked + $instlocked; foreach ($locked as $l) { unset($counting["progressbaritem_internal_{$l}"]); } $totalcounting = 0; foreach ($counting as $c) { $totalcounting = $totalcounting + $c->value; } // Get all artefacts for progressbar and create data structure $data = array(); // For the artefact_get_progressbar_items function, we want them indexed by plugin // and then subindexed by artefact. For most other purposes, having them indexed // by config name is sufficient $onlytheseplugins = array(); foreach ($counting as $key => $obj) { // This one has no value. So remove it from the list. if (!$obj->value) { unset($counting[$key]); continue; } $parts = explode('_', $obj->field); $plugin = $parts[1]; $item = $parts[2]; if (empty($onlytheseplugins[$plugin])) { $onlytheseplugins[$plugin] = array(); } $onlytheseplugins[$plugin][$item] = $item; } $progressbaritems = artefact_get_progressbar_items($onlytheseplugins); // Get the data link about every item foreach ($progressbaritems as $pluginname => $itemlist) { foreach ($itemlist as $artefactname => $item) { $itemname = "progressbaritem_{$pluginname}_{$artefactname}"; $c = $counting[$itemname]; $target = $c->value; $completed = 0; $data[$itemname] = array('artefact' => $artefactname, 'link' => progressbar_artefact_link($pluginname, $artefactname), 'counting' => $target, 'completed' => $completed, 'display' => (bool) $c->value, 'label' => progressbar_artefact_task_label($pluginname, $artefactname, $target, $completed)); } } if ($preview) { $percent = 0; } else { // Since this is not a preview, gather data about the users' actual progress, // and update the records we placed in $data. // Get a list of all the basic artefact types in this progress bar. $nonmeta = array(); foreach ($progressbaritems as $plugin => $pluginitems) { foreach ($pluginitems as $itemname => $item) { if (!$item->ismeta) { $nonmeta[] = $itemname; } } } if ($nonmeta) { // To reduce the number of queries, we gather data about all the user's artefacts // at once. (Metaartefacts are handled separately, below) $insql = "'" . implode("','", $nonmeta) . "'"; $sql = "SELECT artefacttype, (select plugin from {artefact_installed_type} ait where ait.name=a.artefacttype) as plugin, COUNT(*) AS completed\n FROM {artefact} a\n WHERE owner = ?\n AND artefacttype in ({$insql})\n GROUP BY artefacttype"; $normalartefacts = get_records_sql_array($sql, array($USER->get('id'))); if (!$normalartefacts) { $normalartefacts = array(); } } else { // No basic artefacts in this one, so we just use an empty array for this. $normalartefacts = array(); } $totalcompleted = 0; $metaartefacts = array(); foreach ($progressbaritems as $plugin => $pluginitems) { if (is_array($records = artefact_get_progressbar_metaartefacts($plugin, $pluginitems))) { foreach ($records as $record) { $record->plugin = $plugin; array_push($metaartefacts, $record); } } } foreach (array_merge($normalartefacts, $metaartefacts) as $record) { $itemname = "progressbaritem_{$record->plugin}_{$record->artefacttype}"; // It's not an item we're tracking, so skip it. if (!array_key_exists($itemname, $counting)) { continue; } $target = $counting[$itemname]->value; $remaining = max(0, $target - $record->completed); // Override the data for this item $data[$itemname]['completed'] = $record->completed; $data[$itemname]['display'] = $remaining > 0; $data[$itemname]['label'] = $label = get_string('progress_' . $record->artefacttype, 'artefact.' . $record->plugin, $remaining); if ($target > 0) { $totalcompleted = $totalcompleted + min($target, $record->completed); } } $percent = round($totalcompleted / $totalcounting * 100); if ($percent > 100) { $percent = 100; } } return array('data' => $data, 'percent' => $percent, 'preview' => $preview, 'count' => $preview ? 1 : count($institutions), 'institutions' => $institutions, 'institution' => $institution, 'totalcompleted' => !empty($totalcompleted) ? $totalcompleted : 0, 'totalcounting' => $totalcounting); } else { if ($multiinstitutionprogress) { return array('data' => null, 'percent' => 0, 'preview' => $preview, 'count' => $preview ? 1 : count($institutions), 'institutions' => $institutions, 'institution' => $institution, 'totalcompleted' => 0, 'totalcounting' => 0); } } return array('data' => null, 'percent' => 0, 'preview' => $preview, 'count' => 1, 'institutions' => null, 'institution' => 'mahara'); }
public static function artefactchooser_folder_data(&$artefact) { // Grab data about all folders the artefact owner has, so we // can make full paths to them, and show the artefact owner if // it's a group or institution. static $folderdata = array(); $ownerkey = $artefact->owner . '::' . $artefact->group . '::' . $artefact->institution; if (!isset($folderdata[$ownerkey])) { $ownersql = artefact_owner_sql($artefact->owner, $artefact->group, $artefact->institution); $folderdata[$ownerkey]->data = get_records_select_assoc('artefact', "artefacttype='folder' AND {$ownersql}", array(), '', 'id, title, parent'); if ($artefact->group) { $folderdata[$ownerkey]->ownername = get_field('group', 'name', 'id', $artefact->group) . ':'; } else { if ($artefact->institution) { if ($artefact->institution == 'mahara') { $folderdata[$ownerkey]->ownername = get_config('sitename') . ':'; } else { $folderdata[$ownerkey]->ownername = get_field('institution', 'displayname', 'name', $artefact->institution) . ':'; } } else { $folderdata[$ownerkey]->ownername = ''; } } } return $folderdata[$ownerkey]; }
/** * Does a bulk_delete on a list of artefacts, grouping artefacts of * the same type. * * Currently only tested for folders and their contents. */ public static function delete_by_artefacttype($artefactids) { if (empty($artefactids)) { return; } db_begin(); artefact_watchlist_notification($artefactids); // Delete comments first safe_require('artefact', 'comment'); ArtefactTypeComment::delete_comments_onartefacts($artefactids); $records = get_records_select_assoc('artefact', 'id IN (' . join(',', array_map('intval', $artefactids)) . ')', null, 'artefacttype', 'id,parent,artefacttype,container'); $containers = array(); $leaves = array(); foreach ($records as $r) { if ($r->container) { $containers[$r->artefacttype][] = (int) $r->id; } else { $leaves[$r->artefacttype][] = $r->id; } } // Delete non-containers grouped by artefacttype foreach ($leaves as $artefacttype => $ids) { $classname = generate_artefact_class_name($artefacttype); call_static_method($classname, 'bulk_delete', $ids); } // Delete containers grouped by artefacttype foreach ($containers as $artefacttype => $ids) { $classname = generate_artefact_class_name($artefacttype); if (is_mysql()) { set_field_select('artefact', 'parent', null, 'id IN (' . join(',', $ids) . ')', array()); } call_static_method($classname, 'bulk_delete', $ids); } handle_event('deleteartefacts', $artefactids); db_commit(); }
$id = param_integer('id'); $new = param_boolean('new'); $view = new View($id); if (!$USER->can_edit_view($view)) { throw new AccessDeniedException(); } $view->set_edit_nav(); $view->set_user_theme(); $numrows = $view->get('numrows'); $numcolumns = $view->get('numcolumns'); $layoutcolumns = View::$layoutcolumns; // static, all possible column width combinations $layoutrows = $view->get_layoutrows(); $maxlayoutrows = View::$maxlayoutrows; // static, max possible rows for custom layouts $basicoptionids = array_keys(get_records_select_assoc('view_layout', 'layoutmenuorder > 0 AND iscustom = 0', array(), 'layoutmenuorder', 'id, id')); $currentlayout = $view->get('layout'); // if not set, use equal width layout for that number of columns if (!$currentlayout) { // if columns have been dynamically added or removed from a multi-row layout, // there may be no valid layout id, in which case none of the layout options will be selected $currentlayout = $view->get_layout()->id; } if (!in_array($currentlayout, $basicoptionids)) { $basicoptionids[] = $currentlayout; } $layoutoptions = array(); $basiclayoutoptions = array(); $maxrows = 3; foreach ($layoutrows as $key => $layout) { $maxrows = count($layout) > $maxrows ? count($layout) : $maxrows;
function edituser_site_submit(Pieform $form, $values) { global $USER, $authobj, $SESSION; if (!($user = get_record('usr', 'id', $values['id']))) { return false; } if (is_using_probation()) { // Value should be between 0 and 10 inclusive $user->probation = ensure_valid_probation_points($values['probationpoints']); } if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) { $user->quota = $values['quota']; // check if the user has gone over the quota notify limit $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit'); if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) { $quotanotifylimit = 100; } $user->quotausedpercent = $user->quotaused / $user->quota * 100; $overlimit = false; if ($quotanotifylimit <= $user->quotausedpercent) { $overlimit = true; } $notified = get_field('usr_account_preference', 'value', 'field', 'quota_exceeded_notified', 'usr', $user->id); if ($overlimit && '1' !== $notified) { require_once get_config('docroot') . 'artefact/file/lib.php'; ArtefactTypeFile::notify_users_threshold_exceeded(array($user), false); // no need to email admin as we can alert them right now $SESSION->add_error_msg(get_string('useroverquotathreshold', 'artefact.file', display_name($user))); } else { if ($notified && !$overlimit) { set_account_preference($user->id, 'quota_exceeded_notified', false); } } } $unexpire = $user->expiry && strtotime($user->expiry) < time() && (empty($values['expiry']) || $values['expiry'] > time()); $newexpiry = db_format_timestamp($values['expiry']); if ($user->expiry != $newexpiry) { $user->expiry = $newexpiry; if ($unexpire) { $user->expirymailsent = 0; $user->lastaccess = db_format_timestamp(time()); } } // Try to kick the user from any active login sessions, before saving data. require_once get_config('docroot') . 'auth/session.php'; remove_user_sessions($user->id); if ($USER->get('admin')) { // Not editable by institutional admins $user->staff = (int) ($values['staff'] == 'on'); $user->admin = (int) ($values['admin'] == 'on'); if ($user->admin) { activity_add_admin_defaults(array($user->id)); } } if ($values['maildisabled'] == 0 && get_account_preference($user->id, 'maildisabled') == 1) { // Reset the sent and bounce counts otherwise mail will be disabled // on the next send attempt $u = new StdClass(); $u->email = $user->email; $u->id = $user->id; update_bounce_count($u, true); update_send_count($u, true); } set_account_preference($user->id, 'maildisabled', $values['maildisabled']); // process the change of the authinstance and or the remoteuser if (isset($values['authinstance']) && isset($values['remoteusername'])) { // Authinstance can be changed by institutional admins if both the // old and new authinstances belong to the admin's institutions $authinst = get_records_select_assoc('auth_instance', 'id = ? OR id = ?', array($values['authinstance'], $user->authinstance)); // But don't bother if the auth instance doesn't take a remote username $authobj = AuthFactory::create($values['authinstance']); if ($USER->get('admin') || $USER->is_institutional_admin($authinst[$values['authinstance']]->institution) && ($USER->is_institutional_admin($authinst[$user->authinstance]->institution) || $user->authinstance == 1)) { if ($authobj->needs_remote_username()) { // determine the current remoteuser $current_remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id); if (!$current_remotename) { $current_remotename = $user->username; } // if the remoteuser is empty if (strlen(trim($values['remoteusername'])) == 0) { delete_records('auth_remote_user', 'authinstance', $user->authinstance, 'localusr', $user->id); } // what should the new remoteuser be $new_remoteuser = get_field('auth_remote_user', 'remoteusername', 'authinstance', $values['authinstance'], 'localusr', $user->id); // save the remotename for the target existence check $target_remotename = $new_remoteuser; if (!$new_remoteuser) { $new_remoteuser = $user->username; } if (strlen(trim($values['remoteusername'])) > 0) { // value changed on page - use it if ($values['remoteusername'] != $current_remotename) { $new_remoteuser = $values['remoteusername']; } } // only update remote name if the input actually changed on the page or it doesn't yet exist if ($current_remotename != $new_remoteuser || !$target_remotename) { // only remove the ones related to this traget authinstance as we now allow multiple // for dual login mechanisms delete_records('auth_remote_user', 'authinstance', $values['authinstance'], 'localusr', $user->id); insert_record('auth_remote_user', (object) array('authinstance' => $values['authinstance'], 'remoteusername' => $new_remoteuser, 'localusr' => $user->id)); } } // update the ai on the user master $user->authinstance = $values['authinstance']; // update the global $authobj to match the new authinstance // this is used by the password/username change methods // if either/both has been requested at the same time $authobj = AuthFactory::create($user->authinstance); } } // Only change the pw if the new auth instance allows for it if (method_exists($authobj, 'change_password')) { $user->passwordchange = (int) (isset($values['passwordchange']) && $values['passwordchange'] == 'on' ? 1 : 0); if (isset($values['password']) && $values['password'] !== '') { $userobj = new User(); $userobj = $userobj->find_by_id($user->id); $user->password = $authobj->change_password($userobj, $values['password']); $user->salt = $userobj->salt; unset($userobj); } } else { // inform the user that the chosen auth instance doesn't allow password changes // but only if they tried changing it if (isset($values['password']) && $values['password'] !== '') { $SESSION->add_error_msg(get_string('passwordchangenotallowed', 'admin')); // Set empty pw with salt $user->password = ''; $user->salt = auth_get_random_salt(); } } if (isset($values['username']) && $values['username'] !== '') { $userobj = new User(); $userobj = $userobj->find_by_id($user->id); if ($userobj->username != $values['username']) { // Only change the username if the auth instance allows for it if (method_exists($authobj, 'change_username')) { // check the existence of the chosen username try { if ($authobj->user_exists($values['username'])) { // set an error message if it is already in use $SESSION->add_error_msg(get_string('usernameexists', 'account')); } } catch (AuthUnknownUserException $e) { // update the username otherwise $user->username = $authobj->change_username($userobj, $values['username']); } } else { // inform the user that the chosen auth instance doesn't allow username changes $SESSION->add_error_msg(get_string('usernamechangenotallowed', 'admin')); } } unset($userobj); } // OVERWRITE 4: insert if (isset($values['email']) && !empty($values['email']) && $values['email'] != $user->email) { global $CFG; $user->email = $values['email']; $mhr_user = $CFG->current_app->getUserById($user->id); $mhr_user->setEmailAddress($values['email']); } // END OVERWRITE 4 db_begin(); update_record('usr', $user); delete_records('usr_tag', 'usr', $user->id); if (is_array($values['tags'])) { $values['tags'] = check_case_sensitive($values['tags'], 'usr_tag'); foreach (array_unique($values['tags']) as $tag) { if (empty($tag)) { continue; } insert_record('usr_tag', (object) array('usr' => $user->id, 'tag' => strtolower($tag))); } } db_commit(); $SESSION->add_ok_msg(get_string('usersitesettingschanged', 'admin')); redirect('/admin/users/edit.php?id=' . $user->id); }
function user_authorise($token, $useragent) { global $USER; $sso_session = get_record('sso_session', 'token', $token, 'useragent', $useragent); if (empty($sso_session)) { throw new XmlrpcServerException('No such session exists'); } // check session confirm timeout if ($sso_session->expires < time()) { throw new XmlrpcServerException('This session has timed out'); } // session okay, try getting the user $user = new User(); try { $user->find_by_id($sso_session->userid); } catch (Exception $e) { throw new XmlrpcServerException('Unable to get information for the specified user'); } require_once get_config('docroot') . 'artefact/lib.php'; require_once get_config('docroot') . 'artefact/internal/lib.php'; $element_list = call_static_method('ArtefactTypeProfile', 'get_all_fields'); $element_required = call_static_method('ArtefactTypeProfile', 'get_mandatory_fields'); // load existing profile information $profilefields = array(); $profile_data = get_records_select_assoc('artefact', "owner=? AND artefacttype IN (" . join(",", array_map(create_function('$a', 'return db_quote($a);'), array_keys($element_list))) . ")", array($USER->get('id')), '', 'artefacttype, title'); if ($profile_data == false) { $profile_data = array(); } $email = get_field('artefact_internal_profile_email', 'email', 'owner', $sso_session->userid, 'principal', 1); if (false == $email) { throw new XmlrpcServerException("No email adress for user"); } $userdata = array(); $userdata['username'] = $user->username; $userdata['email'] = $email; $userdata['auth'] = 'mnet'; $userdata['confirmed'] = 1; $userdata['deleted'] = 0; $userdata['firstname'] = $user->firstname; $userdata['lastname'] = $user->lastname; $userdata['city'] = array_key_exists('city', $profile_data) ? $profile_data['city']->title : ''; $userdata['country'] = array_key_exists('country', $profile_data) ? $profile_data['country']->title : ''; if (is_numeric($user->profileicon)) { $filename = get_config('dataroot') . 'artefact/file/profileicons/' . $user->profileicon % 256 . '/' . $user->profileicon; if (file_exists($filename) && is_readable($filename)) { $userdata['imagehash'] = sha1_file($filename); } } get_service_providers($USER->authinstance); // Todo: push application name to list of hosts... update Moodle block to display more info, maybe in 'Other' list $userdata['myhosts'] = array(); return $userdata; }
protected function load_views() { $types = array('profile', 'dashboard'); $views = get_records_select_assoc('view', '"owner" = ? AND type IN (' . join(',', array_map('db_quote', $types)) . ')', array($this->id), '', 'type,id'); $specialviews = array(); foreach ($types as $type) { if (!empty($views[$type])) { $specialviews[$type] = $views[$type]->id; } else { $view = $this->install_view($type); $specialviews[$type] = $view->get('id'); } } $this->set('views', $specialviews); }
function artefact_get_records_by_id($ids) { if (!empty($ids)) { if ($records = get_records_select_assoc('artefact', 'id IN (' . join(',', $ids) . ')')) { return $records; } } return array(); }