Esempio n. 1
0
 /**
  * Grab a delegate object for auth stuff
  */
 public function request_user_authorise($token, $remotewwwroot)
 {
     global $USER, $SESSION;
     $this->must_be_ready();
     $peer = get_peer($remotewwwroot);
     if ($peer->deleted != 0 || $this->config['theyssoin'] != 1) {
         throw new XmlrpcClientException('We don\'t accept SSO connections from ' . institution_display_name($peer->institution));
     }
     $client = new Client();
     $client->set_method('auth/mnet/auth.php/user_authorise')->add_param($token)->add_param(sha1($_SERVER['HTTP_USER_AGENT']))->send($remotewwwroot);
     $remoteuser = (object) $client->response;
     if (empty($remoteuser) or !property_exists($remoteuser, 'username')) {
         // Caught by land.php
         throw new AccessDeniedException();
     }
     $create = false;
     $update = false;
     if ('1' == $this->config['updateuserinfoonlogin']) {
         $update = true;
     }
     // Retrieve a $user object. If that fails, create a blank one.
     try {
         $user = new User();
         if (get_config('usersuniquebyusername')) {
             // When turned on, this setting means that it doesn't matter
             // which other application the user SSOs from, they will be
             // given the same account in Mahara.
             //
             // This setting is one that has security implications unless
             // only turned on by people who know what they're doing. In
             // particular, every system linked to Mahara should be making
             // sure that same username == same person.  This happens for
             // example if two Moodles are using the same LDAP server for
             // authentication.
             //
             // If this setting is on, it must NOT be possible to self
             // register on the site for ANY institution - otherwise users
             // could simply pick usernames of people's accounts they wished
             // to steal.
             if ($institutions = get_column('institution', 'name', 'registerallowed', '1')) {
                 log_warn("usersuniquebyusername is turned on but registration is allowed for an institution. " . "No institution can have registration allowed for it, for security reasons.\n" . "The following institutions have registration enabled:\n  " . join("\n  ", $institutions));
                 throw new AccessDeniedException();
             }
             if (!get_config('usersallowedmultipleinstitutions')) {
                 log_warn("usersuniquebyusername is turned on but usersallowedmultipleinstitutions is off. " . "This makes no sense, as users will then change institution every time they log in from " . "somewhere else. Please turn this setting on in Site Options");
                 throw new AccessDeniedException();
             }
             $user->find_by_username($remoteuser->username);
         } else {
             $user->find_by_instanceid_username($this->instanceid, $remoteuser->username, true);
         }
         if ($user->get('suspendedcusr')) {
             die_info(get_string('accountsuspended', 'mahara', strftime(get_string('strftimedaydate'), $user->get('suspendedctime')), $user->get('suspendedreason')));
         }
     } catch (AuthUnknownUserException $e) {
         if (!empty($this->config['weautocreateusers'])) {
             $institution = new Institution($this->institution);
             if ($institution->isFull()) {
                 $institution->send_admin_institution_is_full_message();
                 throw new XmlrpcClientException('SSO attempt from ' . $institution->displayname . ' failed - institution is full');
             }
             $user = new User();
             $create = true;
         } else {
             log_debug("User authorisation request from {$remotewwwroot} failed - " . "remote user '{$remoteuser->username}' is unknown to us and auto creation of users is turned off");
             return false;
         }
     }
     /*******************************************/
     if ($create) {
         $user->passwordchange = 1;
         $user->active = 1;
         $user->deleted = 0;
         //TODO: import institution's expiry?:
         //$institution = new Institution($peer->institution);
         $user->expiry = null;
         $user->expirymailsent = 0;
         $user->lastlogin = time();
         $user->firstname = $remoteuser->firstname;
         $user->lastname = $remoteuser->lastname;
         $user->email = $remoteuser->email;
         $imported = array('firstname', 'lastname', 'email');
         //TODO: import institution's per-user-quota?:
         //$user->quota              = $userrecord->quota;
         $user->authinstance = empty($this->config['parent']) ? $this->instanceid : $this->parent;
         db_begin();
         $user->username = get_new_username($remoteuser->username);
         $user->id = create_user($user, array(), $this->institution, $this, $remoteuser->username);
         $locked = $this->import_user_settings($user, $remoteuser);
         $locked = array_merge($imported, $locked);
         /*
          * We need to convert the object to a stdclass with its own
          * custom method because it uses overloaders in its implementation
          * and its properties wouldn't be visible to a simple cast operation
          * like (array)$user
          */
         $userobj = $user->to_stdclass();
         $userarray = (array) $userobj;
         db_commit();
         // Now we have fired the create event, we need to re-get the data
         // for this user
         $user = new User();
         $user->find_by_id($userobj->id);
     } elseif ($update) {
         $imported = array('firstname', 'lastname', 'email');
         foreach ($imported as $field) {
             if ($user->{$field} != $remoteuser->{$field}) {
                 $user->{$field} = $remoteuser->{$field};
                 set_profile_field($user->id, $field, $user->{$field});
             }
         }
         if (isset($remoteuser->idnumber)) {
             if ($user->studentid != $remoteuser->idnumber) {
                 $user->studentid = $remoteuser->idnumber;
                 set_profile_field($user->id, 'studentid', $user->studentid);
             }
             $imported[] = 'studentid';
         }
         $locked = $this->import_user_settings($user, $remoteuser);
         $locked = array_merge($imported, $locked);
         $user->lastlastlogin = $user->lastlogin;
         $user->lastlogin = time();
         //TODO: import institution's per-user-quota?:
         //$user->quota              = $userrecord->quota;
         $user->commit();
     }
     if (get_config('usersuniquebyusername')) {
         // Add them to the institution they have SSOed in by
         $user->join_institution($peer->institution);
     }
     // See if we need to create/update a profile Icon image
     if ($create || $update) {
         $client->set_method('auth/mnet/auth.php/fetch_user_image')->add_param($remoteuser->username)->send($remotewwwroot);
         $imageobject = (object) $client->response;
         $u = preg_replace('/[^A-Za-z0-9 ]/', '', $user->username);
         $filename = get_config('dataroot') . 'temp/mpi_' . intval($this->instanceid) . '_' . $u;
         if (array_key_exists('f1', $client->response)) {
             $imagecontents = base64_decode($client->response['f1']);
             if (file_put_contents($filename, $imagecontents)) {
                 $imageexists = false;
                 $icons = false;
                 if ($update) {
                     $newchecksum = sha1_file($filename);
                     $icons = get_records_select_array('artefact', 'artefacttype = \'profileicon\' AND owner = ? ', array($user->id), '', 'id');
                     if (false != $icons) {
                         foreach ($icons as $icon) {
                             $iconfile = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $icon->id % 256 . '/' . $icon->id;
                             $checksum = sha1_file($iconfile);
                             if ($newchecksum == $checksum) {
                                 $imageexists = true;
                                 unlink($filename);
                                 break;
                             }
                         }
                     }
                 }
                 if (false == $imageexists) {
                     $filesize = filesize($filename);
                     if (!$user->quota_allowed($filesize)) {
                         $error = get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'));
                     }
                     require_once 'file.php';
                     $imagesize = getimagesize($filename);
                     if (!$imagesize || !is_image_type($imagesize[2])) {
                         $error = get_string('filenotimage');
                     }
                     $mime = $imagesize['mime'];
                     $width = $imagesize[0];
                     $height = $imagesize[1];
                     $imagemaxwidth = get_config('imagemaxwidth');
                     $imagemaxheight = get_config('imagemaxheight');
                     if ($width > $imagemaxwidth || $height > $imagemaxheight) {
                         $error = get_string('profileiconimagetoobig', 'artefact.file', $width, $height, $imagemaxwidth, $imagemaxheight);
                     }
                     try {
                         $user->quota_add($filesize);
                     } catch (QuotaException $qe) {
                         $error = get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'));
                     }
                     require_once get_config('docroot') . '/artefact/lib.php';
                     require_once get_config('docroot') . '/artefact/file/lib.php';
                     // Entry in artefact table
                     $artefact = new ArtefactTypeProfileIcon();
                     $artefact->set('owner', $user->id);
                     $artefact->set('parent', ArtefactTypeFolder::get_folder_id(get_string('imagesdir', 'artefact.file'), get_string('imagesdirdesc', 'artefact.file'), null, true, $user->id));
                     $artefact->set('title', ArtefactTypeFileBase::get_new_file_title(get_string('profileicon', 'artefact.file'), (int) $artefact->get('parent'), $user->id));
                     // unique title
                     $artefact->set('description', get_string('uploadedprofileicon', 'artefact.file'));
                     $artefact->set('note', get_string('profileicon', 'artefact.file'));
                     $artefact->set('size', $filesize);
                     $artefact->set('filetype', $mime);
                     $artefact->set('width', $width);
                     $artefact->set('height', $height);
                     $artefact->commit();
                     $id = $artefact->get('id');
                     // Move the file into the correct place.
                     $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
                     check_dir_exists($directory);
                     rename($filename, $directory . $id);
                     if ($create || empty($icons)) {
                         $user->profileicon = $id;
                     }
                 }
                 $user->commit();
             } else {
                 log_warn(get_string('cantcreatetempprofileiconfile', 'artefact.file', $filename));
             }
         }
         if ($update) {
             $locked[] = 'profileicon';
         }
     }
     /*******************************************/
     // We know who our user is now. Bring her back to life.
     $USER->reanimate($user->id, $this->instanceid);
     // Set session variables to let the application know this session was
     // initiated by MNET. Don't forget that users could initiate their
     // sessions without MNET sometimes, which is why this data is stored in
     // the session object.
     $SESSION->set('mnetuser', $user->id);
     $SESSION->set('authinstance', $this->instanceid);
     if (isset($_SERVER['HTTP_REFERER'])) {
         $SESSION->set('mnetuserfrom', $_SERVER['HTTP_REFERER']);
     }
     if ($update && isset($locked)) {
         $SESSION->set('lockedfields', $locked);
     }
     return true;
 }
Esempio n. 2
0
 /**
  * Displaying of the header logo
  * If $name is specified the site-logo-[$name].png will be returned
  */
 public function header_logo($name = false)
 {
     // OVERWRITE 3: INSERTION
     // This overwrite is designed to try and use the header logo
     // from the home MhrInstitution. If there isn't one, we default to
     // our old printBanner.php code to display the banner.
     global $CFG;
     $mhr_institution = $CFG->current_app->getMhrInstitution();
     $this->headerlogo = $mhr_institution->logo;
     if (empty($this->headerlogo)) {
         $banner_file = $CFG->dataroot . 'gc_images/' . $CFG->current_app->getLogo();
         if (is_file($banner_file)) {
             db_begin();
             safe_require('artefact', 'file');
             // Entry in artefact table
             $data = (object) array('institution' => $mhr_institution->name, 'title' => 'logo', 'description' => 'Institution logo', 'note' => $CFG->current_app->getLogo(), 'size' => 0);
             $imageinfo = getimagesize($banner_file);
             $data->width = $imageinfo[0];
             $data->height = $imageinfo[1];
             $data->filetype = $imageinfo['mime'];
             $artefact = new ArtefactTypeProfileIcon(0, $data);
             if (preg_match("/\\.([^\\.]+)\$/", $banner_file, $saved)) {
                 $artefact->set('oldextension', $saved[1]);
             }
             $artefact->commit();
             $id = $artefact->get('id');
             // Move the file into the correct place.
             $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
             check_dir_exists($directory);
             copy($banner_file, $directory . $id);
             set_field('institution', 'logo', $id, 'name', $mhr_institution->name);
             $this->headerlogo = $id;
             db_commit();
         }
     }
     // END OVERWRITE 3
     if (!empty($this->headerlogo)) {
         return get_config('wwwroot') . 'thumb.php?type=logobyid&id=' . $this->headerlogo;
     } else {
         if ($name) {
             return $this->get_url('images/site-logo-' . $name . '.png');
         }
     }
     return $this->get_url('images/site-logo.png');
 }
Esempio n. 3
0
function institution_submit(Pieform $form, $values)
{
    global $SESSION, $institution, $add, $instancearray, $USER, $authinstances, $customthemedefaults;
    db_begin();
    // Update the basic institution record...
    if ($add) {
        $newinstitution = new Institution();
        $newinstitution->initialise($values['name'], $values['displayname']);
        $institution = $newinstitution->name;
    } else {
        $newinstitution = new Institution($institution);
        $newinstitution->displayname = $values['displayname'];
        $oldinstitution = get_record('institution', 'name', $institution);
        // Clear out any cached menus for this institution
        clear_menu_cache($institution);
    }
    $newinstitution->showonlineusers = !isset($values['showonlineusers']) ? 2 : $values['showonlineusers'];
    if (get_config('usersuniquebyusername')) {
        // Registering absolutely not allowed when this setting is on, it's a
        // security risk. See the documentation for the usersuniquebyusername
        // setting for more information
        $newinstitution->registerallowed = 0;
    } else {
        $newinstitution->registerallowed = $values['registerallowed'] ? 1 : 0;
        $newinstitution->registerconfirm = $values['registerconfirm'] ? 1 : 0;
    }
    if (!empty($values['lang'])) {
        if ($values['lang'] == 'sitedefault') {
            $newinstitution->lang = null;
        } else {
            $newinstitution->lang = $values['lang'];
        }
    }
    $newinstitution->theme = empty($values['theme']) || $values['theme'] == 'sitedefault' ? null : $values['theme'];
    $newinstitution->dropdownmenu = !empty($values['dropdownmenu']) ? 1 : 0;
    $newinstitution->skins = !empty($values['skins']) ? 1 : 0;
    require_once get_config('docroot') . 'artefact/comment/lib.php';
    $commentoptions = ArtefactTypeComment::get_comment_options();
    $newinstitution->commentsortorder = empty($values['commentsortorder']) ? $commentoptions->sort : $values['commentsortorder'];
    $newinstitution->commentthreaded = !empty($values['commentthreaded']) ? 1 : 0;
    if ($newinstitution->theme == 'custom') {
        if (!empty($oldinstitution->style)) {
            $styleid = $oldinstitution->style;
            delete_records('style_property', 'style', $styleid);
        } else {
            $record = (object) array('title' => get_string('customstylesforinstitution', 'admin', $newinstitution->displayname));
            $styleid = insert_record('style', $record, 'id', true);
        }
        $properties = array();
        $record = (object) array('style' => $styleid);
        foreach (array_keys($customthemedefaults) as $name) {
            $record->field = $name;
            $record->value = $values[$name];
            insert_record('style_property', $record);
            $properties[$name] = $values[$name];
        }
        // Cache the css
        $smarty = smarty_core();
        $smarty->assign('data', $properties);
        set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);
        $newinstitution->style = $styleid;
    } else {
        $newinstitution->style = null;
    }
    if (get_config('licensemetadata')) {
        $newinstitution->licensemandatory = !empty($values['licensemandatory']) ? 1 : 0;
        $newinstitution->licensedefault = isset($values['licensedefault']) ? $values['licensedefault'] : '';
    }
    if (!empty($values['resetcustom']) && !empty($oldinstitution->style)) {
        $newinstitution->style = null;
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        if (!empty($values['updateuserquotas']) && !empty($values['defaultquota'])) {
            execute_sql("UPDATE {usr} SET quota = ? WHERE id IN (SELECT usr FROM {usr_institution} WHERE institution = ?)", array($values['defaultquota'], $institution));
            // get all the users from the institution and make sure that they are still below
            // their quota threshold
            if ($users = get_records_sql_array('SELECT * FROM {usr} u LEFT JOIN {usr_institution} ui ON u.id = ui.usr AND ui.institution = ?', array($institution))) {
                $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit');
                if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) {
                    $quotanotifylimit = 100;
                }
                foreach ($users as $user) {
                    $user->quota = $values['defaultquota'];
                    // check if the user has gone over the quota notify limit
                    $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);
                        }
                    }
                }
            }
        }
        $newinstitution->defaultquota = empty($values['defaultquota']) ? get_config_plugin('artefact', 'file', 'defaultquota') : $values['defaultquota'];
    }
    if ($institution != 'mahara') {
        $newinstitution->defaultmembershipperiod = $values['defaultmembershipperiod'] ? intval($values['defaultmembershipperiod']) : null;
        if ($USER->get('admin')) {
            $newinstitution->maxuseraccounts = $values['maxuseraccounts'] ? intval($values['maxuseraccounts']) : null;
            $newinstitution->expiry = db_format_timestamp($values['expiry']);
        }
    }
    $newinstitution->allowinstitutionpublicviews = isset($values['allowinstitutionpublicviews']) && $values['allowinstitutionpublicviews'] ? 1 : 0;
    // TODO: Move handling of authentication instances within the Institution class as well?
    if (!empty($values['authplugin'])) {
        $allinstances = array_merge($values['authplugin']['instancearray'], $values['authplugin']['deletearray']);
        if (array_diff($allinstances, $instancearray)) {
            throw new ConfigException('Attempt to delete or update another institution\'s auth instance');
        }
        if (array_diff($instancearray, $allinstances)) {
            throw new ConfigException('One of your instances is unaccounted for in this transaction');
        }
        foreach ($values['authplugin']['instancearray'] as $priority => $instanceid) {
            if (in_array($instanceid, $values['authplugin']['deletearray'])) {
                // Should never happen:
                throw new SystemException('Attempt to update AND delete an auth instance');
            }
            $record = new StdClass();
            $record->priority = $priority;
            $record->id = $instanceid;
            update_record('auth_instance', $record, array('id' => $instanceid));
        }
        foreach ($values['authplugin']['deletearray'] as $instanceid) {
            // If this authinstance is the only xmlrpc authinstance that references a host, delete the host record.
            $hostwwwroot = null;
            foreach ($authinstances as $ai) {
                if ($ai->id == $instanceid && $ai->authname == 'xmlrpc') {
                    $hostwwwroot = get_field_sql("SELECT \"value\" FROM {auth_instance_config} WHERE \"instance\" = ? AND field = 'wwwroot'", array($instanceid));
                    if ($hostwwwroot && count_records_select('auth_instance_config', "field = 'wwwroot' AND \"value\" = ?", array($hostwwwroot)) == 1) {
                        // Unfortunately, it's possible that this host record could belong to a different institution,
                        // so specify the institution here.
                        delete_records('host', 'wwwroot', $hostwwwroot, 'institution', $institution);
                        // We really need to fix this, either by removing the institution from the host table, or refusing to allow the
                        // institution to be changed in the host record when another institution's authinstance is still pointing at it.
                    }
                    break;
                }
            }
            delete_records('auth_remote_user', 'authinstance', $instanceid);
            delete_records('auth_instance_config', 'instance', $instanceid);
            delete_records('auth_instance', 'id', $instanceid);
            // Make it no longer be the parent authority to any auth instances
            delete_records('auth_instance_config', 'field', 'parent', 'value', $instanceid);
        }
    }
    // Store plugin settings.
    plugin_institution_prefs_submit($form, $values, $newinstitution);
    // Save the changes to the DB
    $newinstitution->commit();
    if ($add) {
        // Automatically create an internal authentication authinstance
        $authinstance = (object) array('instancename' => 'internal', 'priority' => 0, 'institution' => $newinstitution->name, 'authname' => 'internal');
        insert_record('auth_instance', $authinstance);
        // We need to add the default lines to the site_content table for this institution
        // We also need to set the institution to be using default static pages to begin with
        // so that using custom institution pages is an opt-in situation
        $pages = site_content_pages();
        $now = db_format_timestamp(time());
        foreach ($pages as $name) {
            $page = new stdClass();
            $page->name = $name;
            $page->ctime = $now;
            $page->mtime = $now;
            $page->content = get_string($page->name . 'defaultcontent', 'install', get_string('staticpageconfiginstitution', 'install'));
            $page->institution = $newinstitution->name;
            insert_record('site_content', $page);
            $institutionconfig = new stdClass();
            $institutionconfig->institution = $newinstitution->name;
            $institutionconfig->field = 'sitepages_' . $name;
            $institutionconfig->value = 'mahara';
            insert_record('institution_config', $institutionconfig);
        }
    }
    if (is_null($newinstitution->style) && !empty($oldinstitution->style)) {
        delete_records('style_property', 'style', $oldinstitution->style);
        delete_records('style', 'id', $oldinstitution->style);
    }
    // Set the logo after updating the institution, because the institution
    // needs to exist before it can own the logo artefact.
    if (!empty($values['logo'])) {
        safe_require('artefact', 'file');
        // Entry in artefact table
        $data = (object) array('institution' => $institution, 'title' => 'logo', 'description' => 'Institution logo', 'note' => $values['logo']['name'], 'size' => $values['logo']['size']);
        $imageinfo = getimagesize($values['logo']['tmp_name']);
        $data->width = $imageinfo[0];
        $data->height = $imageinfo[1];
        $data->filetype = $imageinfo['mime'];
        $artefact = new ArtefactTypeProfileIcon(0, $data);
        if (preg_match("/\\.([^\\.]+)\$/", $values['logo']['name'], $saved)) {
            $artefact->set('oldextension', $saved[1]);
        }
        $artefact->commit();
        $id = $artefact->get('id');
        // Move the file into the correct place.
        $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
        check_dir_exists($directory);
        move_uploaded_file($values['logo']['tmp_name'], $directory . $id);
        // Delete the old logo
        if (!empty($oldinstitution->logo)) {
            $oldlogo = new ArtefactTypeProfileIcon($oldinstitution->logo);
            $oldlogo->delete();
        }
        set_field('institution', 'logo', $id, 'name', $institution);
    }
    if (!empty($values['deletelogo'])) {
        execute_sql("UPDATE {institution} SET logo = NULL WHERE name = ?", array($institution));
    }
    delete_records('institution_locked_profile_field', 'name', $institution);
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
        if ($values[$field]) {
            $profilefield = new StdClass();
            $profilefield->name = $institution;
            $profilefield->profilefield = $field;
            insert_record('institution_locked_profile_field', $profilefield);
        }
    }
    db_commit();
    if ($add) {
        if (!$newinstitution->registerallowed) {
            // If registration is not allowed, then an authinstance will not
            // have been created, and thus cause the institution page to add
            // its own error message on the next page load
            $SESSION->add_ok_msg(get_string('institutionaddedsuccessfully2', 'admin'));
        }
        $nexturl = '/admin/users/institutions.php?i=' . urlencode($institution);
    } else {
        $message = get_string('institutionupdatedsuccessfully', 'admin');
        if (isset($values['theme'])) {
            $changedtheme = $oldinstitution->theme != $values['theme'] && (!empty($oldinstitution->theme) || $values['theme'] != 'sitedefault');
            if ($changedtheme || $values['theme'] == 'custom') {
                $message .= '  ' . get_string('usersseenewthemeonlogin', 'admin');
            }
            $USER->reset_institutions();
        }
        $SESSION->add_ok_msg($message);
        $nexturl = '/admin/users/institutions.php';
    }
    redirect($nexturl);
}
Esempio n. 4
0
function upload_submit(Pieform $form, $values)
{
    global $USER, $filesize;
    safe_require('artefact', 'file');
    try {
        $USER->quota_add($filesize);
    } catch (QuotaException $qe) {
        $form->json_reply(PIEFORM_ERR, array('message' => get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'))));
    }
    // Entry in artefact table
    $data = new stdClass();
    $data->owner = $USER->id;
    $data->parent = ArtefactTypeFolder::get_folder_id(get_string('imagesdir', 'artefact.file'), get_string('imagesdirdesc', 'artefact.file'), null, true, $USER->id);
    $data->title = $values['title'] ? $values['title'] : $values['file']['name'];
    $data->title = ArtefactTypeFileBase::get_new_file_title($data->title, (int) $data->parent, $USER->id);
    // unique title
    $data->note = $values['file']['name'];
    $data->size = $filesize;
    $imageinfo = getimagesize($values['file']['tmp_name']);
    $data->width = $imageinfo[0];
    $data->height = $imageinfo[1];
    $data->filetype = $imageinfo['mime'];
    $data->description = get_string('uploadedprofileicon', 'artefact.file');
    $artefact = new ArtefactTypeProfileIcon(0, $data);
    if (preg_match("/\\.([^\\.]+)\$/", $values['file']['name'], $saved)) {
        $artefact->set('oldextension', $saved[1]);
    }
    $artefact->commit();
    $id = $artefact->get('id');
    // Move the file into the correct place.
    $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
    check_dir_exists($directory);
    move_uploaded_file($values['file']['tmp_name'], $directory . $id);
    $USER->commit();
    $form->json_reply(PIEFORM_OK, get_string('profileiconaddedtoimagesfolder', 'artefact.file', get_string('imagesdir', 'artefact.file')));
}
Esempio n. 5
0
function upload_submit(Pieform $form, $values)
{
    global $USER, $filesize;
    // If there are no icons, we can set this one that is being uploaded to be
    // the default for the user
    $setasdefault = false;
    if (0 == get_field('artefact', 'COUNT(*)', 'artefacttype', 'profileicon', 'owner', $USER->id)) {
        $setasdefault = true;
    }
    try {
        $USER->quota_add($filesize);
    } catch (QuotaException $qe) {
        $form->json_reply(PIEFORM_ERR, array('message' => get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'))));
    }
    // Entry in artefact table
    $data = (object) array('owner' => $USER->id, 'title' => $values['title'] ? $values['title'] : $values['file']['name'], 'note' => $values['file']['name'], 'size' => $filesize);
    $imageinfo = getimagesize($values['file']['tmp_name']);
    $data->width = $imageinfo[0];
    $data->height = $imageinfo[1];
    $data->filetype = $imageinfo['mime'];
    $artefact = new ArtefactTypeProfileIcon(0, $data);
    if (preg_match("/\\.([^\\.]+)\$/", $values['file']['name'], $saved)) {
        $artefact->set('oldextension', $saved[1]);
    }
    $artefact->commit();
    $id = $artefact->get('id');
    // Move the file into the correct place.
    $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
    check_dir_exists($directory);
    move_uploaded_file($values['file']['tmp_name'], $directory . $id);
    if ($setasdefault) {
        $USER->profileicon = $id;
    }
    $USER->commit();
    $form->json_reply(PIEFORM_OK, get_string('uploadedprofileiconsuccessfully', 'artefact.file'));
}
Esempio n. 6
0
function institution_submit(Pieform $form, $values)
{
    global $SESSION, $institution, $add, $instancearray, $USER, $authinstances, $customthemedefaults;
    db_begin();
    // Update the basic institution record...
    $newinstitution = new StdClass();
    if ($add) {
        $institution = $newinstitution->name = strtolower($values['name']);
    } else {
        $oldinstitution = get_record('institution', 'name', $institution);
    }
    $newinstitution->displayname = $values['displayname'];
    $newinstitution->authplugin = empty($values['authplugin']) ? null : $values['authplugin'];
    $newinstitution->showonlineusers = !isset($values['showonlineusers']) ? 2 : $values['showonlineusers'];
    if (get_config('usersuniquebyusername')) {
        // Registering absolutely not allowed when this setting is on, it's a
        // security risk. See the documentation for the usersuniquebyusername
        // setting for more information
        $newinstitution->registerallowed = 0;
    } else {
        $newinstitution->registerallowed = $values['registerallowed'] ? 1 : 0;
        $newinstitution->registerconfirm = $values['registerconfirm'] ? 1 : 0;
    }
    $newinstitution->theme = empty($values['theme']) || $values['theme'] == 'sitedefault' ? null : $values['theme'];
    $newinstitution->dropdownmenu = !empty($values['dropdownmenu']) ? 1 : 0;
    $newinstitution->skins = !empty($values['skins']) ? 1 : 0;
    if ($newinstitution->theme == 'custom') {
        if (!empty($oldinstitution->style)) {
            $styleid = $oldinstitution->style;
            delete_records('style_property', 'style', $styleid);
        } else {
            $record = (object) array('title' => get_string('customstylesforinstitution', 'admin', $newinstitution->displayname));
            $styleid = insert_record('style', $record, 'id', true);
        }
        $properties = array();
        $record = (object) array('style' => $styleid);
        foreach (array_keys($customthemedefaults) as $name) {
            $record->field = $name;
            $record->value = $values[$name];
            insert_record('style_property', $record);
            $properties[$name] = $values[$name];
        }
        // Cache the css
        $smarty = smarty_core();
        $smarty->assign('data', $properties);
        set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);
        $newinstitution->style = $styleid;
    } else {
        $newinstitution->style = null;
    }
    if (get_config('licensemetadata')) {
        $newinstitution->licensemandatory = !empty($values['licensemandatory']) ? 1 : 0;
        $newinstitution->licensedefault = isset($values['licensedefault']) ? $values['licensedefault'] : '';
    }
    if (!empty($values['resetcustom']) && !empty($oldinstitution->style)) {
        $newinstitution->style = null;
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        if (!empty($values['updateuserquotas']) && !empty($values['defaultquota'])) {
            execute_sql("UPDATE {usr} SET quota = ? WHERE id IN (SELECT usr FROM {usr_institution} WHERE institution = ?)", array($values['defaultquota'], $institution));
        }
        $newinstitution->defaultquota = empty($values['defaultquota']) ? get_config_plugin('artefact', 'file', 'defaultquota') : $values['defaultquota'];
    }
    if ($institution != 'mahara') {
        $newinstitution->defaultmembershipperiod = $values['defaultmembershipperiod'] ? intval($values['defaultmembershipperiod']) : null;
        if ($USER->get('admin')) {
            $newinstitution->maxuseraccounts = $values['maxuseraccounts'] ? intval($values['maxuseraccounts']) : null;
            $newinstitution->expiry = db_format_timestamp($values['expiry']);
        }
    }
    $newinstitution->allowinstitutionpublicviews = isset($values['allowinstitutionpublicviews']) && $values['allowinstitutionpublicviews'] ? 1 : 0;
    if (!empty($values['authplugin'])) {
        $allinstances = array_merge($values['authplugin']['instancearray'], $values['authplugin']['deletearray']);
        if (array_diff($allinstances, $instancearray)) {
            throw new ConfigException('Attempt to delete or update another institution\'s auth instance');
        }
        if (array_diff($instancearray, $allinstances)) {
            throw new ConfigException('One of your instances is unaccounted for in this transaction');
        }
        foreach ($values['authplugin']['instancearray'] as $priority => $instanceid) {
            if (in_array($instanceid, $values['authplugin']['deletearray'])) {
                // Should never happen:
                throw new SystemException('Attempt to update AND delete an auth instance');
            }
            $record = new StdClass();
            $record->priority = $priority;
            $record->id = $instanceid;
            update_record('auth_instance', $record, array('id' => $instanceid));
        }
        foreach ($values['authplugin']['deletearray'] as $instanceid) {
            // If this authinstance is the only xmlrpc authinstance that references a host, delete the host record.
            $hostwwwroot = null;
            foreach ($authinstances as $ai) {
                if ($ai->id == $instanceid && $ai->authname == 'xmlrpc') {
                    $hostwwwroot = get_field_sql("SELECT \"value\" FROM {auth_instance_config} WHERE \"instance\" = ? AND field = 'wwwroot'", array($instanceid));
                    if ($hostwwwroot && count_records_select('auth_instance_config', "field = 'wwwroot' AND \"value\" = ?", array($hostwwwroot)) == 1) {
                        // Unfortunately, it's possible that this host record could belong to a different institution,
                        // so specify the institution here.
                        delete_records('host', 'wwwroot', $hostwwwroot, 'institution', $institution);
                        // We really need to fix this, either by removing the institution from the host table, or refusing to allow the
                        // institution to be changed in the host record when another institution's authinstance is still pointing at it.
                    }
                    break;
                }
            }
            delete_records('auth_remote_user', 'authinstance', $instanceid);
            delete_records('auth_instance_config', 'instance', $instanceid);
            delete_records('auth_instance', 'id', $instanceid);
            // Make it no longer be the parent authority to any auth instances
            delete_records('auth_instance_config', 'field', 'parent', 'value', $instanceid);
        }
    }
    if ($add) {
        insert_record('institution', $newinstitution);
        // If registration has been turned on, then we automatically insert an
        // internal authentication authinstance
        // OVERWRITE 4: deletion
        //if ($newinstitution->registerallowed) {
        // END OVERWRITE 4
        $authinstance = (object) array('instancename' => 'internal', 'priority' => 0, 'institution' => $newinstitution->name, 'authname' => 'internal');
        insert_record('auth_instance', $authinstance);
        // OVERWRITE 5: deletion
        //}
        // END OVERWRITE 5
    } else {
        $where = new StdClass();
        $where->name = $institution;
        update_record('institution', $newinstitution, $where);
    }
    if (is_null($newinstitution->style) && !empty($oldinstitution->style)) {
        delete_records('style_property', 'style', $oldinstitution->style);
        delete_records('style', 'id', $oldinstitution->style);
    }
    // Set the logo after updating the institution, because the institution
    // needs to exist before it can own the logo artefact.
    if (!empty($values['logo'])) {
        safe_require('artefact', 'file');
        // Entry in artefact table
        $data = (object) array('institution' => $institution, 'title' => 'logo', 'description' => 'Institution logo', 'note' => $values['logo']['name'], 'size' => $values['logo']['size']);
        $imageinfo = getimagesize($values['logo']['tmp_name']);
        $data->width = $imageinfo[0];
        $data->height = $imageinfo[1];
        $data->filetype = $imageinfo['mime'];
        $artefact = new ArtefactTypeProfileIcon(0, $data);
        if (preg_match("/\\.([^\\.]+)\$/", $values['logo']['name'], $saved)) {
            $artefact->set('oldextension', $saved[1]);
        }
        $artefact->commit();
        $id = $artefact->get('id');
        // Move the file into the correct place.
        $directory = get_config('dataroot') . 'artefact/file/profileicons/originals/' . $id % 256 . '/';
        check_dir_exists($directory);
        move_uploaded_file($values['logo']['tmp_name'], $directory . $id);
        // Delete the old logo
        if (!empty($oldinstitution->logo)) {
            $oldlogo = new ArtefactTypeProfileIcon($oldinstitution->logo);
            $oldlogo->delete();
        }
        set_field('institution', 'logo', $id, 'name', $institution);
    }
    if (!empty($values['deletelogo'])) {
        execute_sql("UPDATE {institution} SET logo = NULL WHERE name = ?", array($institution));
    }
    delete_records('institution_locked_profile_field', 'name', $institution);
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
        if ($values[$field]) {
            $profilefield = new StdClass();
            $profilefield->name = $institution;
            $profilefield->profilefield = $field;
            insert_record('institution_locked_profile_field', $profilefield);
        }
    }
    db_commit();
    if ($add) {
        // OVERWRITE 7: insert
        global $CFG;
        $current_user = $CFG->current_app->getCurrentUser();
        $mhr_usr_institution = $current_user->addMhrInstitutionMembership($newinstitution);
        $CFG->current_app->updateMhrTable('usr_institution', array('admin' => 1), array('usr' => $current_user->getObject()->id));
        // END OVERWRITE 7
        if ($newinstitution->registerallowed) {
            // If registration is not allowed, then an authinstance will not
            // have been created, and thus cause the institution page to add
            // its own error message on the next page load
            $SESSION->add_ok_msg(get_string('institutionaddedsuccessfully2', 'admin'));
        }
        $nexturl = '/admin/users/institutions.php?i=' . urlencode($institution);
    } else {
        $message = get_string('institutionupdatedsuccessfully', 'admin');
        if (isset($values['theme'])) {
            $changedtheme = $oldinstitution->theme != $values['theme'] && (!empty($oldinstitution->theme) || $values['theme'] != 'sitedefault');
            if ($changedtheme || $values['theme'] == 'custom') {
                $message .= '  ' . get_string('usersseenewthemeonlogin', 'admin');
            }
            $USER->reset_institutions();
        }
        $SESSION->add_ok_msg($message);
        $nexturl = '/admin/users/institutions.php';
    }
    redirect($nexturl);
}