Example #1
0
 /**
  * This method gets called after the action is called.
  *
  * @param mixed $response Value returned from the action method.
  * 
  * @return Response $response
  */
 public function after($response)
 {
     // Return if passed a response.
     if ($response instanceof Response) {
         return parent::after($response);
     }
     if ($this->autorender) {
         try {
             $this->view->set_filename(Str::lower(str_replace('_', '/', Inflector::denamespace(str_replace('controller_', '', Str::lower($this->request->controller)))) . DS . str_replace('_', '/', $this->request->action)));
         } catch (FuelException $e) {
         }
     }
     // Inject view into the layout if the main request.
     if ($this->layout instanceof View) {
         if ($this->autorender) {
             try {
                 // Throws exception if there is no view template found.
                 $this->layout->content = $this->view->render();
             } catch (FuelException $e) {
             }
         }
         $this->layout->content_data = $this->view->get();
         $this->response->body($this->layout);
     } else {
         $this->response->body($this->view);
     }
     return parent::after($this->response);
 }
Example #2
0
 public static function allowed_in_view(View $view)
 {
     if ($view->get('title') == gcr::defaultDashboardTemplateTitle) {
         return true;
     } else {
         return $view->get('owner') != null;
     }
 }
Example #3
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     global $USER;
     require_once get_config('docroot') . 'lib/view.php';
     $configdata = $instance->get('configdata');
     // this will make sure to unserialize it for us
     $configdata['viewid'] = $instance->get('view');
     $view = new View($configdata['viewid']);
     $group = $view->get('group');
     $result = '';
     $artefactid = isset($configdata['artefactid']) ? $configdata['artefactid'] : null;
     if ($artefactid) {
         $artefact = $instance->get_artefact_instance($configdata['artefactid']);
         if (!file_exists($artefact->get_path())) {
             return '';
         }
         $urlbase = get_config('wwwroot');
         // edit view doesn't use subdomains, neither do groups
         if (get_config('cleanurls') && get_config('cleanurlusersubdomains') && !$editing && empty($group)) {
             $viewauthor = new User();
             $viewauthor->find_by_id($view->get('owner'));
             $viewauthorurlid = $viewauthor->get('urlid');
             if ($urlallowed = !is_null($viewauthorurlid) && strlen($viewauthorurlid)) {
                 $urlbase = profile_url($viewauthor) . '/';
             }
         }
         // Send the current language to the pdf viewer
         $language = current_language();
         $language = str_replace('_', '-', substr($language, 0, substr_count($language, '_') > 0 ? 5 : 2));
         if ($language != 'en' && !file_exists(get_config('docroot') . 'artefact/file/blocktype/pdf/js/pdfjs/web/locale/' . $language . '/viewer.properties')) {
             // In case the language file exists as a string with both lower and upper case, eg fr_FR we test for this
             $language = substr($language, 0, 2) . '-' . strtoupper(substr($language, 0, 2));
             if (!file_exists(get_config('docroot') . 'artefact/file/blocktype/pdf/js/pdfjs/web/locale/' . $language . '/viewer.properties')) {
                 // In case we fail to find a language of 5 chars, eg pt_BR (Portugese, Brazil) we try the 'parent' pt (Portugese)
                 $language = substr($language, 0, 2);
                 if ($language != 'en' && !file_exists(get_config('docroot') . 'artefact/file/blocktype/pdf/js/pdfjs/web/locale/' . $language . '/viewer.properties')) {
                     $language = 'en-GB';
                 }
             }
         }
         $result = '<iframe src="' . $urlbase . 'artefact/file/blocktype/pdf/viewer.php?editing=' . $editing . '&ingroup=' . !empty($group) . '&file=' . $artefactid . '&lang=' . $language . '&view=' . $instance->get('view') . '" width="100%" height="500" frameborder="0"></iframe>';
         require_once get_config('docroot') . 'artefact/comment/lib.php';
         require_once get_config('docroot') . 'lib/view.php';
         $view = new View($configdata['viewid']);
         list($commentcount, $comments) = ArtefactTypeComment::get_artefact_comments_for_view($artefact, $view, $instance->get('id'), true, $editing);
     }
     $smarty = smarty_core();
     if ($artefactid) {
         $smarty->assign('commentcount', $commentcount);
         $smarty->assign('comments', $comments);
     }
     $smarty->assign('html', $result);
     return $smarty->fetch('blocktype:pdf:pdfrender.tpl');
 }
Example #4
0
 /**
  * Maneja las excepciones no capturadas
  *
  * @param Exception $e
  * */
 public static function handle_exception($e)
 {
     if (isset($e->_view) && ($e->_view == 'no_controller' || $e->_view == 'no_action')) {
         header('HTTP/1.1 404 Not Found');
     } else {
         header('HTTP/1.1 500 Internal Server Error');
     }
     extract(Router::get(), EXTR_OVERWRITE);
     $Controller = Util::camelcase($controller);
     ob_start();
     if (PRODUCTION) {
         include APP_PATH . 'views/_shared/errors/404.phtml';
         return;
     } else {
         $Template = 'views/templates/exception.phtml';
         if (isset($e->_view)) {
             include CORE_PATH . "views/errors/{$e->_view}.phtml";
         } else {
             include CORE_PATH . "views/errors/exception.phtml";
         }
     }
     $content = ob_get_clean();
     // termina los buffers abiertos
     while (ob_get_level()) {
         ob_end_clean();
     }
     // verifica si esta cargado el View
     if (class_exists('View')) {
         if (View::get('template') === NULL) {
             echo $content;
             exit;
         }
     }
     include CORE_PATH . $Template;
 }
Example #5
0
function edit_comment_submit(Pieform $form, $values)
{
    global $viewid, $comment, $SESSION, $goto, $USER;
    require_once 'embeddedimage.php';
    db_begin();
    $comment->set('rating', valid_rating($values['rating']));
    require_once get_config('libroot') . 'view.php';
    $view = new View($viewid);
    $owner = $view->get('owner');
    $group = $comment->get('group');
    $newdescription = EmbeddedImage::prepare_embedded_images($values['message'], 'comment', $comment->get('id'), $group);
    $comment->set('description', $newdescription);
    $approvecomments = $view->get('approvecomments');
    if (!empty($group) && ($approvecomments || !$approvecomments && $view->user_comments_allowed($USER) == 'private') && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $comment->set('requestpublic', 'author');
    } else {
        if (($approvecomments || !$approvecomments && $view->user_comments_allowed($USER) == 'private') && $values['ispublic'] && (!empty($owner) && $owner != $comment->get('author'))) {
            $comment->set('requestpublic', 'author');
        } else {
            $comment->set('private', 1 - (int) $values['ispublic']);
            $comment->set('requestpublic', null);
        }
    }
    $comment->commit();
    require_once 'activity.php';
    $data = (object) array('commentid' => $comment->get('id'), 'viewid' => $viewid);
    activity_occurred('feedback', $data, 'artefact', 'comment');
    if ($comment->get('requestpublic') == 'author') {
        if (!empty($owner)) {
            edit_comment_notify($view, $comment->get('author'), $owner);
        } else {
            if (!empty($group)) {
                $group_admins = group_get_admin_ids($group);
                // TODO: need to notify the group admins bug #1197197
            }
        }
    }
    db_commit();
    $SESSION->add_ok_msg(get_string('commentupdated', 'artefact.comment'));
    redirect($goto);
}
 /**
  * test that the setters work and commit to the db
  * and when we get the view back it matches
  */
 public function testViewCommitting()
 {
     // now commit to db and test again
     foreach ($this->fields as $field => $values) {
         $this->view->set($field, $values[1]);
     }
     $this->view->commit();
     $createdview = new View($this->view->get('id'));
     foreach ($this->fields as $field => $values) {
         $this->assertEquals($values[1], $createdview->get($field));
     }
 }
Example #7
0
File: lib.php Project: kienv/mahara
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     global $USER;
     if ($editing) {
         $smarty = smarty_core();
         $smarty->assign('editing', get_string('ineditordescription1', 'blocktype.comment/comment'));
         $html = $smarty->fetch('blocktype:comment:comment.tpl');
         return $html;
     }
     // Feedback list pagination requires limit/offset params
     $limit = param_integer('limit', 10);
     $offset = param_integer('offset', 0);
     $showcomment = param_integer('showcomment', null);
     // Create the "make feedback private form" now if it's been submitted
     if (param_variable('make_public_submit', null)) {
         pieform(ArtefactTypeComment::make_public_form(param_integer('comment')));
     } else {
         if (param_variable('delete_comment_submit_x', null)) {
             pieform(ArtefactTypeComment::delete_comment_form(param_integer('comment')));
         }
     }
     $view = new View($instance->get('view'));
     $submittedgroup = (int) $view->get('submittedgroup');
     if ($USER->is_logged_in() && $submittedgroup && group_user_can_assess_submitted_views($submittedgroup, $USER->get('id'))) {
         $releaseform = true;
     } else {
         $releaseform = false;
     }
     // If the view has comments turned off, tutors can still leave
     // comments if the view is submitted to their group.
     if (!empty($releaseform) || $view->user_comments_allowed($USER)) {
         $addfeedbackpopup = true;
     }
     safe_require('artefact', 'comment');
     $commentoptions = ArtefactTypeComment::get_comment_options();
     $commentoptions->limit = $limit;
     $commentoptions->offset = $offset;
     $commentoptions->showcomment = $showcomment;
     $commentoptions->view = $instance->get_view();
     $feedback = ArtefactTypeComment::get_comments($commentoptions);
     $smarty = smarty_core();
     $smarty->assign('feedback', $feedback);
     if (isset($addfeedbackpopup)) {
         $smarty->assign('enablecomments', 1);
         $smarty->assign('addfeedbackpopup', $addfeedbackpopup);
     }
     $html = $smarty->fetch('blocktype:comment:comment.tpl');
     return $html;
 }
 public static function index($params)
 {
     $page = intval(Helpers::select("page", $params, 1));
     $per_page = Config::get("posts.per_page");
     $posts = DB::getAll("select * from posts " . "order by posted_at desc " . "limit :limit offset :offset", array("limit" => $per_page, "offset" => ($page - 1) * $per_page));
     View::set("posts", $posts);
     View::set("total", DB::getValue("select count(*) from posts"));
     View::set("first", ($page - 1) * $per_page + 1);
     View::set("last", min(View::get("first") + $per_page - 1, View::get("total")));
     View::set("page", $page);
     View::set("pages", ceil(View::get("total") / $per_page));
     View::set("highlight", Session::getFlash("highlight"));
     if ($page > 1 && count($posts) === 0) {
         Helpers::notFound();
     }
     View::render("post/index");
 }
function deleteview_submit(Pieform $form, $values)
{
    global $SESSION, $USER, $viewid, $groupid, $institution, $goto;
    $view = new View($viewid, null);
    if (View::can_remove_viewtype($view->get('type')) || $USER->get('admin')) {
        $view->delete();
        $SESSION->add_ok_msg(get_string('viewdeleted', 'view'));
    } else {
        $SESSION->add_error_msg(get_string('cantdeleteview', 'view'));
    }
    if ($groupid) {
        redirect('/view/groupviews.php?group=' . $groupid);
    }
    if ($institution) {
        redirect('/view/institutionviews.php?institution=' . $institution);
    }
    redirect('/view/' . $goto);
}
Example #10
0
 public function testPageTag()
 {
     Template::render('page-lookup-test.html');
     $pageTagTestLookUp = View::get('pageTagTestLookUp');
     $pageTagTestPaginate = View::get('pageTagTestPaginate');
     $this->assertTrue(is_array($pageTagTestLookUp));
     $this->assertEquals(1, count($pageTagTestLookUp));
     $this->assertTrue($pageTagTestPaginate instanceof \Disco\classes\Paginate);
     $this->assertEquals(2, $pageTagTestPaginate->totalPages);
     Template::render('page-model-test.html');
     $pageTagTestModel = View::get('pageTagTestModel');
     $pageTagTestPaginate = View::get('pageTagTestPaginate');
     $this->assertTrue(is_array($pageTagTestModel));
     $this->assertEquals(1, count($pageTagTestModel));
     $this->assertEquals('Person Two', $pageTagTestModel[0]['name']);
     $this->assertTrue($pageTagTestPaginate instanceof \Disco\classes\Paginate);
     $this->assertEquals(5, $pageTagTestPaginate->totalPages);
 }
Example #11
0
 public function __construct($path, $data, $root = "")
 {
     if ($root != "") {
         View::$root = $root;
     }
     $cache = View::get($path);
     if (!$cache) {
         $path = View::$root . $path;
         $fh = @fopen($path, "r");
         if (!$fh) {
             throw new ErrorException("Missing file '" . $path . "'.");
         }
         $this->tplFileContent = fread($fh, filesize($path));
         fclose($fh);
         View::add($path, $this->tplFileContent);
     } else {
         $this->tplFileContent = $cache;
     }
     $this->vars = $data;
 }
Example #12
0
 public static function send($view, $array, $callback)
 {
     include "../core/Associates/PHPMailer/class.phpmailer.php";
     //
     $selfmail = new self();
     $callback($selfmail);
     //
     $mail = new PHPMailer();
     //
     //
     if ($selfmail->type == "text") {
         $view2 = $view;
         $mail->IsHTML(false);
     } else {
         if ($selfmail->type == "html") {
             $view2 = View::get($view, $array);
             $mail->IsHTML(true);
         }
     }
     //
     $mail->IsSMTP();
     $mail->SMTPDebug = 1;
     $mail->SMTPAuth = true;
     $mail->SMTPSecure = Config::get("mail.encryption");
     $mail->Host = Config::get("mail.host");
     $mail->Port = Config::get("mail.port");
     $mail->Username = Config::get("mail.username");
     $mail->Password = Config::get("mail.password");
     if (is_null($selfmail->froms)) {
         $selfmail->froms = Config::get("mail.from.adresse");
     }
     $mail->SetFrom($selfmail->froms);
     $mail->Subject = $selfmail->subject;
     $mail->Body = $view2;
     //
     foreach ($selfmail->too as $key => $value) {
         $name = "";
         $maile = "";
         //
         foreach ($value as $key2 => $value2) {
             if ($key2 == "name") {
                 $name = $value2;
             } else {
                 if ($key2 == "mail") {
                     $maile = $value2;
                 }
             }
         }
         //
         if (empty($name)) {
             $mail->AddAddress($maile);
         } else {
             $mail->AddAddress($maile, $name);
         }
     }
     //
     // atachement
     if (!is_null($selfmail->atachmnt) && count($selfmail->atachmnt) > 0) {
         foreach ($selfmail->atachmnt as $key => $value) {
             $name = "";
             $filee = "";
             //
             foreach ($value as $key2 => $value2) {
                 if ($key2 == 1) {
                     $name = $value2;
                 } else {
                     if ($key2 == 0) {
                         $filee = $value2;
                     }
                 }
             }
             //
             if (empty($name)) {
                 $mail->addAttachment($filee);
             } else {
                 $mail->addAttachment($filee, $name);
             }
         }
     }
     //
     // CC
     if (!is_null($selfmail->cc)) {
         foreach ($selfmail->cc as $key => $value) {
             $mail->addCC($value);
         }
     }
     //
     // CCB
     if (!is_null($selfmail->cci)) {
         foreach ($selfmail->cci as $key => $value) {
             $mail->addBCC($value);
         }
     }
     if (!$mail->Send()) {
         self::$error = $mail->ErrorInfo;
         return false;
     } else {
         return true;
     }
 }
Example #13
0
    $views = $collection->views();
    if (empty($views)) {
        $SESSION->add_error_msg(get_string('emptycollectionnoeditaccess', 'collection'));
        redirect('/collection/views.php?id=' . $collectionid);
    }
    // Pick any old view, they all have the same access records.
    $viewid = $views['views'][0]->view;
} else {
    $viewid = param_integer('id');
}
$view = new View($viewid);
if (empty($collection)) {
    $collection = $view->get_collection();
}
define('TITLE', get_string('editaccess', 'view'));
$group = $view->get('group');
$institution = $view->get('institution');
View::set_nav($group, $institution, true);
if (!$USER->can_edit_view($view) || $view->get('owner') == "0") {
    throw new AccessDeniedException();
}
if ($group && !group_within_edit_window($group)) {
    throw new AccessDeniedException();
}
$form = array('name' => 'editaccess', 'renderer' => 'div', 'plugintype' => 'core', 'pluginname' => 'view', 'viewid' => $view->get('id'), 'userview' => (int) $view->get('owner'), 'elements' => array('id' => array('type' => 'hidden', 'value' => $view->get('id'))));
// Create checkboxes to allow the user to apply these access rules to
// any of their views/collections.
// For institution views, force edit access of one view at a time for now.  Editing multiple
// institution views requires doing some tricky stuff with the 'copy for new users/groups'
// options, and there's not much room for the 'Share' tab in the admin area anyway
if ($view->get('type') != 'profile') {
Example #14
0
/**
 * Given a view id, and a user id (defaults to currently logged in user if not
 * specified) will return wether this user is allowed to look at this view.
 *
 * @param mixed $view           viewid or View to check
 * @param integer $user_id      User trying to look at the view (defaults to
 * currently logged in user, or null if user isn't logged in)
 *
 * @returns boolean Wether the specified user can look at the specified view.
 */
function can_view_view($view, $user_id = null)
{
    global $USER, $SESSION;
    if (defined('BULKEXPORT')) {
        return true;
    }
    $now = time();
    $dbnow = db_format_timestamp($now);
    if ($user_id === null) {
        $user = $USER;
        $user_id = $USER->get('id');
    } else {
        $user = new User();
        if ($user_id) {
            try {
                $user->find_by_id($user_id);
            } catch (AuthUnknownUserException $e) {
            }
        }
    }
    $publicviews = get_config('allowpublicviews');
    $publicprofiles = get_config('allowpublicprofiles');
    // If the user is logged out and the publicviews & publicprofiles sitewide configs are false,
    // we can deny access without having to hit the database at all
    if (!$user_id && !$publicviews && !$publicprofiles) {
        return false;
    }
    require_once get_config('libroot') . 'view.php';
    if ($view instanceof View) {
        $view_id = $view->get('id');
    } else {
        $view = new View($view_id = $view);
    }
    // If the page belongs to an individual, check for individual-specific overrides
    if ($view->get('owner')) {
        $ownerobj = $view->get_owner_object();
        // Suspended user
        if ($ownerobj->suspendedctime) {
            return false;
        }
        // Probationary user (no public pages or profiles)
        // (setting these here instead of doing a return-false, so that we can do checks for
        // logged-in users later)
        require_once get_config('libroot') . 'antispam.php';
        $onprobation = is_probationary_user($ownerobj->id);
        $publicviews = $publicviews && !$onprobation;
        $publicprofiles = $publicprofiles && !$onprobation;
        // Member of an institution that prohibits public pages
        // (group views and logged in users are not affected by
        // the institution level config for public views)
        $owner = new User();
        $owner->find_by_id($ownerobj->id);
        $publicviews = $publicviews && $owner->institution_allows_public_views();
    }
    // Now that we've examined the page owner, check again for whether it can be viewed by a logged-out user
    if (!$user_id && !$publicviews && !$publicprofiles) {
        return false;
    }
    if ($user_id && $user->can_edit_view($view)) {
        return true;
    }
    // If the view's owner is suspended, deny access to the view
    if ($view->get('owner')) {
        if (!($owner = $view->get_owner_object()) || $owner->suspendedctime) {
            return false;
        }
    }
    if ($SESSION->get('mnetuser')) {
        $mnettoken = get_cookie('mviewaccess:' . $view_id);
    }
    // If the page has been marked "objectionable" admins should be able to view
    // it for review purposes.
    if ($view->is_objectionable()) {
        if ($owner = $view->get('owner')) {
            if ($user->is_admin_for_user($owner)) {
                return true;
            }
        } else {
            if ($view->get('group') && $user->get('admin')) {
                return true;
            }
        }
    }
    // Overriding start/stop dates are set by the owner to deny access
    // to users who would otherwise be allowed to see the view.  However,
    // for some kinds of access (e.g. objectionable content, submitted
    // views), we have to override the override and let the logged in
    // user see it anyway.  So we can't return false now, we have to wait
    // till we find out what kind of view_access record is being used.
    $overridestart = $view->get('startdate');
    $overridestop = $view->get('stopdate');
    $allowedbyoverride = (empty($overridestart) || $overridestart < $dbnow) && (empty($overridestop) || $overridestop > $dbnow);
    $access = View::user_access_records($view_id, $user_id);
    if (empty($access)) {
        return false;
    }
    foreach ($access as &$a) {
        if ($a->accesstype == 'public' && $allowedbyoverride) {
            if ($publicviews) {
                return true;
            } else {
                if ($publicprofiles && $view->get('type') == 'profile') {
                    return true;
                }
            }
        } else {
            if ($a->token && ($allowedbyoverride || !$a->visible)) {
                $usertoken = get_cookie('viewaccess:' . $view_id);
                if ($a->token == $usertoken && $publicviews) {
                    return true;
                }
                if (!empty($mnettoken) && $a->token == $mnettoken) {
                    $mnetviewlist = $SESSION->get('mnetviewaccess');
                    if (empty($mnetviewlist)) {
                        $mnetviewlist = array();
                    }
                    $mnetviewlist[$view_id] = true;
                    $SESSION->set('mnetviewaccess', $mnetviewlist);
                    return true;
                }
                // Don't bother to pull the collection out unless the user actually
                // has some collection access cookies.
                if ($ctokens = get_cookies('caccess:')) {
                    $cid = $view->collection_id();
                    if ($cid && isset($ctokens[$cid]) && $a->token == $ctokens[$cid]) {
                        return true;
                    }
                }
            } else {
                if ($user_id) {
                    if ($a->accesstype == 'friends') {
                        $owner = $view->get('owner');
                        if (!get_field_sql('
                    SELECT COUNT(*) FROM {usr_friend} f WHERE (usr1=? AND usr2=?) OR (usr1=? AND usr2=?)', array($owner, $user_id, $user_id, $owner))) {
                            continue;
                        }
                    } else {
                        if ($a->institution) {
                            // Check if user belongs to the allowed institution
                            if (!in_array($a->institution, array_keys($user->get('institutions')))) {
                                continue;
                            }
                        }
                    }
                    if (!$allowedbyoverride && $a->visible) {
                        continue;
                    }
                    // The view must have loggedin access, user access for the user
                    // or group/role access for one of the user's groups
                    return true;
                }
            }
        }
    }
    return false;
}
Example #15
0
function edit_annotation_feedback_submit(Pieform $form, $values)
{
    global $viewid, $annotationfeedback, $annotation, $SESSION, $goto, $USER;
    db_begin();
    $annotationfeedback->set('description', $values['message']);
    require_once get_config('libroot') . 'view.php';
    $view = new View($viewid);
    $owner = $view->get('owner');
    $group = $annotationfeedback->get('group');
    $oldispublic = !$annotationfeedback->get('private');
    $approvecomments = $view->get('approvecomments');
    // We need to figure out what to set the 'requestpublic' field in the artefact_annotation_feedback table.
    // Then, set who is requesting to make it public - if the public flag has changed.
    if (!empty($group) && ($approvecomments || !$approvecomments && $view->user_comments_allowed($USER) == 'private') && $values['ispublic'] && !$USER->can_edit_view($view) && $values['ispublic'] != $oldispublic) {
        // This annotation belongs to a group - but this shouldn't really happen - keeping in case
        // we allow annotations in group views.
        // 1. If approvecomments on this view is switched on and
        //    the author of the feedback wants to make it public and
        //    the author of the feeback can't edit the group view and
        //    the auther of the feedback has changed the public setting,
        // the owner of the view needs to approve the feedback before it's made public.
        // 2. If approvecomments on this view is switched off and
        //    the access (for the author of the feedback) of the view forces private comments and
        //    the author of the feeback can't edit the view and
        //    the auther of the feedback has changed the public setting,
        // the owner of the view needs to approve the feedback before it's made public.
        // The author of the feedback wants to make the feedback public.
        $annotationfeedback->set('requestpublic', 'author');
    } else {
        if (($approvecomments || !$approvecomments && $view->user_comments_allowed($USER) == 'private') && $values['ispublic'] && !empty($owner) && $owner != $annotationfeedback->get('author') && $values['ispublic'] != $oldispublic) {
            // 1. If approvecomments on this view is switched on and
            //    the author of the feedback would like to make this public and
            //    the author of the feeback is not the owner of the view and
            //    the auther of the feedback has changed the public setting,
            // the owner of the view needs to approve the feedback before it's made public.
            // 2. If approvecomments on this view is switched off and
            //    the access (for the author of the feedback) of the view forces private feedback and
            //    the author of the feeback is not the owner of the view and
            //    the auther of the feedback has changed the public setting,
            // the owner of the view needs to approve the feedback before it's made public.
            // The author of the feedback wants to make the feedback public.
            $annotationfeedback->set('requestpublic', 'author');
        } else {
            // Otherwise, the owner of the feedback is editing the feedback.
            // Set the privacy setting of the feedback - based on the 'ispublic' flag set by the user.
            // And, clear the request to make the feedback public.
            $annotationfeedback->set('private', 1 - (int) $values['ispublic']);
            $annotationfeedback->set('requestpublic', null);
        }
    }
    $annotationfeedback->commit();
    require_once 'activity.php';
    $data = (object) array('annotationfeedbackid' => $annotationfeedback->get('id'), 'annotationid' => $annotation->get('id'), 'viewid' => $viewid, 'artefactid' => '');
    activity_occurred('annotationfeedback', $data, 'artefact', 'annotation');
    if ($annotationfeedback->get('requestpublic') == 'author') {
        if (!empty($owner)) {
            edit_annotation_feedback_notify($view, $annotationfeedback->get('author'), $owner);
        } else {
            if (!empty($group)) {
                $group_admins = group_get_admin_ids($group);
                // TODO: need to notify the group admins bug #1197197
            }
        }
    }
    db_commit();
    $SESSION->add_ok_msg(get_string('annotationfeedbackupdated', 'artefact.annotation'));
    redirect($goto);
}
Example #16
0
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
 *
 */
// TODO fix title of this page
// TODO check security of this page
define('INTERNAL', 1);
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once 'pieforms/pieform.php';
require_once 'view.php';
require_once get_config('libroot') . 'group.php';
define('TITLE', get_string('changemyviewlayout', 'view'));
$id = param_integer('id');
$new = param_boolean('new');
$category = param_alpha('c', '');
$view = new View($id);
$numcolumns = $view->get('numcolumns');
$currentlayout = $view->get('layout');
$back = !$USER->get_account_preference('addremovecolumns');
$group = $view->get('group');
$institution = $view->get('institution');
View::set_nav($group, $institution);
if (!$USER->can_edit_view($view)) {
    throw new AccessDeniedException();
}
// if not set, use equal width layout for that number of columns
if (!$currentlayout) {
    $currentlayout = $numcolumns == 2 ? 1 : ($numcolumns == 3 ? 4 : 7);
}
if ($numcolumns > 1 && $numcolumns < 5) {
    $layouts = get_records_array('view_layout', 'columns', $numcolumns);
    $options = array();
Example #17
0
 /**
  * Implementation of the actionAfter hook
  */
 public function actionAfter()
 {
     \View::set('helloWorld', \View::get('helloWorld') . ' This does not work.');
 }
 /**
  * @param array $data Parameters:
  *                    - view (int)
  *                    - oldusers (array of user IDs)
  */
 public function __construct($data, $cron = false)
 {
     parent::__construct($data, $cron);
     if (!($viewinfo = new View($this->view))) {
         if (!empty($this->cron)) {
             // probably deleted already
             return;
         }
         throw new ViewNotFoundException(get_string('viewnotfound', 'error', $this->view));
     }
     $this->url = $viewinfo->get_url(false);
     $this->users = array_diff_key(activity_get_viewaccess_users($this->view), $this->oldusers);
     if ($viewinfo->get_collection()) {
         $this->incollection = true;
         $this->title = $viewinfo->get_collection()->get('name');
         $this->add_urltext(array('key' => 'Collection', 'section' => 'collection'));
     } else {
         $this->title = $viewinfo->get('title');
         $this->add_urltext(array('key' => 'View', 'section' => 'view'));
     }
     $this->ownername = $viewinfo->formatted_owner();
 }
Example #19
0
    if ($usertoken) {
        if (!($viewid = get_view_from_token($usertoken, true))) {
            throw new AccessDeniedException(get_string('accessdenied', 'error'));
        }
    } else {
        if ($pageurl = param_alphanumext('page', null)) {
            if ($profile = param_alphanumext('profile', null)) {
                $view = new View(array('urlid' => $pageurl, 'ownerurlid' => $profile));
            } else {
                if ($homepage = param_alphanumext('homepage', null)) {
                    $view = new View(array('urlid' => $pageurl, 'groupurlid' => $homepage));
                } else {
                    throw new ViewNotFoundException(get_string('viewnotfoundexceptiontitle', 'error'));
                }
            }
            $viewid = $view->get('id');
        } else {
            $viewid = param_integer('id');
        }
    }
}
$new = param_boolean('new');
$showmore = param_boolean('showmore');
if (!$showmore) {
    $showmore = 0;
}
if (!isset($view)) {
    $view = new View($viewid);
}
if (!can_view_view($view)) {
    $errorstr = param_integer('objection', null) ? get_string('accessdeniedobjection', 'error') : get_string('accessdenied', 'error');
Example #20
0
 /**
  * Get variable from local template vars, or from View
  * modify it by modifiers and return result value
  * $name should be like `value` or `object.propertyName`
  *
  * @param string $name
  * @return mixed
  */
 public function getvar($name)
 {
     // extract modififiers
     $modifiers = null;
     if (strpos($name, '|') !== false) {
         $name = explode('|', $name);
         $modifiers = array_slice($name, 1);
         $name = reset($name);
     }
     // find path
     $path = explode('.', $name);
     $start = reset($path);
     $root = isset($this->vars[$start]) ? $this->vars[$start] : View::get($start);
     // get value
     $value = '';
     if (count($path) > 1 and is_object($root)) {
         $value = $root->{$path[1]};
     } elseif (count($path) > 1 and is_array($root)) {
         $value = isset($root[$path[1]]) ? $root[$path[1]] : null;
     } else {
         $value = $root;
     }
     // apply modifiers
     if (is_array($modifiers)) {
         foreach ($modifiers as $mod) {
             $method = $mod . 'Modifier';
             if (is_callable([$this, $method])) {
                 $value = $this->{$method}($value);
             }
         }
     }
     return $value;
 }
Example #21
0
 public static function echoCount($varName)
 {
     echo count(View::get($varName));
 }
Example #22
0
require_once 'view.php';
$id = param_integer('id');
// view addition/displayorder values
$view = param_integer('view', 0);
$direction = param_variable('direction', '');
$collection = new Collection($id);
if (!$USER->can_edit_collection($collection)) {
    throw new AccessDeniedException(get_string('canteditcollection', 'collection'));
}
$sesskey = $USER->get('sesskey');
$inlinejs = '';
if ($accesschanged = $SESSION->get('pageaccesschanged')) {
    $alertstr = get_string('viewsaddedaccesschanged', 'collection');
    foreach ($accesschanged as $viewid) {
        $changedview = new View($viewid);
        $alertstr .= " " . json_encode($changedview->get('title')) . ",";
    }
    $alertstr = substr($alertstr, 0, -1) . '.';
    $alertstr = get_string('viewsaddedtocollection1', 'collection', $SESSION->get('pagesadded')) . ' ' . $alertstr;
    $inlinejs = <<<EOF
jQuery(function(\$) {
    var message = \$('<div id="changestatusline" class="warning"><div>{$alertstr}</div></div>');
    \$('#messages').append(message);
});
EOF;
    $SESSION->set('pageaccesschanged', false);
    $SESSION->set('pagesadded', false);
}
$owner = $collection->get('owner');
$groupid = $collection->get('group');
$institutionname = $collection->get('institution');
Example #23
0
 /**
  * Copy the description of the view template
  * and its embedded image artefacts
  *
  * @param View $template the view template
  * @param array &$artefactcopies the artefact mapping
  * @return string updated description
  */
 private function copy_description(View $template, array &$artefactcopies)
 {
     $new_description = $template->get('description');
     if (!empty($new_description) && strpos($new_description, 'artefact/file/download.php?file=') !== false) {
         // Get all possible embedded artefacts
         $artefactids = array_unique(artefact_get_references_in_html($new_description));
         // Copy these image artefacts
         foreach ($artefactids as $aid) {
             try {
                 $a = artefact_instance_from_id($aid);
             } catch (Exception $e) {
                 continue;
             }
             if ($a instanceof ArtefactTypeImage) {
                 $artefactcopies[$aid] = (object) array('oldid' => $aid, 'oldparent' => $a->get('parent'));
                 $artefactcopies[$aid]->newid = $a->copy_for_new_owner($this->get('owner'), $this->get('group'), $this->get('institution'));
             }
         }
         // Update the image urls in the description
         if (!empty($artefactcopies)) {
             $regexp = array();
             $replacetext = array();
             foreach ($artefactcopies as $oldaid => $newobj) {
                 // Change the old image id to the new one
                 $regexp[] = '#<img([^>]+)src=("|\\")' . preg_quote(get_config('wwwroot') . 'artefact/file/download.php?file=' . $oldaid) . '(&|&amp;)embedded=1([^"]*)"#';
                 $replacetext[] = '<img$1src="' . get_config('wwwroot') . 'artefact/file/download.php?file=' . $newobj->newid . '&embedded=1"';
             }
             $new_description = preg_replace($regexp, $replacetext, $new_description);
         }
     }
     return $new_description;
 }
Example #24
0
function viewskin_submit(Pieform $form, $values)
{
    global $SESSION;
    $view = new View($values['view']);
    $new = $values['new'];
    $view->set('skin', $values['skin']);
    $view->commit();
    handle_event('saveview', $view->get('id'));
    $SESSION->add_ok_msg(get_string('viewskinchanged', 'skin'));
    redirect('/view/view.php?id=' . $view->get('id') . ($new ? '&new=1' : ''));
}
Example #25
0
function add_annotation_feedback_form_submit(Pieform $form, $values)
{
    global $USER;
    $data = (object) array('title' => get_string('Annotation', 'artefact.annotation'), 'description' => $values['message'], 'onannotation' => $values['annotationid']);
    // hidden fields.
    $artefactid = $values['artefactid'];
    $viewid = $values['viewid'];
    $blockid = $values['blockid'];
    if ($artefactid) {
        $artefact = artefact_instance_from_id($artefactid);
        $data->artefact = $artefactid;
        $data->owner = $artefact->get('owner');
        $data->group = $artefact->get('group');
        $data->institution = $artefact->get('institution');
    } else {
        if ($viewid) {
            $view = new View($viewid);
            $data->view = $viewid;
            $data->owner = $view->get('owner');
            $data->group = $view->get('group');
            $data->institution = $view->get('institution');
        }
    }
    if ($author = $USER->get('id')) {
        $anonymous = false;
        $data->author = $author;
    } else {
        $anonymous = true;
        $data->authorname = $values['authorname'];
    }
    if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $data->private = 1;
        $data->requestpublic = 'author';
        $moderated = true;
    } else {
        $data->private = (int) (!$values['ispublic']);
        $moderated = false;
    }
    $private = $data->private;
    $annotationfeedback = new ArtefactTypeAnnotationfeedback(0, $data);
    $annotation = new ArtefactTypeAnnotation($values['annotationid']);
    db_begin();
    $annotationfeedback->commit();
    $url = $annotation->get_view_url($view->get('id'), true, false);
    $goto = get_config('wwwroot') . $url;
    if (isset($data->requestpublic) && $data->requestpublic === 'author' && $data->owner) {
        $arg = $author ? display_name($USER, null, true) : $data->authorname;
        $moderatemsg = (object) array('subject' => false, 'message' => false, 'strings' => (object) array('subject' => (object) array('key' => 'makepublicrequestsubject', 'section' => 'artefact.annotation', 'args' => array()), 'message' => (object) array('key' => 'makepublicrequestbyauthormessage', 'section' => 'artefact.annotation', 'args' => array(hsc($arg))), 'urltext' => (object) array('key' => 'Annotation', 'section' => 'artefact.annotation')), 'users' => array($data->owner), 'url' => $url);
    }
    require_once 'activity.php';
    $data = (object) array('annotationfeedbackid' => $annotationfeedback->get('id'), 'annotationid' => $values['annotationid'], 'viewid' => $viewid, 'artefactid' => $artefactid);
    activity_occurred('annotationfeedback', $data, 'artefact', 'annotation');
    if (isset($moderatemsg)) {
        activity_occurred('maharamessage', $moderatemsg);
    }
    db_commit();
    if (param_exists('offset')) {
        $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
        $options->showcomment = 'last';
        $options->artefact = $artefactid;
        $options->view = $viewid;
        $options->annotation = $values['annotationid'];
        $options->block = $blockid;
        $newlist = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);
    } else {
        $newlist = null;
    }
    // If you're anonymous and your message is moderated or private, then you won't
    // be able to tell what happened to it. So we'll provide some more explanation in
    // the feedback message.
    if ($anonymous && $moderated) {
        $message = get_string('annotationfeedbacksubmittedmoderatedanon', 'artefact.annotation');
    } else {
        if ($anonymous && $private) {
            $message = get_string('annotationfeedbacksubmittedprivateanon', 'artefact.annotation');
        } else {
            $message = get_string('annotationfeedbacksubmitted', 'artefact.annotation');
        }
    }
    $form->reply(PIEFORM_OK, array('message' => $message, 'goto' => $goto, 'data' => $newlist));
}
Example #26
0
 public static function instance_config_form(BlockInstance $instance)
 {
     global $USER;
     safe_require('artefact', 'blog');
     $configdata = $instance->get('configdata');
     require_once get_config('libroot') . 'view.php';
     $view = new View($instance->get('view'));
     $institution = $view->get('institution');
     $group = $view->get('group');
     if (!empty($configdata['artefactid'])) {
         $blog = $instance->get_artefact_instance($configdata['artefactid']);
     }
     $elements = array();
     // If the blog in this block is owned by the owner of the View, then
     // the block can be configured. Otherwise, the blog was copied in from
     // another View. We won't confuse users by asking them to choose a blog
     // to put in this block, when the one that is currently in it isn't
     // choosable.
     //
     // Note: the owner check will have to change when we do group/site
     // blogs
     if (empty($configdata['artefactid']) || ArtefactTypeBlog::can_edit_blog($blog, $institution, $group)) {
         $where = array('blog');
         $sql = "SELECT a.id FROM {artefact} a\n                    WHERE a.artefacttype = ?";
         if ($institution) {
             $sql .= " AND a.institution = ?";
             $where[] = $institution;
         } else {
             if ($group) {
                 $sql .= " AND a.group = ?";
                 $where[] = $group;
             } else {
                 $sql .= " AND a.owner = ?";
                 $where[] = $USER->get('id');
             }
         }
         $blogids = get_column_sql($sql, $where);
         $elements[] = self::artefactchooser_element(isset($configdata['artefactid']) ? $configdata['artefactid'] : null, $blogids);
         $elements['count'] = array('type' => 'text', 'title' => get_string('postsperpage', 'blocktype.blog/blog'), 'defaultvalue' => isset($configdata['count']) ? $configdata['count'] : 5, 'size' => 3);
         $elements[] = PluginArtefactBlog::block_advanced_options_element($configdata, 'blog');
     } else {
         $elements[] = array('type' => 'html', 'name' => 'notice', 'value' => '<div class="metadata">' . get_string('blogcopiedfromanotherview', 'artefact.blog', get_string('Blog', 'artefact.blog')) . '</div>');
     }
     return $elements;
 }
/**
 * Return the title, type and id of the item based on which is more important
 *
 * Takes an array containing ids on either or all of these items with ranking
 * preference in this order:
 * - collection
 * - view
 * and returns the title, type, and id of which ever one is present and is highest ranked
 *
 * @param array  $item An array containing any or all of 'collection', 'view' ids
 * @return array The title/url/type/id information on the most senior one found.
 */
function get_export_contentdata($item)
{
    // first make sure we have an array
    if (is_object($item)) {
        $item = (array) $item;
    }
    $record = new stdClass();
    $record->title = '';
    $record->url = null;
    $record->type = null;
    $record->id = 0;
    if (!empty($item['collection'])) {
        require_once 'collection.php';
        $collection = new Collection($item['collection']);
        $views = $collection->get('views');
        $record->title = $collection->get('name');
        $record->url = $views['views'][0]->fullurl;
        $record->type = 'collection';
        $record->id = $item['collection'];
    } else {
        if (!empty($item['view'])) {
            require_once 'view.php';
            $view = new View($item['view']);
            $record->title = $view->get('title');
            $record->url = get_config('wwwroot') . 'view/view.php?id=' . $item['view'];
            $record->type = 'view';
            $record->id = $item['view'];
        }
    }
    return $record;
}
Example #28
0
 public static function get_blocktypes_for_category($category, View $view)
 {
     $sql = 'SELECT bti.name, bti.artefactplugin
         FROM {blocktype_installed} bti
         JOIN {blocktype_installed_category} btic ON btic.blocktype = bti.name
         JOIN {blocktype_installed_viewtype} btiv ON btiv.blocktype = bti.name
         WHERE btic.category = ? AND bti.active = 1 AND btiv.viewtype = ?
         ORDER BY btic.sortorder, bti.name';
     if (!($bts = get_records_sql_array($sql, array($category, $view->get('type'))))) {
         return false;
     }
     $blocktypes = array();
     if (function_exists('local_get_allowed_blocktypes')) {
         $localallowed = local_get_allowed_blocktypes($category, $view);
     }
     foreach ($bts as $bt) {
         $namespaced = blocktype_single_to_namespaced($bt->name, $bt->artefactplugin);
         if (isset($localallowed) && is_array($localallowed) && !in_array($namespaced, $localallowed)) {
             continue;
         }
         safe_require('blocktype', $namespaced);
         // Note for later: this is Blocktype::allowed_in_view, which
         // returns true if the blocktype should be insertable into the
         // given view.
         // e.g. for blogs it returns false when view owner is not set,
         // because blogs can't be inserted into group views.
         // This could be different from whether a blockinstance is allowed
         // to be copied into a View (see the other place in this file where
         // allowed_in_view is called)
         //
         // Note also that if we want templates to be able to have all
         // blocktypes, we can add $view->get('template') here as part of
         // the condition, and also to View::addblocktype and
         // View::get_category_data
         if (call_static_method(generate_class_name('blocktype', $namespaced), 'allowed_in_view', $view)) {
             $blocktypes[] = array('name' => $bt->name, 'title' => call_static_method(generate_class_name('blocktype', $namespaced), 'get_title'), 'description' => call_static_method(generate_class_name('blocktype', $namespaced), 'get_description'), 'singleonly' => call_static_method(generate_class_name('blocktype', $namespaced), 'single_only'), 'artefactplugin' => $bt->artefactplugin, 'thumbnail_path' => get_config('wwwroot') . 'thumb.php?type=blocktype&bt=' . $bt->name . (!empty($bt->artefactplugin) ? '&ap=' . $bt->artefactplugin : ''));
         }
     }
     return $blocktypes;
 }
Example #29
0
 /**
  * Blogpost blocktype is only allowed in personal views, because currently
  * there's no such thing as group/site blogs
  */
 public static function allowed_in_view(View $view)
 {
     return $view->get('owner') != null;
 }
Example #30
0
/**
 * Creates a group.
 *
 * All group creation should be done through this function, as the
 * implementation of group creation may change over time.
 *
 * @param array $data Data required to create the group. The following
 * key/value pairs can be specified:
 *
 * - name: The group name [required, must be unique]
 * - description: The group description [optional, defaults to empty string]
 * - grouptype: The grouptype for the new group. Must be an installed grouptype.
 * - open (jointype): anyone can join the group
 * - controlled (jointype): admin adds members; members cannot leave the group
 * - request: allows membership requests
 * - ctime: The unix timestamp of the time the group will be recorded as having
 *          been created. Defaults to the current time.
 * - members: Array of users who should be in the group, structured like this:
 *            array(
 *                userid => role,
 *                userid => role,
 *                ...
 *            )
 * @return int The ID of the created group
 */
function group_create($data)
{
    if (!is_array($data)) {
        throw new InvalidArgumentException("group_create: data must be an array, see the doc comment for this " . "function for details on its format");
    }
    if (!isset($data['name'])) {
        throw new InvalidArgumentException("group_create: must specify a name for the group");
    }
    if (get_records_sql_array('SELECT id FROM {group} WHERE LOWER(TRIM(name)) = ?', array(strtolower(trim($data['name']))))) {
        throw new UserException(get_string('groupalreadyexists', 'group') . ': ' . $data['name']);
    }
    if (!isset($data['grouptype']) || !in_array($data['grouptype'], group_get_grouptypes())) {
        throw new InvalidArgumentException("group_create: grouptype specified must be an installed grouptype");
    }
    safe_require('grouptype', $data['grouptype']);
    if (!empty($data['open'])) {
        if (!empty($data['controlled'])) {
            throw new InvalidArgumentException("group_create: a group cannot have both open and controlled membership");
        }
        if (!empty($data['request'])) {
            throw new InvalidArgumentException("group_create: open-membership groups don't accept membership requests");
        }
        $jointype = 'open';
    } else {
        if (!empty($data['controlled'])) {
            $jointype = 'controlled';
        } else {
            $jointype = 'approve';
        }
    }
    if (isset($data['jointype'])) {
        log_warn("group_create: ignoring supplied jointype");
    }
    if (!isset($data['ctime'])) {
        $data['ctime'] = time();
    }
    $data['ctime'] = db_format_timestamp($data['ctime']);
    $data['public'] = isset($data['public']) ? intval($data['public']) : 0;
    $data['hidden'] = isset($data['hidden']) ? intval($data['hidden']) : 0;
    $data['hidemembers'] = isset($data['hidemembers']) ? intval($data['hidemembers']) : 0;
    $data['hidemembersfrommembers'] = isset($data['hidemembersfrommembers']) ? intval($data['hidemembersfrommembers']) : 0;
    $data['groupparticipationreports'] = isset($data['groupparticipationreports']) ? intval($data['groupparticipationreports']) : 0;
    $data['usersautoadded'] = isset($data['usersautoadded']) ? intval($data['usersautoadded']) : 0;
    $data['quota'] = get_config_plugin('artefact', 'file', 'defaultgroupquota');
    if (!empty($data['invitefriends']) && !empty($data['suggestfriends'])) {
        throw new InvalidArgumentException("group_create: a group cannot enable both invitefriends and suggestfriends");
    }
    $data['invitefriends'] = isset($data['invitefriends']) ? intval($data['invitefriends']) : 0;
    $data['suggestfriends'] = isset($data['suggestfriends']) ? intval($data['suggestfriends']) : 0;
    if (isset($data['shortname']) && strlen($data['shortname'])) {
        // This is a group whose details and membership can be updated automatically, using a
        // webservice api or possibly csv upload.
        // On updates to this group, it will be identified using the institution and shortname
        // which must be unique.
        // The $USER object will be set to someone with at least institutional admin permission.
        global $USER;
        if (empty($data['institution'])) {
            throw new SystemException("group_create: a group with a shortname must have an institution; shortname: " . $data['shortname']);
        }
        if (!$USER->can_edit_institution($data['institution'])) {
            throw new AccessDeniedException("group_create: cannot create a group in this institution");
        }
        if (!preg_match('/^[a-zA-Z0-9_.-]{2,255}$/', $data['shortname'])) {
            $message = get_string('invalidshortname', 'group') . ': ' . $data['shortname'];
            $message .= "\n" . get_string('shortnameformat', 'group');
            throw new UserException($message);
        }
        if (record_exists('group', 'shortname', $data['shortname'], 'institution', $data['institution'])) {
            throw new UserException('group_create: group with shortname ' . $data['shortname'] . ' and institution ' . $data['institution'] . ' already exists');
        }
        if (empty($data['members'])) {
            $data['members'] = array($USER->get('id') => 'admin');
        }
    } else {
        if (!empty($data['institution'])) {
            throw new SystemException("group_create: group institution only available for api-controlled groups");
        }
        $data['shortname'] = null;
    }
    if (get_config('cleanurls') && (!isset($data['urlid']) || strlen($data['urlid']) == 0)) {
        $data['urlid'] = generate_urlid($data['name'], get_config('cleanurlgroupdefault'), 3, 30);
        $data['urlid'] = group_get_new_homepage_urlid($data['urlid']);
    }
    if (!is_array($data['members']) || count($data['members']) == 0) {
        throw new InvalidArgumentException("group_create: at least one member must be specified for adding to the group");
    }
    if (!isset($data['submittableto'])) {
        $data['submittableto'] = $data['grouptype'] != 'standard';
    }
    if (!isset($data['editroles'])) {
        $data['editroles'] = $data['grouptype'] == 'standard' ? 'all' : 'notmember';
    } else {
        if (!in_array($data['editroles'], array_keys(group_get_editroles_options()))) {
            throw new InvalidArgumentException("group_create: invalid option for page editroles setting");
        }
    }
    if (!isset($data['editwindowstart'])) {
        $data['editwindowstart'] = null;
    }
    if (!isset($data['editwindowend'])) {
        $data['editwindowend'] = null;
    }
    if (!isset($data['sendnow'])) {
        $data['sendnow'] = null;
    }
    db_begin();
    $id = insert_record('group', (object) array('name' => $data['name'], 'description' => isset($data['description']) ? $data['description'] : null, 'urlid' => isset($data['urlid']) ? $data['urlid'] : null, 'grouptype' => $data['grouptype'], 'category' => isset($data['category']) ? intval($data['category']) : null, 'jointype' => $jointype, 'ctime' => $data['ctime'], 'mtime' => $data['ctime'], 'public' => $data['public'], 'usersautoadded' => $data['usersautoadded'], 'quota' => $data['quota'], 'institution' => !empty($data['institution']) ? $data['institution'] : null, 'shortname' => $data['shortname'], 'request' => isset($data['request']) ? intval($data['request']) : 0, 'submittableto' => intval($data['submittableto']), 'allowarchives' => !empty($data['submittableto']) && !empty($data['allowarchives']) ? intval($data['allowarchives']) : 0, 'editroles' => $data['editroles'], 'hidden' => $data['hidden'], 'hidemembers' => $data['hidemembers'], 'hidemembersfrommembers' => $data['hidemembersfrommembers'], 'groupparticipationreports' => $data['groupparticipationreports'], 'invitefriends' => $data['invitefriends'], 'suggestfriends' => $data['suggestfriends'], 'editwindowstart' => $data['editwindowstart'], 'editwindowend' => $data['editwindowend'], 'sendnow' => isset($data['sendnow']) ? $data['sendnow'] : null, 'viewnotify' => isset($data['viewnotify']) ? $data['viewnotify'] : null, 'feedbacknotify' => isset($data['feedbacknotify']) ? $data['feedbacknotify'] : null), 'id', true);
    foreach ($data['members'] as $userid => $role) {
        insert_record('group_member', (object) array('group' => $id, 'member' => $userid, 'role' => $role, 'ctime' => $data['ctime']));
    }
    // Copy views for the new group
    $templates = get_column('view_autocreate_grouptype', 'view', 'grouptype', $data['grouptype']);
    $templates = get_records_sql_array("\n        SELECT v.id, v.title, v.description\n        FROM {view} v\n        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id\n        LEFT JOIN {collection_view} cv ON v.id = cv.view\n        WHERE vag.grouptype = 'standard'\n            AND cv.view IS NULL", array());
    if ($templates) {
        require_once get_config('libroot') . 'view.php';
        foreach ($templates as $template) {
            list($view) = View::create_from_template(array('group' => $id, 'title' => $template->title, 'description' => $template->description), $template->id, null, false);
            $view->set_access(array(array('type' => 'group', 'id' => $id, 'startdate' => null, 'stopdate' => null, 'role' => null)));
        }
    }
    // Copy collections for the new group
    $templates = get_records_sql_array("\n        SELECT DISTINCT c.id, c.name\n        FROM {view} v\n        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id\n        INNER JOIN {collection_view} cv ON v.id = cv.view\n        INNER JOIN {collection} c ON cv.collection = c.id\n        WHERE vag.grouptype = ?", array($data['grouptype']));
    if ($templates) {
        require_once 'collection.php';
        foreach ($templates as $template) {
            Collection::create_from_template(array('group' => $id), $template->id, null, false, true);
        }
    }
    $data['id'] = $id;
    // install the homepage
    if ($t = get_record('view', 'type', 'grouphomepage', 'template', 1, 'owner', 0)) {
        require_once 'view.php';
        $template = new View($t->id, (array) $t);
        list($homepage) = View::create_from_template(array('group' => $id, 'title' => $template->get('title'), 'description' => $template->get('description'), 'type' => 'grouphomepage'), $t->id, 0, false);
    }
    insert_record('view_access', (object) array('view' => $homepage->get('id'), 'accesstype' => $data['public'] ? 'public' : 'loggedin', 'ctime' => db_format_timestamp(time())));
    handle_event('creategroup', $data);
    db_commit();
    return $id;
}