Example #1
0
 /**
  * Get the blog entries that will be displayed by this block.
  * (This list will change depending when new blog entries are created, published, etc
  *
  * @param BlockInstance $instance
  * @return array of objects
  */
 public static function get_blog_posts_in_block(BlockInstance $instance)
 {
     $configdata = $instance->get('configdata');
     $limit = isset($configdata['count']) ? (int) $configdata['count'] : 10;
     $mostrecent = array();
     if (!empty($configdata['artefactids'])) {
         $before = 'TRUE';
         if ($instance->get_view()->is_submitted()) {
             if ($submittedtime = $instance->get_view()->get('submittedtime')) {
                 // Don't display posts added after the submitted date.
                 $before = "a.ctime < '{$submittedtime}'";
             }
         }
         $blogids = $configdata['artefactids'];
         $artefactids = implode(', ', array_map('db_quote', $blogids));
         $mostrecent = get_records_sql_array('SELECT a.title, ' . db_format_tsfield('a.ctime', 'ctime') . ', p.title AS parenttitle, a.id, a.parent
                 FROM {artefact} a
                 JOIN {artefact} p ON a.parent = p.id
                 JOIN {artefact_blog_blogpost} ab ON (ab.blogpost = a.id AND ab.published = 1)
                 WHERE a.artefacttype = \'blogpost\'
                 AND a.parent IN ( ' . $artefactids . ' )
                 AND a.owner = (SELECT "owner" from {view} WHERE id = ?)
                 AND ' . $before . '
                 ORDER BY a.ctime DESC, a.id DESC
                 LIMIT ' . $limit, array($instance->get('view')));
         if (!$mostrecent) {
             $mostrecent = array();
         }
     }
     return $mostrecent;
 }
Example #2
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     $configdata = $instance->get('configdata');
     $result = '';
     if (!empty($configdata['artefactids'])) {
         $artefactids = implode(', ', array_map('db_quote', $configdata['artefactids']));
         if (!($mostrecent = get_records_sql_array('SELECT a.title, ' . db_format_tsfield('a.ctime', 'ctime') . ', p.title AS parenttitle, a.id, a.parent
             FROM {artefact} a
             JOIN {artefact} p ON a.parent = p.id
             WHERE a.artefacttype = \'blogpost\'
             AND a.parent IN ( ' . $artefactids . ' ) 
             AND a.owner = (SELECT owner from {view} WHERE id = ?)
             ORDER BY a.ctime DESC
             LIMIT 10', array($instance->get('view'))))) {
             $mostrecent = array();
         }
         // format the dates
         foreach ($mostrecent as &$data) {
             $data->displaydate = format_date($data->ctime);
         }
         $smarty = smarty_core();
         $smarty->assign('mostrecent', $mostrecent);
         $smarty->assign('view', $instance->get('view'));
         $result = $smarty->fetch('blocktype:recentposts:recentposts.tpl');
     }
     return $result;
 }
Example #3
0
 public function assign_smarty_vars()
 {
     $user = $this->get('exporter')->get('user');
     $userid = $user->get('id');
     $updated = get_record_sql('select ' . db_format_tsfield('max(mtime)', 'mtime') . ' from {artefact} a join {artefact_installed_type} t on a.artefacttype = t.name where t.plugin = \'internal\'');
     $this->smarty->assign('artefacttype', 'internal');
     $this->smarty->assign('artefactplugin', 'internal');
     $this->smarty->assign('title', display_name($user, $user));
     $this->smarty->assign('updated', PluginExportLeap::format_rfc3339_date($updated->mtime));
     // If this ID is changed, you'll have to change it in author.tpl too
     $this->smarty->assign('id', 'portfolio:artefactinternal');
     $this->smarty->assign('leaptype', $this->get_leap_type());
     $persondata = array();
     $spacialdata = array();
     usort($this->artefacts, array($this, 'artefact_sort'));
     foreach ($this->artefacts as $a) {
         if (!($data = $this->data_mapping($a))) {
             if ($a->get('artefacttype') == 'introduction') {
                 $this->smarty->assign('contenttype', 'html');
                 $this->smarty->assign('content', clean_html($a->get('title')));
             }
             continue;
         }
         $value = $a->render_self(array());
         $value = $value['html'];
         // TODO fix this when we non-js stuff
         $data = array_merge(array('value' => $value, 'artefacttype' => $a->get('artefacttype'), 'artefactplugin' => 'internal'), $data);
         if (array_key_exists('spacial', $data)) {
             $spacialdata[] = (object) $data;
         } else {
             $label = get_string($a->get('artefacttype'), 'artefact.internal');
             if ($a->get('artefacttype') == 'socialprofile') {
                 $label = $a->get('description');
             }
             $data = array_merge($data, array('label' => $label));
             $persondata[] = (object) $data;
         }
     }
     if ($extras = $this->exporter->get('extrapersondata')) {
         $persondata = array_merge($persondata, $extras);
     }
     $this->smarty->assign('persondata', $persondata);
     $this->smarty->assign('spacialdata', $spacialdata);
     // Grab profile icons and link to them, making sure the default is first
     if ($icons = get_column_sql("SELECT id\n            FROM {artefact}\n            WHERE artefacttype = 'profileicon'\n            AND \"owner\" = ?\n            ORDER BY id = (\n                SELECT profileicon FROM {usr} WHERE id = ?\n            ) DESC, id", array($userid, $userid))) {
         foreach ($icons as $icon) {
             $icon = artefact_instance_from_id($icon);
             $this->add_artefact_link($icon, 'related');
         }
         $this->smarty->assign('links', $this->links);
     }
     if (!($categories = $this->get_categories())) {
         $categories = array();
     }
     $this->smarty->assign('categories', $categories);
 }
Example #4
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     $configdata = $instance->get('configdata');
     $result = '';
     $limit = isset($configdata['count']) ? (int) $configdata['count'] : 10;
     if (!empty($configdata['artefactids'])) {
         $before = 'TRUE';
         if ($instance->get_view()->is_submitted()) {
             if ($submittedtime = $instance->get_view()->get('submittedtime')) {
                 // Don't display posts added after the submitted date.
                 $before = "a.ctime < '{$submittedtime}'";
             }
         }
         $artefactids = implode(', ', array_map('db_quote', $configdata['artefactids']));
         if (!($mostrecent = get_records_sql_array('SELECT a.title, ' . db_format_tsfield('a.ctime', 'ctime') . ', p.title AS parenttitle, a.id, a.parent
             FROM {artefact} a
             JOIN {artefact} p ON a.parent = p.id
             JOIN {artefact_blog_blogpost} ab ON (ab.blogpost = a.id AND ab.published = 1)
             WHERE a.artefacttype = \'blogpost\'
             AND a.parent IN ( ' . $artefactids . ' )
             AND a.owner = (SELECT "owner" from {view} WHERE id = ?)
             AND ' . $before . '
             ORDER BY a.ctime DESC, a.id DESC
             LIMIT ' . $limit, array($instance->get('view'))))) {
             $mostrecent = array();
         }
         // format the dates
         foreach ($mostrecent as &$data) {
             $data->displaydate = format_date($data->ctime);
         }
         $smarty = smarty_core();
         $smarty->assign('mostrecent', $mostrecent);
         $smarty->assign('view', $instance->get('view'));
         $smarty->assign('blockid', $instance->get('id'));
         $smarty->assign('editing', $editing);
         if ($editing) {
             // Get id and title of configued blogs
             $recentpostconfigdata = $instance->get('configdata');
             $wherestm = ' WHERE id IN (' . join(',', array_fill(0, count($recentpostconfigdata['artefactids']), '?')) . ')';
             if (!($selectedblogs = get_records_sql_array('SELECT id, title FROM {artefact}' . $wherestm, $recentpostconfigdata['artefactids']))) {
                 $selectedblogs = array();
             }
             $smarty->assign('blogs', $selectedblogs);
         }
         $result = $smarty->fetch('blocktype:recentposts:recentposts.tpl');
     }
     return $result;
 }
/**
 * Sends notification e-mails to site and institutional admins when:
 *
 *  - An institution is expiring within the institution expiry warning
 *    period, set in site options.
 *
 * The actual prevention of users logging in is handled by the authentication
 * code. This cron job sends e-mails to notify users that these events will
 * happen soon.
 */
function auth_handle_institution_expiries()
{
    // The 'expiry' flag on the usr table
    $sitename = get_config('sitename');
    $wwwroot = get_config('wwwroot');
    $expire = get_config('institutionautosuspend');
    $warn = get_config('institutionexpirynotification');
    $daystoexpire = ceil($warn / 86400) . ' ';
    $daystoexpire .= $daystoexpire == 1 ? get_string('day') : get_string('days');
    // Get site administrators
    $siteadmins = get_records_sql_array('SELECT u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff FROM {usr} u WHERE u.admin = 1', array());
    // Expiry warning messages
    if ($institutions = get_records_sql_array('SELECT i.name, i.displayname FROM {institution} i ' . 'WHERE ' . db_format_tsfield('i.expiry', false) . ' < ? AND suspended != 1 AND expirymailsent != 1', array(time() + $warn))) {
        foreach ($institutions as $institution) {
            $institution_displayname = $institution->displayname;
            // Email site administrators
            foreach ($siteadmins as $user) {
                $user_displayname = display_name($user);
                _email_or_notify($user, get_string('institutionexpirywarning'), get_string('institutionexpirywarningtext_site', 'mahara', $user_displayname, $institution_displayname, $daystoexpire, $sitename, $sitename), get_string('institutionexpirywarninghtml_site', 'mahara', $user_displayname, $institution_displayname, $daystoexpire, $sitename, $sitename));
            }
            // Email institutional administrators
            $institutionaladmins = get_records_sql_array('SELECT u.id, u.username, u.expiry, u.staff, u.admin AS siteadmin, ui.admin AS institutionadmin, u.firstname, u.lastname, u.email ' . 'FROM {usr_institution} ui JOIN {usr} u ON (ui.usr = u.id) WHERE ui.admin = 1', array());
            foreach ($institutionaladmins as $user) {
                $user_displayname = display_name($user);
                _email_or_notify($user, get_string('institutionexpirywarning'), get_string('institutionexpirywarningtext_institution', 'mahara', $user_displayname, $institution_displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename), get_string('institutionexpirywarninghtml_institution', 'mahara', $user_displayname, $institution_displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename));
            }
            set_field('institution', 'expirymailsent', 1, 'name', $institution->name);
        }
    }
    // If we can automatically suspend expired institutions
    $autosuspend = get_config('institutionautosuspend');
    if ($autosuspend) {
        // Actual expired institutions
        if ($institutions = get_records_sql_array('SELECT name FROM {institution} ' . 'WHERE ' . db_format_tsfield('expiry', false) . ' < ?', array(time()))) {
            // Institutions have expired!
            foreach ($institutions as $institution) {
                set_field('institution', 'suspended', 1, 'name', $institution->name);
            }
        }
    }
}
Example #6
0
 /**
  * Take a username and password and try to authenticate the
  * user
  *
  * @param  string $username
  * @param  string $password
  * @return bool
  */
 public function login($username, $password)
 {
     $sql = 'SELECT
                 *,
                 ' . db_format_tsfield('expiry') . ',
                 ' . db_format_tsfield('lastlogin') . ',
                 ' . db_format_tsfield('lastlastlogin') . ',
                 ' . db_format_tsfield('lastaccess') . ',
                 ' . db_format_tsfield('suspendedctime') . ',
                 ' . db_format_tsfield('ctime') . '
             FROM
                 {usr}
             WHERE
                 LOWER(username) = ?';
     if (function_exists('mb_strtolower')) {
         $user = get_record_sql($sql, array(mb_strtolower($username, 'UTF-8')));
     } else {
         $user = get_record_sql($sql, array(strtolower($username)));
     }
     if ($user == false) {
         throw new AuthUnknownUserException("\"{$username}\" is not known");
     }
     if (isset($user->logintries) && $user->logintries >= MAXLOGINTRIES) {
         global $SESSION;
         $SESSION->add_error_msg(get_string('toomanytries', 'auth'));
         return false;
     }
     if (is_site_closed($user->admin)) {
         return false;
     }
     // Authentication instances that have parents do so because they cannot
     // use Mahara's normal login mechanism - for example, XMLRPC. If the
     // user is using one of these authentication instances, we look and try
     // to use the parent.
     //
     // There's no code here that prevents the authinstance being tried if
     // it has no parent, mainly because that's an extra database lookup for
     // the general case, and the authentication will probably just fail
     // anyway. (XMLRPC, for example, leaves implementation of
     // authenticate_user_account to the parent Auth class, which says 'not
     // authorised' by default).
     $instanceid = $user->authinstance;
     if ($parentid = get_field('auth_instance_config', 'value', 'field', 'parent', 'instance', $instanceid)) {
         $instanceid = $parentid;
     }
     // Check for a suspended institution
     // If a user in more than one institution and one of them is suspended
     // make sure their authinstance is not set to the suspended institution
     // otherwise they will not be able to login.
     $authinstance = get_record_sql('
         SELECT i.suspended, i.displayname
         FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name
         WHERE a.id = ?', array($instanceid));
     if ($authinstance->suspended) {
         $sitename = get_config('sitename');
         throw new AccessTotallyDeniedException(get_string('accesstotallydenied_institutionsuspended', 'mahara', $authinstance->displayname, $sitename));
         return false;
     }
     $auth = AuthFactory::create($instanceid);
     // catch the AuthInstanceException that allows authentication plugins to
     // fail but pass onto the next possible plugin
     try {
         if ($auth->authenticate_user_account($user, $password)) {
             $this->authenticate($user, $auth->instanceid);
             return true;
         }
     } catch (AuthInstanceException $e) {
         return false;
     }
     // Display a message to users who are only allowed to login via their
     // external application.
     if ($auth->authloginmsg != '') {
         global $SESSION;
         $SESSION->add_error_msg(clean_html($auth->authloginmsg), false, 'loginbox');
     }
     if (empty($user->logintries)) {
         $user->logintries = 0;
     }
     if ($user->logintries < MAXLOGINTRIES) {
         $record = get_record('usr', 'id', $user->id, null, null, null, null, 'id, logintries');
         $record->logintries = $user->logintries + 1;
         update_record('usr', $record, false);
     }
     return false;
 }
function load_user_institutions($userid)
{
    if (!is_numeric($userid) || $userid < 0) {
        throw new InvalidArgumentException("couldn't load institutions, no user id specified");
    }
    if ($institutions = get_records_sql_assoc('
        SELECT u.institution,' . db_format_tsfield('ctime') . ',' . db_format_tsfield('u.expiry', 'membership_expiry') . ',u.studentid,u.staff,u.admin,i.theme,i.registerallowed
        FROM {usr_institution} u INNER JOIN {institution} i ON u.institution = i.name
        WHERE u.usr = ?', array($userid))) {
        return $institutions;
    }
    return array();
}
Example #8
0
 public function login($email)
 {
     // This will do one of 3 things
     // 1 - If a user has an account, log them in
     // 2 - If a user doesn't have an account, and there is an auth method (which also has weautocreate), create acc and login
     // 3 - If a user doesn't have an account, and there is more than one auth method, show a registration page
     $sql = "SELECT\n                    a.id, i.name AS institutionname\n                FROM\n                    {auth_instance} a\n                JOIN\n                    {institution} i ON a.institution = i.name\n                WHERE\n                    a.authname = 'browserid' AND\n                    i.suspended = 0";
     $authinstances = get_records_sql_array($sql, array());
     if (!$authinstances) {
         throw new ConfigException(get_string('browseridnotenabled', 'auth.browserid'));
     }
     $autocreate = array();
     // Remember the authinstances that are happy to create users
     foreach ($authinstances as $authinstance) {
         $auth = AuthFactory::create($authinstance->id);
         $institutionjoin = '';
         $institutionwhere = '';
         $sqlvalues = array($email);
         if ($authinstance->institutionname != 'mahara') {
             // Make sure that user is in the right institution
             $institutionjoin = 'JOIN {usr_institution} ui ON ui.usr = u.id';
             $institutionwhere = 'AND ui.institution = ?';
             $sqlvalues[] = $authinstance->institutionname;
         }
         $sql = "SELECT\n                        u.*,\n                        " . db_format_tsfield('u.expiry', 'expiry') . ",\n                        " . db_format_tsfield('u.lastlogin', 'lastlogin') . ",\n                        " . db_format_tsfield('u.lastlastlogin', 'lastlastlogin') . ",\n                        " . db_format_tsfield('u.lastaccess', 'lastaccess') . ",\n                        " . db_format_tsfield('u.suspendedctime', 'suspendedctime') . ",\n                        " . db_format_tsfield('u.ctime', 'ctime') . "\n                    FROM\n                        {usr} u\n                    JOIN\n                        {artefact_internal_profile_email} a ON a.owner = u.id\n                    {$institutionjoin}\n                    WHERE\n                        a.verified = 1 AND\n                        a.email = ?\n                    {$institutionwhere}";
         $user = get_record_sql($sql, $sqlvalues);
         if (!$user) {
             if ($auth->weautocreateusers) {
                 if ($authinstance->institutionname == 'mahara') {
                     array_unshift($autocreate, $auth);
                     // Try "No Instititution" first when creating users below
                 } else {
                     $autocreate[] = $auth;
                 }
             }
             continue;
             // skip to the next auth_instance
         }
         if (is_site_closed($user->admin)) {
             return false;
         }
         ensure_user_account_is_active($user);
         $this->authenticate($user, $auth->instanceid);
         return true;
     }
     foreach ($autocreate as $auth) {
         if (!($user = $auth->create_new_user($email))) {
             continue;
         }
         $this->authenticate($user, $auth->instanceid);
         return;
     }
     // Autocreation failed; try registration.
     list($form, $registerconfirm) = auth_generate_registration_form('register', 'browserid', '/register.php');
     if (!$form) {
         throw new AuthUnknownUserException(get_string('emailnotfound', 'auth.browserid', $email));
     }
     if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
         throw new AuthUnknownUserException(get_string('emailalreadytaken', 'auth.internal', $email));
     }
     $form['elements']['email'] = array('type' => 'hidden', 'value' => $email);
     $form['elements']['authtype'] = array('type' => 'hidden', 'value' => 'browserid');
     list($formhtml, $js) = auth_generate_registration_form_js($form, $registerconfirm);
     $registerdescription = get_string('registerwelcome');
     if ($registerterms = get_config('registerterms')) {
         $registerdescription .= ' ' . get_string('registeragreeterms');
     }
     $registerdescription .= ' ' . get_string('registerprivacy');
     $smarty = smarty();
     $smarty->assign('register_form', $formhtml);
     $smarty->assign('registerdescription', $registerdescription);
     if ($registerterms) {
         $smarty->assign('termsandconditions', get_site_page_content('termsandconditions'));
     }
     $smarty->assign('PAGEHEADING', get_string('register', 'auth.browserid'));
     $smarty->assign('INLINEJAVASCRIPT', $js);
     $smarty->display('register.tpl');
     die;
 }
Example #9
0
/**
 * get the views that a user can see belonging
 * to the given users
 *
 * @param array $users users to fetch views owned by
 * @param int $userlooking (optional, defaults to logged in user)
 * @param int $limit grab this many views. (setting this null means get all)
 *
 * @return array Associative array keyed by userid, of arrays of view ids
 */
function get_views($users, $userlooking = null, $limit = 5, $type = null)
{
    $userlooking = optional_userid($userlooking);
    if (is_int($users)) {
        $users = array($users);
    }
    $list = array();
    if (count($users) == 0) {
        return $list;
    }
    $users = array_flip($users);
    $dbnow = db_format_timestamp(time());
    if ($friends = get_records_sql_array('SELECT
            CASE WHEN usr1=? THEN usr2 ELSE usr1 END AS id
        FROM
            {usr_friend} f
        WHERE
            ( usr1=? AND usr2 IN (' . join(',', array_map('db_quote', array_keys($users))) . ') )
            OR
            ( usr2=? AND usr1 IN (' . join(',', array_map('db_quote', array_keys($users))) . ') )
        ', array($userlooking, $userlooking, $userlooking))) {
        foreach ($friends as $user_id) {
            $users[$user_id->id] = 'friend';
        }
    }
    if (is_null($type)) {
        $typesql = "AND v.type != 'profile'";
    } else {
        $typesql = 'AND v.type = ' . db_quote($type);
    }
    $data = array();
    $done = false;
    // public, logged in, or friends' views
    if ($results = get_records_sql_assoc('SELECT
            v.*,
            ' . db_format_tsfield('atime') . ',
            ' . db_format_tsfield('mtime') . ',
            ' . db_format_tsfield('v.ctime', 'ctime') . '
        FROM
            {view} v
            INNER JOIN {view_access} a ON
                v.id=a.view
                AND (
                    accesstype IN (\'public\',\'loggedin\')
            ' . (count(preg_grep('/^friend$/', $users)) > 0 ? 'OR (
                            accesstype = \'friends\'
                            AND v.owner IN (' . join(',', array_map('db_quote', array_keys(preg_grep('/^friend$/', $users)))) . ')
                        )' : '') . '
                )
        WHERE
            v.owner IN (' . join(',', array_map('db_quote', array_keys($users))) . ')
            AND ( v.startdate IS NULL OR v.startdate < ? )
            AND ( v.stopdate IS NULL OR v.stopdate > ? )
        ' . $typesql, array($dbnow, $dbnow))) {
        foreach ($results as $row) {
            $list[$row->owner][$row->id] = $row->id;
        }
        $data = $results;
        // bail if we've filled all users to the limit
        $done = _get_views_trim_list($list, $users, $limit, $data);
    }
    // check individual user access
    if (!$done && ($results = get_records_sql_assoc('SELECT
            v.*,
            ' . db_format_tsfield('atime') . ',
            ' . db_format_tsfield('mtime') . ',
            ' . db_format_tsfield('v.ctime', 'ctime') . '
        FROM
            {view} v
            INNER JOIN {view_access} a ON v.id=a.view AND a.usr=?
        WHERE
            v.owner IN (' . join(',', array_map('db_quote', array_keys($users))) . ')
            AND ( v.startdate IS NULL OR v.startdate < ? )
            AND ( v.stopdate IS NULL OR v.stopdate > ? )
        ' . $typesql, array($userlooking, $dbnow, $dbnow)))) {
        foreach ($results as &$row) {
            $list[$row->owner][$row->id] = $row->id;
        }
        $data = array_merge($data, $results);
        // bail if we've filled all users to the limit
        $done = $done && _get_views_trim_list($list, $users, $limit, $data);
    }
    // check group access
    if (!$done && ($results = get_records_sql_assoc('SELECT
            v.*,
            ' . db_format_tsfield('v.atime', 'atime') . ',
            ' . db_format_tsfield('v.mtime', 'mtime') . ',
            ' . db_format_tsfield('v.ctime', 'ctime') . '
        FROM
            {view} v
            INNER JOIN {view_access} a ON v.id=a.view
            INNER JOIN {group_member} m ON m.group=a.group AND m.member=?
            INNER JOIN {group} g ON (g.id = a.group AND g.deleted = ?)
        WHERE
            v.owner IN (' . join(',', array_map('db_quote', array_keys($users))) . ')
            AND ( v.startdate IS NULL OR v.startdate < ? )
            AND ( v.stopdate IS NULL OR v.stopdate > ? )
        ' . $typesql, array($userlooking, 0, $dbnow, $dbnow)))) {
        foreach ($results as &$row) {
            $list[$row->owner][$row->id] = $row->id;
        }
        $data = array_merge($data, $results);
        // bail if we've filled all users to the limit
        $done = $done && _get_views_trim_list($list, $users, $limit, $data);
    }
    require_once 'view.php';
    View::get_extra_view_info($data, false, false);
    $list = array();
    foreach ($data as $d) {
        $list[$d['owner']][$d['id']] = (object) $d;
    }
    return $list;
}
Example #10
0
 /**
  * This function returns a list of the current cpds activities.
  *
  * @param limit how many activities to display per page
  * @param offset current page to display
  * @return array (grandtotalhours: number, count: integer, data: array)
  *
  */
 public static function get_activities($cpd, $offset = 0, $limit = 10)
 {
     ($results = get_records_sql_array("\n            SELECT a.id, at.artefact AS activity, at.location, at.hours, " . db_format_tsfield('startdate') . ", " . db_format_tsfield('enddate') . ",\n                a.title, a.description, a.parent\n                FROM {artefact} a\n            JOIN {artefact_cpds_activity} at ON at.artefact = a.id\n            WHERE a.artefacttype = 'activity' AND a.parent = ?\n            ORDER BY at.startdate DESC", array($cpd), $offset, $limit)) || ($results = array());
     // format the date and calculate grand total of hours spent
     $grandtotalhours = 0;
     if (!empty($results)) {
         foreach ($results as $result) {
             $grandtotalhours = $grandtotalhours + $result->hours;
             if (!empty($result->startdate)) {
                 $result->startdate = strftime(get_string('strftimedate'), $result->startdate);
                 if (!empty($result->enddate)) {
                     $result->enddate = strftime(get_string('strftimedate'), $result->enddate);
                 }
             }
         }
     }
     $result = array('grandtotalhours' => $grandtotalhours, 'count' => count_records('artefact', 'artefacttype', 'activity', 'parent', $cpd), 'data' => $results, 'offset' => $offset, 'limit' => $limit, 'id' => $cpd);
     return $result;
 }
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */
define('INTERNAL', 1);
define('PUBLIC', 1);
define('SECTION_PLUGINTYPE', 'artefact');
define('SECTION_PLUGINNAME', 'internal');
define('SECTION_PAGE', 'validate');
require dirname(dirname(dirname(__FILE__))) . '/init.php';
require_once 'pieforms/pieform.php';
safe_require('artefact', 'internal');
define('TITLE', get_string('emailactivation', 'artefact.internal'));
$email = param_variable('email');
$key = param_variable('key');
$decline = param_boolean('decline');
$row = get_record('artefact_internal_profile_email', 'email', $email, 'key', $key, null, null, 'owner,artefact,email,verified,' . db_format_tsfield('expiry'));
if ($row) {
    if ($decline) {
        delete_records_select('artefact_internal_profile_email', 'verified=0 AND key=? AND email=?', array($key, $email));
        $SESSION->add_ok_msg(get_string('emailactivationdeclined', 'artefact.internal'));
        redirect(get_config('wwwroot'));
    }
    if ($row->expiry > time()) {
        if ($row->artefact) {
            $artefact = new ArtefactTypeEmail($row->artefact);
        } else {
            $artefact = new ArtefactTypeEmail();
        }
        $artefact->set('owner', $row->owner);
        $artefact->set('title', $row->email);
        $artefact->commit();
Example #12
0
safe_require('interaction', 'forum');
require_once 'group.php';
require_once get_config('docroot') . 'interaction/lib.php';
require_once 'pieforms/pieform.php';
require_once 'antispam.php';
require_once 'embeddedimage.php';
$userid = $USER->get('id');
$topicid = param_integer('id', 0);
$returnto = param_alpha('returnto', 'topic');
if ($topicid == 0) {
    // new topic
    unset($topicid);
    $forumid = param_integer('forum');
} else {
    // edit topic
    $topic = get_record_sql('SELECT p.subject, p.id AS postid, p.body, p.poster, p.topic AS id, ' . db_format_tsfield('p.ctime', 'ctime') . ', t.sticky, t.closed, f.id AS forum
        FROM {interaction_forum_post} p
        INNER JOIN {interaction_forum_topic} t ON (p.topic = t.id AND t.deleted != 1)
        INNER JOIN {interaction_instance} f ON (f.id = t.forum AND f.deleted != 1)
        WHERE p.parent IS NULL
        AND p.topic = ?', array($topicid));
    $forumid = $topic->forum;
    if (!$topic) {
        throw new NotFoundException(get_string('cantfindtopic', 'interaction.forum', $topicid));
    }
}
$forum = get_record_sql('SELECT f.group AS groupid, f.title, g.name AS groupname, g.grouptype
    FROM {interaction_instance} f
    INNER JOIN {group} g ON (g.id = f.group AND g.deleted = 0)
    WHERE f.id = ?
    AND f.deleted != 1', array($forumid));
Example #13
0
/**
 * cron job to process the queue and wake up and finish imports
 */
function import_process_queue()
{
    if (!($ready = get_records_select_array('import_queue', 'ready = ? OR expirytime <  ?', array(1, db_format_timestamp(time())), '', '*,' . db_format_tsfield('expirytime', 'ex')))) {
        return true;
    }
    $now = time();
    $processed = array();
    foreach ($ready as $item) {
        if ($item->ex < $now) {
            log_debug('deleting expired import record', $item);
            $processed[] = $item->id;
            continue;
        }
        $tr = null;
        if (!empty($item->host)) {
            $tr = new MnetImporterTransport($item);
        } else {
            $tr = new LocalImporterTransport($item);
        }
        $importer = PluginImport::create_importer($item->id, $tr, $item);
        try {
            $importer->prepare();
            $importer->process();
            $importer->cleanup();
            $processed[] = $item->id;
        } catch (Exception $e) {
            log_debug('an error occurred on import: ' . $e->getMessage());
            $importer->get('importertransport')->cleanup();
        }
    }
    if (empty($processed)) {
        return true;
    }
    delete_records_select('import_queue', 'id IN ( ' . implode(',', db_array_to_ph($processed)) . ')', $processed);
}
Example #14
0
 public function set_composites()
 {
     $this->composites = get_records_sql_array('SELECT ' . db_format_tsfield('a.mtime', 'mtime') . ', b.* FROM {artefact} a JOIN {' . $this->artefact->get_other_table_name() . '} b
         ON a.id = b.artefact
         WHERE b.artefact = ?', array($this->artefact->get('id')));
 }
Example #15
0
    mobile_api_json_reply(array('fail' => get_string('mobileuploadusernamenotset', 'auth')));
}
$USER = new User();
try {
    $USER->find_by_mobileuploadtoken($token, $username);
} catch (AuthUnknownUserException $e) {
    mobile_api_json_reply(array('fail' => get_string('mobileuploadtokennotfound', 'auth')));
}
// Add in bits of sync data - let's start with notifications
$lastsync = param_integer('lastsync', 0);
$notification_types_sql = '';
$notification_types = explode(",", trim(param_variable('notifications', '')));
if (count($notification_types) > 0) {
    $notification_types_sql = ' a.name IN (' . join(',', array_map('db_quote', $notification_types)) . ')';
}
$activity_arr = get_records_sql_array("\n            SELECT n.id, n.subject, n.message\n            FROM {notification_internal_activity} n\n            INNER JOIN {activity_type} a ON n.type=a.id\n            WHERE {$notification_types_sql}\n                AND n.read=0\n                AND " . db_format_tsfield('ctime', '') . " >= ?\n                AND n.usr= ? ", array($lastsync, $USER->id));
if (count($activity_arr) > 0) {
    $json['activity'] = $activity_arr;
}
// OK - let's add tags
$tags_arr = array();
$tagsort = param_alpha('ts', null) != 'freq' ? 'alpha' : 'freq';
foreach (get_my_tags(null, false, $tagsort) as $tag) {
    $tags_arr[] = array("id" => $tag->tag, "tag" => $tag->tag);
}
if (count($tags_arr) > 0) {
    $json['tags'] = $tags_arr;
}
// OK - let's add journals (and journal posts)
$blogs_arr = array();
$blogs = (object) array('offset' => param_integer('offset', 0), 'limit' => param_integer('limit', 10));
Example #16
0
 public static function instance_config_form($instance)
 {
     global $USER;
     $elements = array();
     $groupid = $instance->get_view()->get('group');
     $configdata = $instance->get('configdata');
     if ($groupid || $instance->get_view()->get('institution')) {
         // This block will show recent forum posts from this group
         $elements['groupid'] = array('type' => 'hidden', 'value' => $groupid);
     } else {
         // Allow the user to choose a group they're in to show posts for
         if (!empty($configdata['groupid'])) {
             $groupid = intval($configdata['groupid']);
             $group = get_record_select('group', 'id = ? AND deleted = 0', array($groupid), '*, ' . db_format_tsfield('ctime'));
         }
         $usergroups = get_records_sql_array("SELECT g.id, g.name\n                FROM {group} g\n                JOIN {group_member} gm ON (gm.group = g.id)\n                WHERE gm.member = ?\n                AND g.deleted = 0\n                ORDER BY g.name", array($USER->get('id')));
         if ($usergroups) {
             $choosablegroups = array();
             foreach ($usergroups as $group) {
                 $choosablegroups[$group->id] = $group->name;
             }
             $elements['groupid'] = array('type' => 'select', 'title' => get_string('group', 'blocktype.recentforumposts'), 'options' => $choosablegroups, 'collapseifoneoption' => false, 'defaultvalue' => $groupid, 'rules' => array('required' => true));
         }
     }
     if (isset($elements['groupid'])) {
         $elements['limit'] = array('type' => 'text', 'title' => get_string('poststoshow', 'blocktype.recentforumposts'), 'description' => get_string('poststoshowdescription', 'blocktype.recentforumposts'), 'defaultvalue' => isset($configdata['limit']) ? intval($configdata['limit']) : 5, 'size' => 3, 'minvalue' => 1, 'maxvalue' => 100);
     } else {
         $elements = array('whoops' => array('type' => 'html', 'value' => '<p class="noartefacts">' . get_string('nogroupstochoosefrom', 'blocktype.recentforumposts') . '</p>'));
     }
     return $elements;
 }
Example #17
0
function group_current_group()
{
    static $group;
    if (isset($group)) {
        return $group;
    }
    if (defined('GROUP')) {
        $group = get_record_select('group', 'id = ? AND deleted = 0', array(GROUP), '*, ' . db_format_tsfield('ctime'));
        if (!$group) {
            throw new GroupNotFoundException(get_string('groupnotfound', 'group', GROUP));
        }
    } else {
        if (defined('GROUPURLID')) {
            $group = get_record_select('group', 'urlid = ? AND deleted = 0', array(GROUPURLID), '*, ' . db_format_tsfield('ctime'));
            if (!$group) {
                throw new GroupNotFoundException(get_string('groupnotfoundname', 'group', GROUPURLID));
            }
            define('GROUP', $group->id);
        } else {
            $group = null;
        }
    }
    return $group;
}
$instsql = $USER->get('admin') ? '' : '
    AND ui.institution IN (' . join(',', array_map('db_quote', array_keys($USER->get('institutions')))) . ')';
$count = get_field_sql('
    SELECT COUNT(*)
    FROM (
        SELECT u.id
        FROM {usr} u
        LEFT OUTER JOIN {usr_institution} ui ON (ui.usr = u.id)
        WHERE ' . ($type == 'expired' ? 'u.expiry < current_timestamp' : 'suspendedcusr IS NOT NULL') . '
        AND deleted = 0 ' . $instsql . '
        GROUP BY u.id
    ) AS a');
$data = get_records_sql_assoc('
    SELECT
        u.id, u.firstname, u.lastname, u.studentid, u.suspendedctime, u.suspendedreason AS reason,
        ua.firstname AS cusrfirstname, ua.lastname AS cusrlastname, ' . db_format_tsfield('u.expiry', 'expiry') . '
    FROM {usr} u
    LEFT JOIN {usr} ua on (ua.id = u.suspendedcusr)
    LEFT OUTER JOIN {usr_institution} ui ON (ui.usr = u.id)
    WHERE ' . ($type == 'expired' ? 'u.expiry < current_timestamp' : 'u.suspendedcusr IS NOT NULL') . '
    AND u.deleted = 0 ' . $instsql . '
    GROUP BY
        u.id, u.firstname, u.lastname, u.studentid, u.suspendedctime, u.suspendedreason,
        ua.firstname, ua.lastname, u.expiry
    ORDER BY ' . ($type == 'expired' ? 'u.expiry' : 'u.suspendedctime') . ', u.id
    LIMIT ?
    OFFSET ?', array($limit, $offset));
if (!$data) {
    $data = array();
} else {
    $institutions = get_records_sql_array('
Example #19
0
 public static function send_digest()
 {
     $users = array();
     $sitename = get_config('sitename');
     $types = get_records_assoc('activity_type', 'admin', 0, 'plugintype,pluginname,name', 'id,name,plugintype,pluginname');
     foreach ($types as &$type) {
         if (!empty($type->plugintype)) {
             $type->section = "{$type->plugintype}.{$type->pluginname}";
         } else {
             $type->section = "activity";
         }
     }
     $sql = 'SELECT q.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff,
                 p.value AS lang, q.*,' . db_format_tsfield('ctime') . '
             FROM {usr} u 
                 JOIN {notification_emaildigest_queue} q
                     ON q.usr = u.id
                 LEFT OUTER JOIN {usr_account_preference} p ON (p.usr = u.id AND p.field = \'lang\')
             ORDER BY usr,type,q.ctime';
     if ($tosend = get_records_sql_array($sql, array())) {
         foreach ($tosend as $queue) {
             if (!isset($users[$queue->usr])) {
                 $users[$queue->usr] = new StdClass();
                 $users[$queue->usr]->user = new StdClass();
                 $users[$queue->usr]->user->username = $queue->username;
                 $users[$queue->usr]->user->firstname = $queue->firstname;
                 $users[$queue->usr]->user->lastname = $queue->lastname;
                 $users[$queue->usr]->user->preferredname = $queue->preferredname;
                 $users[$queue->usr]->user->email = $queue->email;
                 $users[$queue->usr]->user->admin = $queue->admin;
                 $users[$queue->usr]->user->staff = $queue->staff;
                 $users[$queue->usr]->user->id = $queue->usr;
                 $users[$queue->usr]->user->lang = empty($queue->lang) || $queue->lang == 'default' ? get_config('lang') : $queue->lang;
                 $users[$queue->usr]->entries = array();
             }
             $queue->nicetype = get_string_from_language($users[$queue->usr]->user->lang, 'type' . $types[$queue->type]->name, $types[$queue->type]->section);
             $users[$queue->usr]->entries[$queue->id] = $queue;
         }
     }
     foreach ($users as $user) {
         $lang = $user->user->lang;
         $subject = get_string_from_language($lang, 'emailsubject', 'notification.emaildigest', $sitename);
         $body = get_string_from_language($lang, 'emailbodynoreply', 'notification.emaildigest', $sitename);
         foreach ($user->entries as $entry) {
             $body .= get_string_from_language($lang, 'type', 'activity') . ': ' . $entry->nicetype . ' ' . get_string_from_language($lang, 'attime', 'activity') . ' ' . format_date($entry->ctime) . "\n";
             if (!empty($entry->subject)) {
                 $body .= get_string_from_language($lang, 'subject') . $entry->subject . "\n";
             }
             if (!empty($entry->message)) {
                 $body .= "\n" . $entry->message;
             }
             if (!empty($entry->url)) {
                 $body .= "\n" . $entry->url;
             }
             $body .= "\n\n";
         }
         $prefurl = get_config('wwwroot') . 'account/activity/preferences/';
         $body .= "\n\n" . get_string_from_language($lang, 'emailbodyending', 'notification.emaildigest', $prefurl);
         try {
             email_user($user->user, null, $subject, $body);
             //only delete them if the email succeeded!
             $in = db_array_to_ph($user->entries);
             delete_records_select('notification_emaildigest_queue', 'id IN (' . implode(', ', $in) . ')', array_keys($user->entries));
         } catch (Exception $e) {
             // @todo
         }
     }
 }
Example #20
0
function get_postedits($postid)
{
    ($postedits = get_records_sql_array('SELECT ' . db_format_tsfield('e.ctime', 'edittime') . ', e.user AS editor, m2.user AS editormoderator
        FROM {interaction_forum_edit} e
        LEFT JOIN {interaction_forum_post} p ON p.id = e.post
        LEFT JOIN {interaction_forum_topic} t ON t.id = p.topic
        LEFT JOIN (
            SELECT m.forum, m.user
            FROM {interaction_forum_moderator} m
            INNER JOIN {usr} u ON (m.user = u.id AND u.deleted = 0)
        ) m2 ON (m2.forum = t.forum AND m2.user = e.user)
        WHERE e.post = ?
        ORDER BY e.ctime', array($postid))) || ($postedits = array());
    $editrecs = array();
    foreach ($postedits as $postedit) {
        $postedit->edittime = relative_date(get_string('strftimerecentfullrelative', 'interaction.forum'), get_string('strftimerecentfull'), $postedit->edittime);
        $editrecs[] = array('editormoderator' => $postedit->editormoderator, 'editor' => $postedit->editor, 'edittime' => $postedit->edittime);
    }
    return $editrecs;
}
Example #21
0
 /**
  * Get all views for a (user,group,institution), grouping views
  * into their collections.  Empty collections not returned.
  *
  * @param mixed   $owner integer userid or array of userids
  * @param mixed   $group integer groupid or array of groupids
  * @param mixed   $institution string institution name or array of institution names
  * @param string  $matchconfig record all matches with given config hash (see set_access)
  * @param boolean $includeprofile include profile view
  * @param integer $submittedgroup return only views & collections submitted to this group
  * @param $string $sort Order to sort by (defaults to 'c.name, v.title')
  *
  * @return array, array
  */
 function get_views_and_collections($owner = null, $group = null, $institution = null, $matchconfig = null, $includeprofile = true, $submittedgroup = null, $sort = null)
 {
     $excludelocked = $group && group_user_access($group) != 'admin';
     // Anonymous public viewing of a group with 'Allow submissions' checked needs to avoid including the dummy root profile page.
     if ($owner == '0') {
         $includeprofile = false;
     }
     $sql = "\n            SELECT v.id, v.type, v.title, v.accessconf, v.ownerformat, v.startdate, v.stopdate, v.template,\n                v.owner, v.group, v.institution, v.urlid, v.submittedgroup, v.submittedhost, " . db_format_tsfield('v.submittedtime', 'submittedtime') . ", v.submittedstatus,\n                c.id AS cid, c.name AS cname,\n                c.submittedgroup AS csubmitgroup, c.submittedhost AS csubmithost, " . db_format_tsfield('c.submittedtime', 'csubmittime') . ", c.submittedstatus AS csubmitstatus\n            FROM {view} v\n                LEFT JOIN {collection_view} cv ON v.id = cv.view\n                LEFT JOIN {collection} c ON cv.collection = c.id\n            WHERE  v.type IN ('portfolio'";
     $sql .= $includeprofile ? ", 'profile') " : ') ';
     $sql .= $excludelocked ? 'AND v.locked != 1 ' : '';
     if (is_null($owner) && is_null($group) && is_null($institution)) {
         $values = array();
     } else {
         list($ownersql, $values) = self::multiple_owner_sql((object) array('owner' => $owner, 'group' => $group, 'institution' => $institution));
         $sql .= "AND v.{$ownersql} ";
     }
     if ($submittedgroup) {
         $sql .= 'AND v.submittedgroup = ? ';
         $values[] = (int) $submittedgroup;
     }
     if ($sort == null) {
         $sql .= 'ORDER BY c.name, v.title';
     } else {
         $sql .= "ORDER BY {$sort}";
     }
     $records = get_records_sql_assoc($sql, $values);
     $collections = array();
     $views = array();
     if (!$records) {
         return array($collections, $views);
     }
     self::get_extra_view_info($records, false, false);
     foreach ($records as &$r) {
         $vid = $r['id'];
         $cid = $r['cid'];
         $v = array('id' => $vid, 'type' => $r['type'], 'name' => $r['displaytitle'], 'url' => $r['fullurl'], 'startdate' => $r['startdate'], 'stopdate' => $r['stopdate'], 'template' => $r['template'], 'owner' => $r['owner'], 'submittedgroup' => $r['submittedgroup'], 'submittedhost' => $r['submittedhost'], 'submittedtime' => $r['submittedtime'], 'submittedstatus' => $r['submittedstatus']);
         if (isset($r['user'])) {
             $v['ownername'] = display_name($r['user']);
             $v['ownerurl'] = profile_url($r['user']);
         }
         // If filtering by submitted views, and the view is submitted, but the collection isn't,
         // then ignore the collection and return the view by itself.
         if ($cid && (!$submittedgroup || $r['csubmitgroup'] == $r['submittedgroup'])) {
             if (!isset($collections[$cid])) {
                 $collections[$cid] = array('id' => $cid, 'name' => $r['cname'], 'url' => $r['fullurl'], 'owner' => $r['owner'], 'group' => $r['group'], 'institution' => $r['institution'], 'submittedgroup' => $r['csubmitgroup'], 'submittedhost' => $r['csubmithost'], 'submittedtime' => $r['csubmittime'], 'submittedstatus' => $r['csubmitstatus'], 'template' => $r['template'], 'views' => array());
                 if (isset($r['user'])) {
                     $collections[$cid]['ownername'] = $v['ownername'];
                     $collections[$cid]['ownerurl'] = $v['ownerurl'];
                 }
                 if ($matchconfig && $matchconfig == $r['accessconf']) {
                     $collections[$cid]['match'] = true;
                 }
             }
             $collections[$cid]['views'][$vid] = $v;
         } else {
             $views[$vid] = $v;
             if ($matchconfig && $matchconfig == $r['accessconf']) {
                 $views[$vid]['match'] = true;
             }
         }
     }
     return array($collections, $views);
 }
Example #22
0
/**
 * Take a username and password and try to authenticate the
 * user
 *
 * Copied and modified from core LiveUser->login()
 *
 * @param  string $username
 * @param  string $password
 * @return bool
 */
function login_test_all_user_authinstance($username, $password)
{
    global $USER;
    // do the normal user lookup
    $sql = 'SELECT
                *,
                ' . db_format_tsfield('expiry') . ',
                ' . db_format_tsfield('lastlogin') . ',
                ' . db_format_tsfield('lastlastlogin') . ',
                ' . db_format_tsfield('lastaccess') . ',
                ' . db_format_tsfield('suspendedctime') . ',
                ' . db_format_tsfield('ctime') . '
            FROM
                {usr}
            WHERE
                LOWER(username) = ?';
    $user = get_record_sql($sql, array(strtolower($username)));
    // throw out unknown users
    if ($user == false) {
        throw new AuthUnknownUserException("\"{$username}\" is not known");
    }
    // stop right here if the site is closed for any reason
    $siteclosedforupgrade = get_config('siteclosed');
    if ($siteclosedforupgrade && get_config('disablelogin')) {
        global $SESSION;
        $SESSION->add_error_msg(get_string('siteclosedlogindisabled', 'mahara', get_config('wwwroot') . 'admin/upgrade.php'), false);
        return false;
    }
    if ($siteclosedforupgrade || get_config('siteclosedbyadmin')) {
        global $SESSION;
        $SESSION->add_error_msg(get_string('siteclosed'));
        return false;
    }
    // Build up a list of authinstance that can be tried for this user - typically
    // internal, or ldap - definitely NOT none, saml, or xmlrpc
    $instances = array();
    // all other candidtate auth_instances
    $sql = 'SELECT ai.* from {auth_instance} ai INNER JOIN {auth_remote_user} aru
                ON ai.id = aru.authinstance
                WHERE ai.authname NOT IN(\'saml\', \'xmlrpc\', \'none\') AND aru.localusr = ?';
    $authinstances = get_records_sql_array($sql, array($user->id));
    foreach ($authinstances as $authinstance) {
        $instances[] = $authinstance->id;
    }
    // determine the internal authinstance ID associated with the base 'mahara'
    // 'no institution' - use this is a default fallback login attempt
    $authinstance = get_record('auth_instance', 'institution', 'mahara', 'authname', 'internal');
    $instances[] = $authinstance->id;
    // test each auth_instance candidate associated with this user
    foreach ($instances as $authinstanceid) {
        $auth = AuthFactory::create($authinstanceid);
        // catch the AuthInstanceException that allows authentication plugins to
        // fail but pass onto the next possible plugin
        try {
            if ($auth->authenticate_user_account($user, $password)) {
                $USER->reanimate($user->id, $auth->instanceid);
                // Check for a suspended institution - should never be for 'mahara'
                $authinstance = get_record_sql('
                    SELECT i.suspended, i.displayname
                    FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name
                    WHERE a.id = ?', array($authinstanceid));
                if ($authinstance->suspended) {
                    continue;
                }
                // we havea winner
                return true;
            }
        } catch (AuthInstanceException $e) {
            // auth fail - try the next one
            continue;
        }
    }
    // all fail
    return false;
}
/**
 * Returns the search results for the export queue
 *
 * @param array  $search            The parameters we want to search against
 * @param int    $offset            What result to start showing paginated results from
 * @param int    $limit             How many results to show
 *
 * @return array  A data structure containing results (see top of file).
 */
function build_admin_export_queue_results($search, $offset, $limit)
{
    global $USER;
    $wantedparams = array('query', 'sortby', 'sortdir', 'institution');
    $params = array();
    foreach ($search as $k => $v) {
        if (!in_array($k, $wantedparams)) {
            continue;
        }
        if (!empty($v)) {
            $params[] = $k . '=' . $v;
        }
    }
    $searchurl = get_config('wwwroot') . 'admin/users/exportqueue.php?' . join('&', $params) . '&limit=' . $limit;
    // Use get_admin_user_search_results() as it hooks into the same
    // funky stuff the user search box query does on user/search.php page.
    $search->exportqueue = true;
    $results = get_admin_user_search_results($search, $offset, $limit);
    // Now that we have the users we need to match them up with their export_queue data
    if (!empty($results['count'])) {
        foreach ($results['data'] as $key => $data) {
            $used = array();
            $exportdata = get_records_sql_assoc('
                SELECT *, ' . db_format_tsfield('e.starttime', 'started') . ',
                          ' . db_format_tsfield('e.ctime', 'added') . '
                FROM {export_queue} e
                JOIN {export_queue_items} ei
                ON e.id = ei.exportqueueid
                AND e.usr = ?
                AND e.id = ?
                GROUP BY e.id, ei.id
                ORDER BY collection, view', array($data['id'], $data['eid']));
            $exportdataall = false;
            if (empty($exportdata)) {
                // Try checking if it an 'all' export
                $exportdataall = get_record_sql("SELECT *, " . db_format_tsfield('starttime', 'started') . ", " . db_format_tsfield('ctime', 'added') . "\n                                                 FROM {export_queue} WHERE id = ? AND type = ?", array($data['eid'], 'all'));
            }
            if (empty($exportdataall) && empty($exportdata)) {
                // we have a problem with this row so will mark as failed
                $results['data'][$key]['status'] = get_string('exportfailed', 'admin', format_date($data['status']));
                $results['data'][$key]['statustype'] = $statustype = 'failed';
                continue;
            }
            // To get the main content title/url/type/id we look at the first row of the exportdata.
            if ($exportdataall) {
                $firstitem = $exportdataall;
                $contentdata = new stdClass();
                $contentdata->title = get_string('allmydata', 'export');
                $contentdata->type = 'all';
                $results['data'][$key]['contentdata'] = $contentdata;
            } else {
                $firstitem = reset($exportdata);
                if (!empty($firstitem->type)) {
                    $contentdata = new stdClass();
                    $contentdata->title = get_string('exporting' . $firstitem->type, 'export');
                    $contentdata->type = $firstitem->type;
                    $results['data'][$key]['contentdata'] = $contentdata;
                } else {
                    $results['data'][$key]['contentdata'] = get_export_contentdata($firstitem);
                }
            }
            // To get the status we check if the starttime is set
            if (empty($firstitem->starttime)) {
                $status = get_string('exportpending', 'admin', format_date($firstitem->added));
                $statustype = 'pending';
            } else {
                if (!empty($firstitem->starttime)) {
                    $status = get_string('exportfailed', 'admin', format_date($firstitem->started));
                    $statustype = 'failed';
                }
            }
            $results['data'][$key]['status'] = $status;
            $results['data'][$key]['statustype'] = $statustype;
            // Add on the raw exportdata allowing us to show the titles of all pages / artefacts
            // @todo allow all the titles to be displayed in an expanding box/area
            $results['data'][$key]['exportdata'] = $exportdata;
        }
    }
    $pagination = build_pagination(array('id' => 'admin_exportqueue_pagination', 'class' => 'center', 'url' => $searchurl, 'count' => $results['count'], 'setlimit' => true, 'limit' => $limit, 'jumplinks' => 8, 'numbersincludeprevnext' => 2, 'offset' => $offset, 'datatable' => 'searchresults', 'searchresultsheading' => 'resultsheading', 'jsonscript' => 'admin/users/exportqueue.json.php'));
    $cols = array('icon' => array('template' => 'admin/users/searchiconcolumn.tpl', 'class' => 'center', 'accessible' => get_string('profileicon')), 'firstname' => array('name' => get_string('firstname'), 'sort' => true, 'template' => 'admin/users/searchfirstnamecolumn.tpl'), 'lastname' => array('name' => get_string('lastname'), 'sort' => true, 'template' => 'admin/users/searchlastnamecolumn.tpl'), 'preferredname' => array('name' => get_string('displayname'), 'sort' => true), 'username' => array('name' => get_string('username'), 'sort' => true, 'template' => 'admin/users/searchusernamecolumn.tpl'), 'contentname' => array('name' => get_string('exportcontentname', 'admin'), 'sort' => false, 'template' => 'admin/users/searchexportcontentcolumn.tpl'), 'status' => array('name' => get_string('status'), 'sort' => true, 'template' => 'admin/users/searchexportstatuscolumn.tpl'), 'exportselect' => array('headhtml' => get_string('Export', 'export') . '<br /><a href="" id="selectallexport">' . get_string('All') . '</a>&nbsp;<a href="" id="selectnoneexport">' . get_string('none') . '</a>', 'template' => 'admin/users/searchselectcolumnexport.tpl', 'class' => 'center nojs-hidden-table-cell', 'accessible' => get_string('bulkselect')), 'deleteselect' => array('headhtml' => get_string('delete') . '<br /><a href="" id="selectalldelete">' . get_string('All') . '</a>&nbsp;<a href="" id="selectnonedelete">' . get_string('none') . '</a>', 'template' => 'admin/users/searchselectcolumnexportdelete.tpl', 'class' => 'center nojs-hidden-table-cell', 'accessible' => get_string('bulkselect')));
    $smarty = smarty_core();
    $smarty->assign_by_ref('results', $results);
    $smarty->assign('USER', $USER);
    $smarty->assign('limit', $limit);
    $smarty->assign('limitoptions', array(10, 50, 100, 200, 500));
    $smarty->assign('cols', $cols);
    $smarty->assign('ncols', count($cols));
    $html = $smarty->fetch('searchresulttable.tpl');
    if ($html != '') {
        $html .= $smarty->fetch('searchresulttablebuttons.tpl');
    }
    return array($html, $cols, $pagination, array('url' => $searchurl, 'sortby' => $search->sortby, 'sortdir' => $search->sortdir));
}
Example #24
0
 public static function fetch_posts(BlockInstance $instance)
 {
     global $USER;
     $owner = $instance->get_view()->get('owner');
     $userid = !empty($USER) ? $USER->get('id') : 0;
     // We select u.id because display_name uses the 'id' field to get
     // information (we really should be passing objects with just user
     // information to it, for safety). We select it again as 'userid' to
     // avoid confusion in the templates
     $sql = '
         SELECT bwp.id AS postid, bwp.instance, bwp.from, bwp.replyto, bwp.private, bwp.postdate, bwp.text,' . db_format_tsfield('postdate') . ',
             u.id, u.id AS userid, u.username, u.firstname, u.lastname, u.preferredname, u.staff, u.admin
             FROM {blocktype_wall_post} bwp 
             JOIN {usr} u ON bwp.from = u.id
             WHERE bwp.instance = ? AND u.deleted = 0
     ' . ($owner != $userid ? ' 
             AND (bwp.private = 0 OR bwp.from = ' . db_quote($userid) . ') ' : '') . '
             ORDER BY bwp.postdate DESC
     ';
     $params = array($instance->get('id'));
     if ($records = get_records_sql_array($sql, $params, 0, 10)) {
         return array_map(create_function('$item', '$item->displayname = display_name($item);
                 $item->deletable = PluginBlocktypeWall::can_delete_wallpost($item->from, ' . intval($owner) . ');
                 return $item;'), $records);
     }
     return false;
 }
                }
            }
        }
    } else {
        // $checked contains bad values
        $SESSION->add_error_msg(get_string('topicupdatefailed', 'interaction.forum'));
    }
    redirect('/interaction/forum/view.php?id=' . $forumid . '&offset=' . $offset);
}
if ($membership) {
    $forum->subscribe = pieform(array('name' => 'subscribe_forum', 'renderer' => 'div', 'plugintype' => 'interaction', 'pluginname' => 'forum', 'autofocus' => false, 'elements' => array('submit' => array('type' => 'submit', 'class' => 'btn-subscribe', 'value' => $forum->subscribed ? get_string('unsubscribefromforum', 'interaction.forum') : get_string('subscribetoforum', 'interaction.forum'), 'help' => true), 'forum' => array('type' => 'hidden', 'value' => $forumid), 'redirect' => array('type' => 'hidden', 'value' => 'view'), 'offset' => array('type' => 'hidden', 'value' => $offset), 'type' => array('type' => 'hidden', 'value' => $forum->subscribed ? 'unsubscribe' : 'subscribe'))));
}
// gets the info about topics
// the last post is found by taking the max id of the posts in a topic with the max post time
// taking the max id is needed because multiple posts can have the same post time
$sql = 'SELECT t.id, p1.subject, p1.body, p1.poster, p1.deleted, m.user AS moderator, COUNT(p2.id) AS postcount, t.closed, s.topic AS subscribed, p4.id AS lastpost, ' . db_format_tsfield('p4.ctime', 'lastposttime') . ', p4.poster AS lastposter, m2.user AS lastpostermoderator
    FROM {interaction_forum_topic} t
    INNER JOIN {interaction_forum_post} p1 ON (p1.topic = t.id AND p1.parent IS NULL)
    LEFT JOIN (
        SELECT m.forum, m.user
        FROM {interaction_forum_moderator} m
        INNER JOIN {usr} u ON (m.user = u.id AND u.deleted = 0)
    ) m ON (m.forum = t.forum AND p1.poster = m.user)
    INNER JOIN {interaction_forum_post} p2 ON (p2.topic = t.id AND p2.deleted != 1)
    LEFT JOIN {interaction_forum_subscription_topic} s ON (s.topic = t.id AND s."user" = ?)
    INNER JOIN (
        SELECT MAX(p2.id) AS post, t.id AS topic
        FROM {interaction_forum_topic} t
        INNER JOIN (
            SELECT MAX(p.ctime) AS ctime, t.id AS topic
            FROM {interaction_forum_topic} t
Example #26
0
 public function __construct($id = 0, $data = null)
 {
     if (empty($id)) {
         $data['title'] = get_string('personalinformation', 'artefact.resume');
     }
     parent::__construct($id, $data);
     $this->composites = ArtefactTypePersonalinformation::get_composite_fields();
     if (!empty($id)) {
         $this->composites = (array) get_record('artefact_resume_personal_information', 'artefact', $id, null, null, null, null, '*, ' . db_format_tsfield('dateofbirth'));
     }
 }
Example #27
0
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */
define('INTERNAL', 1);
define('MENUITEM', 'groups/forums');
define('SECTION_PLUGINTYPE', 'interaction');
define('SECTION_PLUGINNAME', 'forum');
define('SECTION_PAGE', 'deletepost');
require dirname(dirname(dirname(__FILE__))) . '/init.php';
safe_require('interaction', 'forum');
require_once 'group.php';
require_once get_config('docroot') . 'interaction/lib.php';
require_once 'pieforms/pieform.php';
$postid = param_integer('id');
$post = get_record_sql('SELECT p.subject, p.body, p.topic, p.parent, p.poster, ' . db_format_tsfield('p.ctime', 'ctime') . ', m.user AS moderator, t.forum, p2.subject AS topicsubject, f.group, f.title AS forumtitle, g.name AS groupname, COUNT(p3.id)
    FROM {interaction_forum_post} p
    INNER JOIN {interaction_forum_topic} t ON (p.topic = t.id AND t.deleted != 1)
    INNER JOIN {interaction_forum_post} p2 ON (p2.topic = t.id AND p2.parent IS NULL)
    INNER JOIN {interaction_instance} f ON (t.forum = f.id AND f.deleted != 1)
    INNER JOIN {group} g ON (g.id = f.group AND g.deleted = ?)
    LEFT JOIN (
        SELECT m.forum, m.user
        FROM {interaction_forum_moderator} m
        INNER JOIN {usr} u ON (m.user = u.id AND u.deleted = 0)
    ) m ON (m.forum = f.id AND m.user = p.poster)
    INNER JOIN {interaction_forum_post} p3 ON (p.poster = p3.poster AND p3.deleted != 1)
    INNER JOIN {interaction_forum_topic} t2 ON (t2.deleted != 1 AND p3.topic = t2.id)
    INNER JOIN {interaction_instance} f2 ON (t2.forum = f2.id AND f2.deleted != 1 AND f2.group = f.group)
    WHERE p.id = ?
    AND p.deleted != 1
Example #28
0
function load_user_institutions($userid)
{
    if (!is_numeric($userid) || $userid < 0) {
        throw new InvalidArgumentException("couldn't load institutions, no user id specified");
    }
    if ($institutions = get_records_sql_assoc('
        SELECT u.institution,' . db_format_tsfield('ctime') . ',' . db_format_tsfield('u.expiry', 'membership_expiry') . ',u.studentid,u.staff,u.admin,i.displayname,i.theme,i.registerallowed, i.showonlineusers,i.allowinstitutionpublicviews, i.logo, i.style, i.licensemandatory, i.licensedefault, i.dropdownmenu, i.skins, i.suspended
        FROM {usr_institution} u INNER JOIN {institution} i ON u.institution = i.name
        WHERE u.usr = ? ORDER BY i.priority DESC', array($userid))) {
        return $institutions;
    }
    return array();
}
Example #29
0
            $now = $fake ? time() - ($realstart - $start) : time();
        }
    }
}
// and now the core ones (much simpler)
$now = $fake ? time() - ($realstart - $start) : time();
$jobs = get_records_select_array('cron', 'nextrun < ? OR nextrun IS NULL', array(db_format_timestamp($now)), '', 'id,callfunction,minute,hour,day,month,dayofweek,' . db_format_tsfield('nextrun'));
if ($jobs) {
    foreach ($jobs as $job) {
        if (!cron_lock($job, $start)) {
            continue;
        }
        // If some other cron instance ran the job while we were messing around,
        // skip it.
        $nextrun = get_field_sql('
            SELECT ' . db_format_tsfield('nextrun') . '
            FROM {cron}
            WHERE id = ?', array($job->id));
        if ($nextrun != $job->nextrun) {
            log_info("Too late to run core {$job->callfunction}; skipping.");
            cron_free($job, $start);
            continue;
        }
        log_info("Running core cron " . $job->callfunction);
        $function = $job->callfunction;
        try {
            $function();
        } catch (Exception $e) {
            log_message($e->getMessage(), LOG_LEVEL_WARN, true, true, $e->getFile(), $e->getLine(), $e->getTrace());
            $output = $e instanceof MaharaException ? $e->render_exception() : $e->getMessage();
            echo "{$output}\n";
Example #30
0
 public static function refresh_feeds()
 {
     if (!($feeds = get_records_select_array('blocktype_externalfeed_data', 'lastupdate < ?', array(db_format_timestamp(strtotime('-30 minutes'))), '', 'id,url,' . db_format_tsfield('lastupdate', 'tslastupdate')))) {
         return;
     }
     $yesterday = time() - 60 * 60 * 24;
     foreach ($feeds as $feed) {
         // Hack to stop the updating of dead feeds from delaying other
         // more important stuff that runs on cron.
         if (defined('CRON') && $feed->tslastupdate < $yesterday) {
             // We've been trying for 24 hours already, so waste less
             // time on this one and just try it once a day
             if (mt_rand(0, 24) != 0) {
                 continue;
             }
         }
         try {
             $data = self::parse_feed($feed->url);
             $data->id = $feed->id;
             $data->lastupdate = db_format_timestamp(time());
             $data->content = serialize($data->content);
             $data->image = serialize($data->image);
             update_record('blocktype_externalfeed_data', $data);
         } catch (XML_Feed_Parser_Exception $e) {
             // The feed must have changed in such a way as to become
             // invalid since it was added. We ignore this case in the hope
             // the feed will become valid some time later
         }
     }
 }