public static function getRecordDataById($type, $id)
 {
     $sql = 'SELECT c.id, c.name, c.ctime, c.description, cv.view AS viewid, c.owner
     FROM {collectio}n c
     LEFT OUTER JOIN {collection_view} cv ON cv.collection = c.id
     WHERE id = ? ORDER BY cv.displayorder asc LIMIT 1;';
     $record = get_record_sql($sql, array($id));
     if (!$record) {
         return false;
     }
     $record->name = str_replace(array("\r\n", "\n", "\r"), ' ', strip_tags($record->name));
     $record->description = str_replace(array("\r\n", "\n", "\r"), ' ', strip_tags($record->description));
     //  Created by
     if (intval($record->owner) > 0) {
         $record->createdby = get_record('usr', 'id', $record->owner);
         $record->createdbyname = display_name($record->createdby);
     }
     // Get all views included in that collection
     $sql = 'SELECT v.id, v.title
     FROM {view} v
     LEFT OUTER JOIN {collection_view} cv ON cv.view = v.id
     WHERE cv.collection = ?';
     $views = recordset_to_array(get_recordset_sql($sql, array($id)));
     if ($views) {
         $record_views = array();
         foreach ($views as $view) {
             if (isset($view->id)) {
                 $record_views[$view->id] = $view->title;
             }
         }
         $record->views = $record_views;
     }
     return $record;
 }
Example #2
0
function folio_control_page_edit_move($page)
{
    // Find the security information for the page.
    global $CFG;
    $url = url;
    $page_ident = intval($page->page_ident);
    $parentpage_ident = intval($page->parentpage_ident);
    // Check to see if we're on the homepage.
    if (folio_page_is_homepage($page)) {
        // Don't allow moving a homepage.
        $run_result = '<input type="hidden" name="parentpage_ident" value="' . $page->parentpage_ident . '" />';
    } elseif (!isloggedin()) {
        // Have to be logged in to move a page.
        // mark control as disabled & don't bother loading all of the pages.
        $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" DISABLED>";
        // Get parentpage title
        $pages = recordset_to_array(get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' . 'WHERE newest = 1 and user_ident = ' . $page->user_ident . ' AND page_ident = ' . $page->parentpage_ident));
        // build
        if ($pages) {
            // Iterate
            foreach ($pages as $potentialpage) {
                // Selected
                $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " SELECTED=true>" . $potentialpage->title . "\n";
            }
            $run_result .= "</SELECT><br/>\n" . "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n";
        } else {
            // No pages.  Show control set to homepage & disabled.
            $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" disabled=TRUE>" . '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage' . "</SELECT><br/>\n" . "<input type='hidden' name='parentpage_ident' value='{$potentialpage->page_ident}' />\n";
        }
        $run_result = templates_draw(array('context' => 'databoxvertical', 'name' => 'Parent Page', 'contents' => $run_result));
    } else {
        // Ok conditions, build the control.
        $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\">";
        // Get all titles for active pages belonging to the current user
        $pages = recordset_to_array(get_recordset_sql('select page_ident, title from ' . $CFG->prefix . 'folio_page ' . 'WHERE newest = 1 and user_ident = ' . $page->user_ident . ' AND page_ident <> ' . $page->page_ident . ' AND parentpage_ident <> ' . $page->page_ident . ' order by title'));
        // build
        if ($pages) {
            // Iterate
            foreach ($pages as $potentialpage) {
                if ($page->parentpage_ident == $potentialpage->page_ident) {
                    // Selected
                    $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " SELECTED=true>" . $potentialpage->title . "\n";
                } else {
                    // !Selected
                    $run_result .= '<OPTION VALUE=' . $potentialpage->page_ident . " >" . $potentialpage->title . "\n";
                }
            }
            $run_result .= "</SELECT><br/>\n";
        } else {
            // No pages.  Show control set to homepage & disabled.
            $run_result = "\t\t\t<SELECT NAME=\"parentpage_ident\" disabled=TRUE>" . '<OPTION VALUE="' . $page->parentpage_ident . '" SELECTED=true>Homepage' . "</SELECT><br/>\n";
        }
        $run_result = templates_draw(array('context' => 'databoxvertical', 'name' => 'Parent Page', 'contents' => $run_result));
    }
    return $run_result;
}
Example #3
0
/**
* Get the current version, or -1 if the table isn't present
* @return Integer
**/
function folio_getVersion()
{
    global $CFG;
    // Find.
    $versions = recordset_to_array(get_recordset_sql("SELECT version as v, version FROM " . $CFG->prefix . "folio_version"));
    if ($versions) {
        $i = -1;
        foreach ($versions as $version) {
            if ($i < $version->version) {
                $i = $version->version;
            }
        }
        return $version->version;
    } else {
        // Table not found.  Folios probably aren't installed yet.
        return -1;
    }
}
Example #4
0
/**
* Delete a single wiki page.  Assumes that permission check has already been run.
*       Looks to see if there are any child pages, if so, doesn't allow deleting until those are
*       removed as well.
*
* @package folio
* @param array $page The mysql page record.
* @param string $page_title The passed in title used to access the page.  Assumes that it has already 
*	been decoded by the function in lib.php away from the URL form & into the normal presentation form.
* @param string $username The username of the page owner.  Used to create post link
* 	to the finished page.
* @returns HTML code to delete a folio page.
**/
function folio_page_delete($page, $page_title, $username)
{
    global $CFG;
    global $profile_id;
    global $language;
    global $page_owner;
    global $metatags;
    // Set url var
    $url = url;
    // Error, need a page record.
    if (!$page) {
        error('Sorry, but you can not delete a page that has not yet been created.');
    }
    // Get children records.
    $pages = recordset_to_array(get_recordset_sql('SELECT * FROM ' . $CFG->prefix . 'folio_page p ' . "WHERE parentpage_ident = {$page->page_ident} AND newest = 1"));
    // Build results
    if ($pages) {
        // don't offer to delete pages with children.  link to titles
        $run_result = 'Sorry, but you can not delete a page that has child pages under it.  Delete each' . ' of the child pages, and then come back and delete this page.<br/>' . '<ul>';
        foreach ($pages as $page) {
            $run_result .= "<li><a href=\"{$url}{$username}/page/" . folio_page_encodetitle($page->title) . "\">{$page->title}</a>";
        }
        $run_result .= "</ul>";
    } else {
        $run_result = <<<END
            
        <form method="post" name="elggform" action="{$url}_folio/action_redirection.php">
        \t<h2>{$page_title}</h2>
        \t<p>
                Click the 'delete' button to completely remove this page.  You will not be able to undo this process.<br/>
        \t\t<input type="hidden" name="action" value="folio:page:delete" />
        \t\t<input type="hidden" name="page_ident" value="{$page->page_ident}" />
        \t\t<input type="submit" value="Delete" />
        \t</p>
END;
    }
    return $run_result;
}
Example #5
0
function folio_control_childpagelist($username, $page, $profile_id)
{
    global $CFG;
    $url = url;
    if (!$page) {
        // No pages passed.  Can't show sub-pages of a page that doesnt' exist.
        return '';
    } else {
        // Grab matching records.
        $pages = recordset_to_array(get_recordset_sql("SELECT DISTINCT w.* FROM " . $CFG->prefix . "folio_page w " . "INNER JOIN " . $CFG->prefix . "folio_page_security p ON w.security_ident = p.security_ident " . 'WHERE w.parentpage_ident = ' . $page->page_ident . ' AND w.page_ident <> ' . $page->page_ident . ' AND w.newest = 1 AND ' . folio_page_security_where('p', 'w', 'read', $profile_id) . ' ORDER BY title '));
        $html = '<a href="' . $url . $username . '/page/' . folio_page_encodetitle($page->title) . '/addpage">Add a new page under this one</a><br/>';
        if ($pages) {
            // Build html
            $html .= '<ul>';
            foreach ($pages as $childpage) {
                // Load values.
                $html .= "<li><a href=\"{$url}" . $username . '/page/' . folio_page_encodetitle($childpage->title) . '">' . $childpage->title . "</a>\n";
            }
            $html .= '</ul>';
        }
    }
    return $html;
}
Example #6
0
/**
 * Retrieves a list of note objects with specific atributes.
 *
 * @param int    $courseid id of the course in which the notes were posted (0 means any)
 * @param int    $userid id of the user to which the notes refer (0 means any)
 * @param string $state state of the notes (i.e. draft, public, site) ('' means any)
 * @param int    $author id of the user who modified the note last time (0 means any)
 * @param string $order an order to sort the results in
 * @param int    $limitfrom number of records to skip (offset)
 * @param int    $limitnum number of records to fetch
 * @return array of note objects
 */
function note_list($courseid = 0, $userid = 0, $state = '', $author = 0, $order = 'lastmodified DESC', $limitfrom = 0, $limitnum = 0)
{
    // setup filters
    $selects = array();
    if ($courseid) {
        $selects[] = 'courseid=' . $courseid;
    }
    if ($userid) {
        $selects[] = 'userid=' . $userid;
    }
    if ($author) {
        $selects[] = 'usermodified=' . $author;
    }
    if ($state) {
        $selects[] = "publishstate='{$state}'";
    }
    $selects[] = "module='notes'";
    $select = implode(' AND ', $selects);
    $fields = 'id,courseid,userid,content,format,created,lastmodified,usermodified,publishstate';
    // retrieve data
    $rs =& get_recordset_select('post', $select, $order, $fields, $limitfrom, $limitnum);
    return recordset_to_array($rs);
}
        $security_ident = $pages[$page_ident]->security_ident;
    }
} else {
    // Since we're logged in, allow user to set permissions.
    // Check to see if we're inheriting.
    if ($security_type == 'Parent') {
        // Inheriting
        $security_ident = $security_parent;
    } else {
        // Set to a custom security level.  We'll need to insert/update the security record.
        $security_ident = $page_ident;
        // Validate accesslevel
        if ($security_custom != 'PUBLIC' & $security_custom != 'MODERATED' & $security_custom != 'VIEW_ONLY' & $security_custom != 'LOGGED_IN' & $security_custom != 'PRIVATE') {
            error('Invalid access level passed to page_edit_security_post (' . $security_custom . ')');
        }
        // Test to see if the record already exists.
        $pages = recordset_to_array(get_recordset_sql("SELECT * FROM " . $CFG->prefix . 'folio_page_security WHERE security_ident = ' . $page_ident . ' LIMIT 1'));
        if (!$pages[$page_ident]) {
            // Insert a new security record.
            $security = new StdClass();
            $security->security_ident = $page_ident;
            $security->user_ident = -1;
            // NOTE: this is the owner, not the creator.
            $security->accesslevel = $security_custom;
            insert_record('folio_page_security', $security);
        } else {
            // Update security record(s)
            set_field('folio_page_security', 'accesslevel', $security_custom, 'security_ident', $page_ident);
        }
    }
}
Example #8
0
    $where .= " AND ip = '{$filter}'";
}
if (!($count = count_records_select('log', $where))) {
    $return = '{"response":""}';
    //add_to_log(1, 1, $return, true); //debug mode
    echo $return;
    die;
}
$count = $count > $CFG->limitviewentries ? $count - $CFG->limitviewentries : 0;
if (!($entries = get_recordset_select('log', $where, 'time ASC', '*', $count, $CFG->limitviewentries))) {
    $return = '{"response":"KO"}';
    //add_to_log(1, 1, $return, true); //debug mode
    echo $return;
    die;
}
if (!($entries = recordset_to_array($entries))) {
    $return = '{"response":""}';
    //add_to_log(1, 1, $return, true); //debug mode
    echo $return;
    die;
}
/// set return entries in json format {"response":[{"ip":"","time":"","smarttime":"","category":"","info":""}]}
$return = '{"response":[';
foreach ($entries as $entri) {
    /// search for category names
    if (!($category = get_record('categories', 'id', $entri->categoryid))) {
        $return = '{"response":"KO"}';
        //add_to_log(1, 1, $return, true); //debug mode
        echo $return;
        die;
    }
 function get_submission($userid = 0, $createnew = false, $teachermodified = false)
 {
     global $CFG;
     $submission = parent::get_submission($userid, $createnew, $teachermodified);
     if ($submission) {
         $onlinejudge = get_record('assignment_oj_submissions', 'submission', $submission->id);
         if (empty($onlinejudge) && $createnew) {
             $newsubmission = new Object();
             $newsubmission->submission = $submission->id;
             if (!insert_record("assignment_oj_submissions", $newsubmission)) {
                 error("Could not insert a new empty onlinejudge submission");
             }
             unset($newsubmission);
         }
         $onlinejudge = get_record('assignment_oj_submissions', 'submission', $submission->id);
         if ($onlinejudge) {
             $submission->judged = $onlinejudge->judged;
             $submission->oj_id = $onlinejudge->id;
         } else {
             $submission->judged = 0;
         }
         if ($submission->judged) {
             $results = get_recordset_select('assignment_oj_results', 'submission = ' . $submission->id . ' AND judgetime >= ' . $submission->timemodified, 'judgetime DESC', '*', '', '1');
             $results = recordset_to_array($results);
             if ($results) {
                 $result = array_pop($results);
                 $submission->info = $result->info;
                 $submission->status = $result->status;
                 $submission->judgetime = $result->judgetime;
                 $submission->output = $result->output;
             } else {
                 $submission->judged = 0;
                 //It is been judging
                 $submission->status = 'pending';
             }
         } else {
             if (($files = get_directory_list($CFG->dataroot . '/' . $this->file_area_name($userid))) && count($files) != 0) {
                 // Submitted but unjudged
                 $submission->status = 'pending';
             }
         }
     }
     return $submission;
 }
Example #10
0
/**
 * Get a number of records as an array of objects.
 *
 * @deprecated try to use @see function get_recordset_list instead.
 *
 * Arguments as for @see function get_recordset_sql.
 * Return value as for @see function get_records.
 * 
 * @param string $sql the SQL select query to execute.
 * @return mixed an array of objects, or false if no records were found or an error occured.
 */
function get_records_sql($sql, $values = null)
{
    $rs = get_recordset_sql($sql, $values);
    return recordset_to_array($rs);
}
Example #11
0
/**
* Gets the list of categories for the user or for the group
* @param $groupid Id of the group for which we need the categories'list. If 0 or NULL, then get the list of categories of the user
*/
function fm_get_cat_list($groupid = 0)
{
    global $USER;
    // $cats = array();
    $cats[0] = get_string('btnnoassigncat', 'block_file_manager');
    if ($groupid == 0) {
        $ownertype = OWNERISUSER;
        $rs = get_recordset_select('fmanager_categories', "owner={$USER->id} AND ownertype={$ownertype}", 'name');
        $catsrec = recordset_to_array($rs);
    } else {
        $ownertype = OWNERISGROUP;
        $rs = get_recordset_select('fmanager_categories', "owner={$groupid} AND ownertype={$ownertype}", 'name');
        $catsrec = recordset_to_array($rs);
    }
    if ($catsrec) {
        foreach ($catsrec as $c) {
            $cats[$c->id] = $c->name;
        }
    }
    return $cats;
}
Example #12
0
 public static function getRecordById($type, $id)
 {
     $sql = 'SELECT u.id, u.username, u.preferredname, ap.value AS hidenamepref,
     CASE ap.value WHEN \'1\' THEN NULL ELSE u.firstname END AS firstname,
     CASE ap.value WHEN \'1\' THEN NULL ELSE u.lastname END AS lastname,
     u.active, u.deleted, u.email, u.ctime
     FROM {usr} u
     LEFT JOIN {usr_account_preference} ap ON (u.id = ap.usr AND ap.field = \'hiderealname\')
     WHERE u.id = ?';
     $record = get_record_sql($sql, array($id));
     if (!$record || $record->deleted) {
         return false;
     }
     $record->ctime = self::checkctime($record->ctime);
     // institutions
     $institutions = get_records_array('usr_institution', 'usr', $record->id);
     if ($institutions != false) {
         foreach ($institutions as $institution) {
             $record->institutions[] = $institution->institution;
         }
     } else {
         $record->institutions = null;
     }
     // extra email addresses. A few users registered several email addresses as artefact.
     $sqlemail = "SELECT a.title AS email FROM {usr} u INNER JOIN {artefact} a ON a.owner = u.id AND artefacttype = 'email'\n        WHERE u.email != a.title AND u.id = ? AND a.title != ?";
     $emails = recordset_to_array(get_recordset_sql($sqlemail, array($record->id, $record->email)));
     if ($emails != false) {
         // the email property will hold an array instead of just a string
         $email = $record->email;
         unset($record->email);
         $record->email[] = $email;
         foreach ($emails as $email) {
             $record->email[] = $email->email;
         }
     }
     // check to see if the user's profile page is viewable and which is the most 'open' access
     $accessrank = array('loggedin', 'friends');
     if (get_config('searchuserspublic')) {
         array_unshift($accessrank, 'public');
     }
     // get all accesses of user's profile page ordered by the $accessrank array
     // so that the first result will be the most 'open' access allowed
     if (is_postgres()) {
         $join = '';
         $count = 0;
         foreach ($accessrank as $key => $access) {
             $count++;
             $join .= "('" . $access . "'," . $key . ")";
             if ($count != sizeof($accessrank)) {
                 $join .= ",";
             }
         }
         $sql = "SELECT va.accesstype FROM {view} v, {view_access} va\n                    JOIN (VALUES" . $join . ") AS x (access_type, ordering) ON va.accesstype = x.access_type\n                    WHERE v.id = va.view AND v.type = 'profile' AND v.owner = ? ORDER BY x.ordering";
     } else {
         $join = "'" . join('\',\'', $accessrank) . "'";
         $sql = "SELECT va.accesstype FROM {view} v, {view_access} va\n                    WHERE v.id = va.view AND v.type = 'profile' AND v.owner = ?\n                    AND accesstype IN (" . $join . ") ORDER BY FIELD(va.accesstype, " . $join . ")";
     }
     $profileviewaccess = recordset_to_array(get_recordset_sql($sql, array($record->id)));
     $record->access['general'] = !empty($profileviewaccess) ? $profileviewaccess[0]->accesstype : 'none';
     // always allow user to search themselves for vanity reasons
     $record->access['usrs'] = $record->id;
     $record->mainfacetterm = self::$mainfacetterm;
     $allowhidename = get_config('userscanhiderealnames');
     $showusername = !get_config('nousernames');
     $record->sort = strtolower(strip_tags(display_name($record, null, false, !$allowhidename || !$record->hidenamepref, $showusername)));
     return $record;
 }
 static function get_records_sql($sql, $limitfrom = '', $limitnum = '')
 {
     $rs = self::get_recordset_sql($sql, $limitfrom, $limitnum);
     $result = recordset_to_array($rs);
     return $result ? $result : array();
 }
 /**
  * Internal method. Queries for a number of forums, including additional
  * data about unread posts etc. Returns the database result.
  * @param array $cmids If specified, array of course-module IDs of desired
  *   forums
  * @param object $course If specified, course object
  * @param int $userid User ID, 0 = current user
  * @param int $unread Type of unread data to obtain (UNREAD_xx constant).
  * @param array $groups Array of group IDs to which the given user belongs
  *   (may be null if unread data not required)
  * @param array $aagforums Array of forums in which the user has
  *   'access all groups' (may be null if unread data not required)
  * @param array $viewhiddenforums Array of forums in which the user has
  *   'view hidden discussions' (may be null if unread data not required)
  * @return array Array of row objects
  */
 private static function query_forums($cmids = array(), $course = null, $userid, $unread, $groups, $aagforums, $viewhiddenforums)
 {
     global $CFG, $USER;
     if (!count($cmids) && !$course) {
         throw new forum_exception("forum::query_forums requires course id or cmids");
     }
     if (count($cmids)) {
         $conditions = "cm.id " . forum_utils::in_or_equals($cmids);
     } else {
         $conditions = "f.course = {$course->id}";
     }
     $singleforum = count($cmids) == 1 ? reset($cmids) : false;
     $inviewhiddenforums = forum_utils::in_or_equals($viewhiddenforums);
     // This array of additional results is used later if combining
     // standard results with single-forum calls.
     $plusresult = array();
     // For read tracking, we get a count of total number of posts in
     // forum, and total number of read posts in the forum (this
     // is so we can display the number of UNread posts, but the query
     // works that way around because it will return 0 if no read
     // information is stored).
     if ($unread != self::UNREAD_NONE && forum::enabled_read_tracking()) {
         // Work out when unread status ends
         $endtime = time() - $CFG->forumng_readafterdays * 24 * 3600;
         if (!$userid) {
             $userid = $USER->id;
         }
         $ingroups = forum_utils::in_or_equals($groups);
         $inaagforums = forum_utils::in_or_equals($aagforums);
         $restrictionsql = '';
         if ($singleforum) {
             // If it is for a single forum, get the restriction from the
             // forum type
             $forum = forum::get_from_cmid($singleforum, forum::CLONE_DIRECT);
             $type = $forum->get_type();
             if ($type->has_unread_restriction()) {
                 $value = $type->get_unread_restriction_sql($forum);
                 if ($value) {
                     $restrictionsql = 'AND ' . $value;
                 }
             }
         } else {
             // When it is not for a single forum, we can only group together
             // results for types that do not place restrictions on the
             // unread count.
             $modinfo = self::get_modinfo_special($course, $cmids);
             $okayids = array();
             if (array_key_exists('forumng', $modinfo->instances)) {
                 foreach ($modinfo->instances['forumng'] as $info) {
                     if (count($cmids) && !in_array($info->id, $cmids)) {
                         continue;
                     }
                     $type = self::get_type_from_modinfo_info($info);
                     if (forum_type::get_new($type)->has_unread_restriction()) {
                         // This one's a problem! Do it individually
                         $problemresults = self::query_forums(array($info->id), null, $userid, $unread, $groups, $aagforums, $viewhiddenforums);
                         foreach ($problemresults as $problemresult) {
                             $plusresult[$problemresult->f_id] = $problemresult;
                         }
                     } else {
                         $okayids[] = $info->id;
                     }
                 }
             }
             if (count($okayids) == 0) {
                 // There are no 'normal' forums, so return result so far
                 // after sorting it
                 uasort($plusresult, 'forum::sort_forum_result');
                 return $plusresult;
             } else {
                 // Fall through to normal calculation, but change conditions
                 // to include only the 'normal' forums
                 $conditions .= " AND cm.id " . forum_utils::in_or_equals($okayids);
             }
         }
         // NOTE fpfirst is used only by forum types, not here
         $now = time();
         $sharedquerypart = "\nFROM\n    {$CFG->prefix}forumng_discussions fd\n    INNER JOIN {$CFG->prefix}forumng_posts fplast ON fd.lastpostid = fplast.id\n    INNER JOIN {$CFG->prefix}forumng_posts fpfirst ON fd.postid = fpfirst.id\n    LEFT JOIN {$CFG->prefix}forumng_read fr ON fd.id = fr.discussionid AND fr.userid={$userid}\nWHERE\n    fd.forumid=f.id AND fplast.modified>{$endtime}\n    AND (\n        (fd.groupid IS NULL)\n        OR (fd.groupid {$ingroups})\n        OR cm.groupmode=" . VISIBLEGROUPS . "\n        OR (fd.forumid {$inaagforums})\n    )\n    AND fd.deleted=0\n    AND (\n        ((fd.timestart=0 OR fd.timestart <= {$now})\n        AND (fd.timeend=0 OR fd.timeend > {$now}))\n        OR (fd.forumid {$inviewhiddenforums})\n    )\n    AND ((fplast.edituserid IS NOT NULL AND fplast.edituserid<>{$userid})\n        OR fplast.userid<>{$userid})\n    AND (fr.time IS NULL OR fplast.modified>fr.time)\n    {$restrictionsql}";
         // Note: There is an unusual case in which this number can
         // be inaccurate. It is to do with ignoring messages the user
         // posted. We consider a discussion as 'not unread' if the last
         // message is by current user. In actual fact, a discussion could
         // contain unread messages if messages were posted by other users
         // after this user viewed the forum last, but before they posted
         // their reply. Since this should be an infrequent occurrence I
         // believe this behaviour is acceptable.
         if ($unread == self::UNREAD_BINARY && ($CFG->dbtype == 'postgres7' || $CFG->dbtype == 'mysql')) {
             // Query to get 0/1 unread discussions count
             $readtracking = "\n(SELECT\n    COUNT(1)\nFROM (\n    SELECT\n        1\n    {$sharedquerypart}\n    LIMIT 1) innerquery\n) AS f_hasunreaddiscussions";
         } else {
             // Query to get full unread discussions count
             $readtracking = "\n(SELECT\n    COUNT(1)\n{$sharedquerypart}\n) AS f_numunreaddiscussions";
         }
     } else {
         $readtracking = "NULL AS numreadposts, NULL AS timeread";
     }
     $now = time();
     $orderby = "LOWER(f.name)";
     // Main query. This retrieves:
     // - Full forum fields
     // - Basic course-module and course data (not whole tables)
     // - Discussion count
     // - Unread data, if enabled
     // - User subscription data
     $rs = get_recordset_sql($sql = "\nSELECT\n    " . forum_utils::select_forum_fields('f') . ",\n    " . forum_utils::select_course_module_fields('cm') . ",\n    " . forum_utils::select_course_fields('c') . ",\n    (SELECT COUNT(1)\n        FROM {$CFG->prefix}forumng_discussions cfd\n        WHERE cfd.forumid=f.id AND cfd.deleted=0\n        AND (\n            ((cfd.timestart=0 OR cfd.timestart <= {$now})\n            AND (cfd.timeend=0 OR cfd.timeend > {$now}))\n            OR (cfd.forumid {$inviewhiddenforums})\n        )\n        ) AS f_numdiscussions,\n    {$readtracking}\nFROM\n    {$CFG->prefix}forumng f\n    INNER JOIN {$CFG->prefix}course_modules cm ON cm.instance=f.id\n        AND cm.module=(SELECT id from {$CFG->prefix}modules WHERE name='forumng')\n    INNER JOIN {$CFG->prefix}course c ON c.id=f.course\nWHERE\n    {$conditions}\nORDER BY\n    {$orderby}");
     if (!$rs) {
         throw new forum_exception("Failed to retrieve forums");
     }
     $result = recordset_to_array($rs);
     rs_close($rs);
     if (count($plusresult) > 0) {
         foreach ($plusresult as $key => $value) {
             $result[$key] = $value;
         }
         uasort($result, 'forum::sort_forum_result');
     }
     return $result;
 }
Example #15
0
function folio_control_page_edit_security($page)
{
    // Find the security information for the page.
    global $CFG;
    global $FOLIO_CFG;
    $url = url;
    $accesslevel = '';
    $page_ident = intval($page->page_ident);
    $parentpage_ident = intval($page->parentpage_ident);
    $security_ident = intval($page->security_ident);
    // Find out what security-level we're set at.
    $accesslevels = recordset_to_array(get_recordset_sql('SELECT security_ident, accesslevel FROM ' . $CFG->prefix . 'folio_page_security ' . "WHERE security_ident = {$security_ident} LIMIT 1"));
    if (!$accesslevels[$security_ident]) {
        // No results returned.  Could be because we don't have permission to access the parent pages, or that the parent may have been removed/deleted.
        // Set the default access level.
        $accesslevel = $FOLIO_CFG->page_defaultpermission;
    } else {
        // Grab the record entry.
        $accesslevel = stripslashes($accesslevels[$security_ident]->accesslevel);
    }
    // Figure out which option is selected & set value.
    $oPublic = '';
    $oModerated = '';
    $oPrivate = '';
    if ($accesslevel == 'PUBLIC') {
        $oPublic = ' SELECTED=true ';
    } elseif ($accesslevel == 'MODERATED') {
        $oModerated = ' SELECTED=true ';
    } elseif ($accesslevel == 'PRIVATE') {
        $oPrivate = ' SELECTED=true ';
    } elseif ($accesslevel == 'LOGGED_IN') {
        $oLoggedIn = ' SELECTED=true ';
    } elseif ($accesslevel == 'VIEW_ONLY') {
        $oViewOnly = ' SELECTED=true ';
    }
    // If the user isn't logged in, then they are not allowed to change the permission level for the page.
    if (!isloggedin()) {
        // finish building the control, but mark it as disabled..
        $run_result = <<<END
\t\t\t<SELECT NAME="folio_control_page_edit_security_custom" DISABLED>
\t\t\t\t<OPTION VALUE="PUBLIC" {$oPublic}>Public (everyone has full access)
\t\t\t\t<OPTION VALUE="MODERATED" {$oModerated}>Moderated (other people can read, friends can edit)
\t\t\t\t<OPTION VALUE="VIEW_ONLY" {$oViewOnly}>View Only (other people can read only)
\t\t\t\t<OPTION VALUE="LOGGED_IN" {$oLoggedIn}>Logged In (only logged in users can read)
\t\t\t\t<OPTION VALUE="PRIVATE" {$oPrivate}>Private (other people can not read or edit)
\t\t\t</SELECT><b> You must first log in to change permissions.</b>
\t\t<br/>
END;
    } else {
        // finish building the control.
        $run_result = <<<END
\t\t\t<SELECT NAME="folio_control_page_edit_security_custom">
\t\t\t\t<OPTION VALUE="PUBLIC" {$oPublic}>Public (everyone has full access)
\t\t\t\t<OPTION VALUE="MODERATED" {$oModerated}>Moderated (other people can read, friends can edit)
\t\t\t\t<OPTION VALUE="VIEW_ONLY" {$oViewOnly}>View Only (other people can read only)
\t\t\t\t<OPTION VALUE="LOGGED_IN" {$oLoggedIn}>Logged In (only logged in users can read)
\t\t\t\t<OPTION VALUE="PRIVATE" {$oPrivate}>Private (other people can not read or edit)
\t\t\t</SELECT>
\t\t<br/>
END;
    }
    return templates_draw(array('context' => 'databoxvertical', 'name' => 'Security', 'contents' => $run_result));
}
Example #16
0
/**
 * Find the connected authinstance for the organisation attached to this SAML account
 *
 * @param array $saml_attributes
 *
 * @return object authinstance record
 */
function auth_saml_find_authinstance($saml_attributes)
{
    // find the one (it should be only one) that has the right field, and the right field value for institution
    $instance = false;
    $institutions = array();
    // find all the possible institutions/auth instances of type saml
    $instances = recordset_to_array(get_recordset_sql("SELECT * FROM {auth_instance_config} aic, {auth_instance} ai WHERE ai.id = aic.instance AND ai.authname = 'saml' AND aic.field = 'institutionattribute'"));
    foreach ($instances as $row) {
        $institutions[] = $row->instance . ':' . $row->institution . ':' . $row->value;
        if (isset($saml_attributes[$row->value])) {
            // does this institution use a regex match against the institution check value?
            if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionregex')) {
                $is_regex = (bool) $configvalue->value;
            } else {
                $is_regex = false;
            }
            if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionvalue')) {
                $institution_value = $configvalue->value;
            } else {
                $institution_value = $row->institution;
            }
            if ($is_regex) {
                foreach ($saml_attributes[$row->value] as $attr) {
                    if (preg_match('/' . trim($institution_value) . '/', $attr)) {
                        $instance = $row;
                        break;
                    }
                }
            } else {
                foreach ($saml_attributes[$row->value] as $attr) {
                    if ($attr == $institution_value) {
                        $instance = $row;
                        break;
                    }
                }
            }
        }
    }
    return $instance;
}
/**
 * check the validity of the users current SAML 2.0 session
 * if its bad, force log them out of Mahara, and redirect them to the IdP
 * if it's good, find an applicable saml auth instance, and try logging them in with it
 * passing in the attributes found from the IdP 
 *
 * @param object $saml_config saml configuration object
 * @param boolean $valid_saml_session is there a valid saml2 session
 * @param array $saml_attributes saml attributes passed in by the IdP
 * @param object $as new saml user object
 * @return nothing
 */
function simplesaml_init($saml_config, $valid_saml_session, $saml_attributes, $as)
{
    global $CFG, $USER, $SESSION;
    //    $idp = get_config_plugin('auth', 'saml', 'idpidentity');
    $retry = $SESSION->get('retry');
    if ($retry > SAML_RETRIES) {
        throw new AccessTotallyDeniedException(get_string('errorretryexceeded', 'auth.saml', $retry));
    } else {
        if (!$valid_saml_session) {
            #
            if ($USER->is_logged_in()) {
                $USER->logout();
            }
            $SESSION->set('messages', array());
            $SESSION->set('retry', $retry + 1);
            // not valid session. Ship user off to the Identity Provider
            $as->requireAuth();
        } else {
            // find all the possible institutions/auth instances
            $instances = recordset_to_array(get_recordset_sql("SELECT * FROM {auth_instance_config} aic, {auth_instance} ai WHERE ai.id = aic.instance AND ai.authname = 'saml' AND aic.field = 'institutionattribute'"));
            // find the one (it should be only one) that has the right field, and the right field value for institution
            $instance = false;
            $institutions = array();
            foreach ($instances as $row) {
                $institutions[] = $row->instance . ':' . $row->institution . ':' . $row->value;
                if (isset($saml_attributes[$row->value])) {
                    // does this institution use a regex match against the institution check value?
                    if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionregex')) {
                        $is_regex = (bool) $configvalue->value;
                    } else {
                        $is_regex = false;
                    }
                    if ($configvalue = get_record('auth_instance_config', 'instance', $row->instance, 'field', 'institutionvalue')) {
                        $institution_value = $configvalue->value;
                    } else {
                        $institution_value = $row->institution;
                    }
                    if ($is_regex) {
                        foreach ($saml_attributes[$row->value] as $attr) {
                            if (preg_match('/' . trim($institution_value) . '/', $attr)) {
                                $instance = $row;
                                break;
                            }
                        }
                    } else {
                        foreach ($saml_attributes[$row->value] as $attr) {
                            if ($attr == $institution_value) {
                                $instance = $row;
                                break;
                            }
                        }
                    }
                }
            }
            if (!$instance) {
                log_warn("auth/saml: could not find an authinstance from: " . join(",  ", $institutions));
                log_warn("auth/saml: could not find the saml institutionattribute for user: " . var_export($saml_attributes, true));
                throw new UserNotFoundException(get_string('errorbadinstitution', 'auth.saml'));
            }
            try {
                $auth = new AuthSaml($instance->id);
                if ($auth->request_user_authorise($saml_attributes)) {
                    session_write_close();
                    redirect($CFG->wwwroot);
                } else {
                    throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
                }
            } catch (AccessDeniedException $e) {
                throw new UserNotFoundException(get_string('errnosamluser', 'auth.saml'));
            }
        }
    }
}
Example #18
0
 private function getExistingRoles()
 {
     $rs = get_recordset_sql('SELECT DISTINCT role FROM {grouptype_roles}');
     $roles = array('all');
     foreach (recordset_to_array($rs) as $record) {
         $roles[] = $record->role;
     }
     return $roles;
 }
function cegep_unenrolprogram()
{
    global $CFG, $COURSE, $DB, $OUTPUT, $enroldb;
    $currenttab = 'unenrolprogram';
    require 'block_cegep_tabs.php';
    // Set up enrolment form
    require 'block_cegep_unenrolprogram_form.php';
    $unenrolprogramform = new cegep_unenrolprogram_form('block_cegep_enrolment.php?a=unenrolprogram&id=' . $COURSE->id . '');
    // Go back to course page if cancelled
    if ($unenrolprogramform->is_cancelled()) {
        redirect($CFG->wwwroot . '/course/view.php?id=' . $COURSE->id);
    } elseif ($data = $unenrolprogramform->get_data()) {
        foreach ($data->program as $p) {
            $program_list = "'{$p}',";
        }
        $program_list = rtrim($program_list, ',');
        // Get usernames before removing
        $select = "SELECT `{$CFG->enrol_remoteuserfield}` FROM `{$CFG->enrol_dbname}`.`{$CFG->enrol_remoteenroltable}` WHERE `{$CFG->enrol_remotecoursefield}` = '{$COURSE->idnumber}' AND `{$CFG->enrol_remoterolefield}` = '{$CFG->block_cegep_studentrole}' AND `program_idyear` IN ({$program_list});";
        $usernames = recordset_to_array($enroldb->Execute($select));
        // If user exists, unassign role right away
        if ($usernames) {
            $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
            $student_role = $DB->get_record('role', array($CFG->enrol_localrolefield => $CFG->block_cegep_studentrole));
            foreach ($usernames as $username) {
                if ($student_user = $DB->get_record('user', array($CFG->enrol_localuserfield => $username->username))) {
                    role_unassign($student_role->id, $student_user->id, $context->id, 'enrol_database');
                }
            }
        }
        // Go through each program/year and remove Moodle external enrolment database record
        $delete = "DELETE FROM `{$CFG->enrol_remoteenroltable}` WHERE `{$CFG->enrol_remotecoursefield}` = '{$COURSE->idnumber}' AND `{$CFG->enrol_remoterolefield}` = '{$CFG->block_cegep_studentrole}' AND `program_idyear` IN ({$program_list});";
        $result = $enroldb->Execute($delete);
        if (!$result) {
            trigger_error($enroldb->ErrorMsg() . ' STATEMENT: ' . $delete);
            print_error('errordeletingenrolment', 'block_cegep');
            break;
        } else {
            echo $OUTPUT->notification(get_string('programunenrolled', 'block_cegep', $enroldb->Affected_Rows()), 'notifysuccess');
            echo $OUTPUT->continue_button($CFG->wwwroot . '/course/view.php?id=' . $COURSE->id);
        }
    } else {
        echo $OUTPUT->heading(get_string('unenrolprogram', 'block_cegep'), 3);
        $unenrolprogramform->display();
    }
}
Example #20
0
/**
 * Get a number of records as an array of objects.
 *
 * Return value as for @see function get_records.
 *
 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
 *   must be a unique value (usually the 'id' field), as it will be used as the key of the
 *   returned array.
 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
 * @return mixed an array of objects, or false if no records were found or an error occured.
 */
function get_records_sql($sql, $limitfrom = '', $limitnum = '')
{
    $rs = get_recordset_sql($sql, $limitfrom, $limitnum);
    return recordset_to_array($rs);
}
Example #21
0
		div.innerHTML += "<li>Server response: " + o.responseText + "</li>";
		div.innerHTML += "<li>Argument object: Object ( [foo] => " + o.argument.foo +
						 " [bar] => " + o.argument.bar +" )</li>";
*/
require_once "../../../includes.php";
$page_ident = required_param('page', 0, PARAM_INT);
$page = get_record('folio_page', 'page_ident', $page_ident, 'newest', 1);
$profile_id = $page->user_ident;
$prefix = $CFG->prefix;
$run_result = '';
// NOTE: The following query has the potential to return duplicates.  However, the older mysq doesn't support subqueries,  making it impossible
//  to do the query properly.  Filter out dups in code.
//      Potential Dup: w.* & children = 0, w.* & children = 1
//      Filtering on children=1 is a problem, as moving a child of a page, leaves new=0 with the parentpage_ident still set, filtering out that
//      page.
$pages = recordset_to_array(get_recordset_sql("SELECT DISTINCT w.*, children.newest children FROM {$prefix}folio_page w " . "INNER JOIN {$prefix}folio_page_security p ON w.security_ident = p.security_ident " . "LEFT OUTER JOIN {$prefix}folio_page children ON w.page_ident = children.parentpage_ident " . "WHERE w.parentpage_ident = {$page_ident} AND w.newest = 1 AND w.parentpage_ident <> w.page_ident AND " . folio_page_security_where('p', 'w', 'read', $profile_id) . 'ORDER BY title, children DESC'));
$last_ident = -1;
if ($pages) {
    foreach ($pages as $page) {
        $i = $page->page_ident;
        // Look to see if we're looking at a duplicate.
        if ($last_ident != $i) {
            // Update last_ident
            $last_ident = $i;
            // Load results
            $run_result .= intval($page->page_ident) . "\"";
            $run_result .= str_replace("\"", "'", $page->title) . "\"";
            $run_result .= str_replace("\"", "'", folio_page_encodetitle($page->title)) . "\"";
            if (is_null($page->children)) {
                // No kids.  Value is interpreted as 'already loaded', so since no kids, set to already loaded.
                $run_result .= "true\"";
Example #22
0
/**
* Based off of the incoming parameters, build a SQL where condition
**/
function buildWhere($purpose, $reader_ident, $user_ident, $types, $types_avoid)
{
    global $CFG;
    if ($purpose == 'activity') {
        // FIND FRIENDS AND JOINED COMMUNITIES.
        // Find key values for friends.
        $friendlist = array();
        $friends = recordset_to_array(get_recordset_sql("SELECT DISTINCT friend as i, friend FROM " . $CFG->prefix . "friends where owner = {$user_ident}"));
        if ($friends) {
            foreach ($friends as $friend) {
                $friendlist[] = $friend->friend;
            }
        }
        // Find key values for owned communities
        $friends = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as i, ident FROM " . $CFG->prefix . "users where owner = {$user_ident}"));
        if ($friends) {
            foreach ($friends as $friend) {
                $friendlist[] = $friend->ident;
            }
        }
        // Transform array into a where clause.
        if (count($friendlist) > 0) {
            $friendlist = implode(',', $friendlist);
            $where = 'owner_ident in (' . $friendlist . ')';
        } else {
            // If a person has no friends or communities, then they have no activity.
            $where = ' false ';
        }
    } elseif ($purpose == 'subscribe') {
        // Subscribe to a person's feed.
        $where = "owner_ident = {$user_ident}";
    } else {
        die('unknown purpose passed to feeds.php');
    }
    // Add permissions
    $where .= ' AND access in ("' . implode('","', rss_permissionlist($reader_ident)) . '")';
    // Add type filter
    $where .= rss_buildwhere('type', $types, $types_avoid);
    return $where;
}
Example #23
0
/**
 * Check to make sure table is case sensitive (currently only for MySql)
 * If it is not then reduce supplied array to a case insensitive version
 * Preserving the first occurance of any duplicates.
 * E.g. 'Test,test,cat,TEST,CAT,Cat' will return 'Test,cat'
 *
 * @param array     Array of case senstive strings
 * @param string    Name of table
 *
 * @return array    Array of strings
 */
function check_case_sensitive($a, $table)
{
    if (is_mysql()) {
        $db = get_config('dbname');
        $result = recordset_to_array(get_recordset_sql("SHOW TABLE STATUS IN `{$db}` WHERE Name = ?", array($table)));
        if (preg_match('/_ci/', $result[0]->Collation)) {
            $b = array_unique(array_map('strtolower', $a));
            $a = array_intersect_key($a, array_flip(array_keys($b)));
        }
    }
    return $a;
}
Example #24
0
/**
* Retrieve all of the allowable permission types for the passed userid
* @param int $userid -1 is a valid option, just sets to public permissions.
**/
function rss_permissionlist($userid)
{
    global $CFG;
    if ($userid == -1) {
        return array('PUBLIC', 'MODERATED', 'VIEW_ONLY');
    }
    // Default permissions already availabled to logged-in users.
    $list = array('PUBLIC', 'LOGGED_IN', 'MODERATED', 'VIEW_ONLY');
    // Find values for joined communities.
    $communities = recordset_to_array(get_recordset_sql("SELECT distinct u.ident as i, u.ident FROM " . $CFG->prefix . "friends e inner join " . $CFG->prefix . "users u on e.friend = u.ident where e.owner={$userid} and user_type = 'community'"));
    if ($communities) {
        foreach ($communities as $community) {
            $list[] = 'community' . $community->ident;
        }
    }
    // Find values for owned communities
    $communities = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as username, ident FROM " . $CFG->prefix . "users where owner = {$userid}"));
    if ($communities) {
        foreach ($communities as $community) {
            $list[] = 'community' . $community->username;
        }
    }
    // Find values for joined groups.
    $groups = recordset_to_array(get_recordset_sql("SELECT distinct g.ident as i, g.ident FROM " . $CFG->prefix . "group_membership m inner join " . $CFG->prefix . "groups g on m.group_id = g.ident where m.user_id={$userid} "));
    if ($groups) {
        foreach ($groups as $group) {
            $list[] = 'group' . $group->ident;
        }
    }
    // Find values for owned groups
    $groups = recordset_to_array(get_recordset_sql("SELECT DISTINCT ident as i, ident FROM " . $CFG->prefix . "groups where owner = {$userid}"));
    if ($groups) {
        foreach ($groups as $group) {
            $list[] = 'group' . $group->ident;
        }
    }
    return $list;
}
Example #25
0
/**
* Builds the child nodes for the passed page_ident.
*
* @param int $page_ident The parent for whom we're retrieving children.
* @param int $ignorepage_ident Optional. A page to leave out of the results (if found).  Used by getNodeParents.
**/
function folio_control_tree_getNodeChildren($ajaxprefix, $page_ident, $ignorepage_ident, $url, $previousresults, $profile_id)
{
    global $CFG;
    $prefix = $CFG->prefix;
    // NOTE: The following query has the potential to return duplicates.  However, the older mysq doesn't support subqueries,  making it impossible
    //  to do the query properly.  Filter out dups in code.
    //      Potential Dup: w.* & children = 0, w.* & children = 1
    //      Filtering on children=1 is a problem, as moving a child of a page, leaves new=0 with the parentpage_ident still set, filtering out that
    //      page.
    $pages = recordset_to_array(get_recordset_sql("SELECT DISTINCT w.*, children.newest children FROM {$prefix}folio_page w " . "INNER JOIN {$prefix}folio_page_security p ON w.security_ident = p.security_ident " . "LEFT OUTER JOIN {$prefix}folio_page children ON w.page_ident = children.parentpage_ident " . "WHERE w.parentpage_ident = {$page_ident} AND w.newest = 1 AND w.parentpage_ident <> w.page_ident AND " . folio_page_security_where('p', 'w', 'read', $profile_id) . 'ORDER BY title DESC, children DESC'));
    // Set the parent node's name.
    $parentnode = $ajaxprefix . 'Node' . $page_ident;
    $last_ident = -1;
    $result = '';
    if ($pages) {
        foreach ($pages as $page) {
            $i = $page->page_ident;
            // Look to see if we're looking at a duplicate.
            if ($last_ident != $i) {
                // Update last_ident
                $last_ident = $i;
                // Test to see if we're on the *ignore* page, in which case, insert the nodes that have been built thus far.
                if ($ignorepage_ident == $i) {
                    $result = $previousresults . "\n" . $result;
                } else {
                    if (is_null($page->children)) {
                        // No kids
                        $result = "     var {$ajaxprefix}Node{$i} = {$ajaxprefix}buildNode( \"{$i}\", \"" . str_replace("\"", "'", $page->title) . "\", {$parentnode}, true, \"" . $url . folio_page_encodetitle($page->title) . "\");\n" . $result;
                    } else {
                        // Children, set loaded = false
                        $result = "     var {$ajaxprefix}Node{$i} = {$ajaxprefix}buildNode( \"{$i}\", \"" . str_replace("\"", "'", $page->title) . "\", {$parentnode}, false, \"" . $url . folio_page_encodetitle($page->title) . "\");\n" . $result;
                    }
                }
            } else {
                // $last_ident == $i
                // Don't load, as it would be a duplicate record.
            }
        }
        // foreach
    }
    // if $pages
    return $result;
}