editlayout.php 41.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

/*
 * Created by De Chiara Antonella
 * Eticeo Santé (http://eticeo.fr)
 */

define('INTERNAL', 1);
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'view');
define('SECTION_PAGE', 'editlayout');

require_once(dirname(dirname(__FILE__)) . '/init.php');
14
require_once('skin.php');
15
16
17
18
19
require_once('view.php');
require_once(get_config('libroot') . 'group.php');
require_once(get_config('libroot') . 'layoutpreviewimage.php');
require_once(get_config('docroot') . 'blocktype/lib.php');
require_once(get_config('libroot') . 'view.php');
20
safe_require('artefact', 'file');
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$id = param_integer('id', false);
$new = param_boolean('new', false);

if ($new && $id === false) {
    // Use the site default portfolio page to create a new page
    // cribbed from createview_submit()
    $sitedefaultviewid = get_field('view', 'id', 'institution', 'mahara', 'template', View::SITE_TEMPLATE, 'type', 'portfolio');
    if (!empty($sitedefaultviewid)) {
        $artefactcopies = array();
        $values = array();
        $groupid = param_integer('group', 0);
        $institutionname = param_alphanum('institution', false);
        if (!empty($groupid)) {
            $values['group'] = $groupid;
        }
        else if (!empty($institutionname)) {
            $values['institution'] = $institutionname;
        }
40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        list($view, $template, $copystatus) = View::create_from_template($values, $sitedefaultviewid, null, true, false, $artefactcopies);
        if (isset($copystatus['quotaexceeded'])) {
            $SESSION->add_error_msg(get_string('viewcreatewouldexceedquota', 'view'));
            redirect(get_config('wwwroot') . 'view/index.php');
        }
    }
    else {
         throw new ConfigSanityException(get_string('viewtemplatenotfound', 'error'));
    }

    $goto = get_config('wwwroot') . 'view/editlayout.php?new=1&id=' . $view->get('id');
    if (!empty($values)) {
        $goto .= '&' . http_build_query($values);
    }
    redirect($goto);
}

$view = new View($id);
59
$viewid = $view->get('id'); // for tinymce editor
60
define('TITLE', $view->get('title'));
61
62
63
64
65
define('SUBSECTIONHEADING', TITLE);

if (!$USER->can_edit_view($view)) {
    throw new AccessDeniedException();
}
66

67
68
69
70
$issiteview = $view->get('institution') == 'mahara';
$issitetemplate = ($view->get('template') == View::SITE_TEMPLATE ? true : false);
$canedittitle = $view->can_edit_title();
$canuseskins = !$issitetemplate && can_use_skins(null, false, $issiteview);
71

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// If the view has been submitted, disallow editing
if ($view->is_submitted()) {
    $submittedto = $view->submitted_to();
    throw new AccessDeniedException(get_string('canteditsubmitted', 'view', $submittedto['name']));
}

$group = $view->get('group');
$institution = $view->get('institution');
$view->set_edit_nav();
$view->set_user_theme();

// Clean urls are only available for portfolio views owned by groups or users who already
// have their own clean profiles or group homepages.
if ($urlallowed = get_config('cleanurls') && $view->get('type') == 'portfolio' && !$institution) {
    if ($group) {
        $groupdata = get_record('group', 'id', $group);
        if ($urlallowed = !is_null($groupdata->urlid) && strlen($groupdata->urlid)) {
            $cleanurlbase = group_homepage_url($groupdata) . '/';
        }
    }
    else {
        $userurlid = $USER->get('urlid');
        if ($urlallowed = !is_null($userurlid) && strlen($userurlid)) {
            $cleanurlbase = profile_url($USER) . '/';
        }
    }
}

100
101
if ($group && !group_within_edit_window($group)) {
    throw new AccessDeniedException();
102
103
}

104
105
106
107
108
$state = get_string('settings', 'view');

$pieformname = 'settings';
list($form, $inlinejavascript) = create_settings_pieform();

109
$javascript = array('jquery','js/jquery/jquery-ui/js/jquery-ui.min.js');
110
111
$stylesheets[] = '<link rel="stylesheet" type="text/css" href="' . append_version_number(get_config('wwwroot') . 'js/jquery/jquery-ui/css/smoothness/jquery-ui.min.css') . '">';

112
$smarty = smarty($javascript, $stylesheets, array('view' => array('Row', 'rownr')), array('sidebars' => false));
113
114
115
116
117
118

$smarty->assign('INLINEJAVASCRIPT', $inlinejavascript);
$smarty->assign('form', $form);
$smarty->assign('viewid', $view->get('id'));
$smarty->assign('viewtype', $view->get('type'));
$smarty->assign('viewtitle', $view->get('title'));
119
120
$smarty->assign('edittitle', $canedittitle);
$smarty->assign('canuseskins', $canuseskins);
121
$smarty->assign('displaylink', $view->get_url());
122
123
$smarty->assign('issiteview', $issiteview);
$smarty->assign('issitetemplate', $issitetemplate);
124
$smarty->assign('PAGEHEADING', $state);
125
126
127
128
$returnto = $view->get_return_to_url_and_title();
$smarty->assign('url', $returnto['url']);
$smarty->assign('title', $returnto['title']);

129
$smarty->display('view/editlayout.tpl');
130

131
function create_settings_pieform() {
132
133
    global $view, $pieformname, $issiteview, $issitetemplate,
    $canedittitle, $canuseskins;
134
135
136
    $inlinejavascript = '';

    //get elements for each section of the form
137
    $extrasettingformfields = array();
138
139
    if ($canedittitle) {
        $basicelements = get_basic_elements();
140
141
142
143
144
145
146
        list($advancedelements, $inlinejs) = get_advanced_elements();
        $inlinejavascript .= $inlinejs;
        $extrasettingformfields = array(
            'jsform'     => true,
            'jssuccesscallback' => 'settings_callback',
            'jserrorcallback'   => 'settings_callback',
        );
147
148
    }

149
150
151
    if ($canuseskins) {
        list($skinelements, $hiddenskinelements, $inlinejs) = get_skin_elements();
        $inlinejavascript .= $inlinejs;
152
        $advancedclasslast = '';
153
154
    }
    else {
155
        $advancedclasslast = 'last';
156
157
158
159
160
161
162
163
    }

    //visible elements of the sections
    $formelements = array();

    if ($canedittitle) {
        $formelements['basic'] = array(
            'type'        => 'fieldset',
164
            'class'       => 'first',
165
166
167
168
169
            'collapsible' => true,
            'collapsed'   => false,
            'legend'      => get_string('basics', 'view'),
            'elements'    => $basicelements
        );
170
171
        $formelements['advanced'] = array(
            'type'        => 'fieldset',
172
            'class'       =>  $advancedclasslast,
173
174
175
176
177
            'collapsible' => true,
            'collapsed'   => true,
            'legend'      => get_string('advanced', 'view'),
            'elements'    => $advancedelements
        );
178
179
180
181
182
183
184
185
186
187
188
189
190
    }

    if ($canuseskins) {
        $formelements['skin'] = array(
            'type' => 'fieldset',
            'class' => 'last',
            'collapsible' => true,
            'collapsed' => true,
            'legend' => get_string('skin', 'view'),
            'elements' => $skinelements,
        );
    }

191
    $formelements['submitform'] = array(
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
            'type' => 'submit',
            'class' => 'btn-primary',
            'value' => get_string('save'),
    );

    //hidden elements of the sections
    $hiddenelements = array(
        // hidden 4 all sections
        'id' => array(
            'type'  => 'hidden',
            'value' => $view->get('id'),
        ),
    );

    if ($canuseskins) {
        $hiddenelements = array_merge($hiddenelements, $hiddenskinelements);
    }

    $elements = array_merge($formelements, $hiddenelements);

    //main form
    $settingsform = array(
        'name'      => $pieformname,
215
        'method'     => 'post',
216
217
218
219
220
221
        'renderer'   => 'div',
        'plugintype' => 'core',
        'pluginname' => 'admin',
        'elements'   => $elements,
    );

222
223
    $settingsform = array_merge($settingsform, $extrasettingformfields);

224
    return array(pieform($settingsform), $inlinejavascript);
225
226
}

227
function get_basic_elements() {
228
    global $view, $urlallowed, $group, $institution, $USER;
229

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
    $createtagsoptions = array();
    $typecast = is_postgres() ? '::varchar' : '';
    if ($selecttags = get_records_sql_array("
        SELECT (
            CASE
                WHEN t.tag LIKE 'tagid_%' THEN CONCAT(i.displayname, ': ', t2.tag)
                ELSE t.tag
            END) AS tag, t.resourcetype, t.id
        FROM {tag} t
        LEFT JOIN {tag} t2 ON t2.id" . $typecast . " = SUBSTRING(t.tag, 7)
        LEFT JOIN {institution} i ON i.name = t2.ownerid
        WHERE t.ownertype = ? AND t.ownerid = ?
        AND t.resourcetype IN ('artefact', 'blocktype')
        ORDER BY tag ASC", array('user', $USER->id))) {
        foreach ($selecttags as $k => $tag) {
            $createtagsoptions[$tag->tag] = $tag->tag;
        }
    }

249
250
251
252
253
254
255
256
    $elements = array(
        'title'       => array(
            'type'         => 'text',
            'title'        => get_string('title','view'),
            'defaultvalue' => $view->get('title'),
            'rules'        => array( 'required' => true ),
        ),
        'description' => array(
257
            'type'         => 'textarea',
258
259
260
261
262
            'title'        => get_string('description','view'),
            'rows'         => 5,
            'cols'         => 70,
            'class'        => 'view-description',
            'defaultvalue' => $view->get('description'),
263
            'rules'        => array('maxlength' => 1000000),
264
265
266
267
268
269
270
        ),
        'tags'        => array(
            'type'         => 'tags',
            'title'        => get_string('tags'),
            'description'  => get_string('tagsdescprofile'),
            'defaultvalue' => $view->get('tags'),
            'help'         => true,
271
            'institution'  =>  $institution,
272
273
        )
    );
274
275
276
277
    if (!($group || $institution) && $createtagsoptions) {
        $elements['createtags'] = array(
            'type'         => 'select',
            'title'        => get_string('createtags', 'view'),
278
            'description'  => get_string('createtagsdesc1', 'view'),
279
280
281
282
283
            'options'      => $createtagsoptions,
            'isSelect2'    => true,
            'class'        => 'js-select2',
            'multiple'     => true,
            'defaultvalue' => null,
284
            'collapseifoneoption' => false,
285
286
287
288
            'width'        => '280px',
            'help'         => true,
        );
    }
289
    $viewhasblocks = count_records('block_instance', 'view', $view->get('id'));
290
    $accessibleviewdisabled = $viewhasblocks && !$view->get('accessibleview');
291
292
293
294
    if (!($group || $institution) && $USER->get_account_preference('accessibilityprofile')) {
        $elements['accessibleview'] = array(
            'type'         => 'switchbox',
            'title'        => get_string('accessibleview', 'view'),
295
            'description'  => get_string('accessibleviewdescription', 'view'),
296
297
298
299
            'defaultvalue' => !$accessibleviewdisabled,
            'disabled'     => $accessibleviewdisabled,
        );
    }
300
301
302
303
    return $elements;
}

function get_advanced_elements() {
304
    global $view, $urlallowed, $group, $institution, $USER, $cleanurlbase;
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

    $formatstring = '%s (%s)';
    $ownerformatoptions = array(
        FORMAT_NAME_FIRSTNAME => sprintf($formatstring, get_string('firstname'), $USER->get('firstname')),
        FORMAT_NAME_LASTNAME => sprintf($formatstring, get_string('lastname'), $USER->get('lastname')),
        FORMAT_NAME_FIRSTNAMELASTNAME => sprintf($formatstring, get_string('fullname'), full_name())
    );

    $displayname = display_name($USER);
    if ($displayname !== '') {
        $ownerformatoptions[FORMAT_NAME_DISPLAYNAME] = sprintf($formatstring, get_string('preferredname'), $displayname);
    }
    $studentid = (string)get_field('artefact', 'title', 'owner', $USER->get('id'), 'artefacttype', 'studentid');
    if ($studentid !== '') {
        $ownerformatoptions[FORMAT_NAME_STUDENTID] = sprintf($formatstring, get_string('studentid'), $studentid);
    }

322
323
324
325
326
327
328
329
330
331
332
333
334
    $elements = array();
    if ($view->is_instruction_locked()) {
        if (!empty($view->get('instructions'))) {
            $elements['instructions'] = array(
              'type'         => 'html',
              'title'        => get_string('instructions','view'),
              'class'        => 'view-description',
              'value'        => clean_html($view->get('instructions')),
            );
        }
    }
    else {
        $elements['instructions'] = array(
335
336
337
338
339
340
            'type'         => 'wysiwyg',
            'title'        => get_string('instructions','view'),
            'rows'         => 5,
            'cols'         => 70,
            'class'        => 'view-description',
            'defaultvalue' => $view->get('instructions'),
341
            'rules'        => array('maxlength' => 1000000),
342
343
344
345
346
347
348
349
350
351
352
        );
    }

    $elements['urlid'] = array(
        'type'         => 'text',
        'title'        => get_string('viewurl', 'view'),
        'prehtml'      => '<span class="description">' . (isset($cleanurlbase) ? $cleanurlbase : '') . '</span> ',
        'description'  => get_string('viewurldescription', 'view') . ' ' . get_string('cleanurlallowedcharacters'),
        'defaultvalue' => $view->get('urlid'),
        'rules'        => array('maxlength' => 100, 'regex' => get_config('cleanurlvalidate')),
        'ignore'       => !$urlallowed,
353
    );
354

355
356
357
358
359
360
361
362
363
364
365
366
367
368
    if ($group) {
        $grouproles = $USER->get('grouproles');
        if ($grouproles[$group] == 'admin') {
            $elements['locked'] = array(
                'type'         => 'switchbox',
                'title'        => get_string('Locked', 'view'),
                'description'  => get_string('lockedgroupviewdesc', 'view'),
                'defaultvalue' => $view->get('locked'),
                'disabled'     => $view->get('type') == 'grouphomepage', // This page unreachable for grouphomepage anyway
            );
        }
    }
    $elements['lockblocks'] = array(
        'type'         => 'switchbox',
369
370
        'title'        => get_string('lockblocks1', 'view'),
        'description'  => !empty($view->get('institution')) ? get_string('lockblocksdescriptioninstitution1', 'view') : get_string('lockblocksdescription2', 'view'),
371
        'defaultvalue' => $view->get('lockblocks'),
372
    );
373
374
375
376
377
378
379
380
381
382
383
384
385
386
    if (!($group || $institution)) {
        $default = $view->get('ownerformat');
        if (!$default) {
            $default = FORMAT_NAME_DISPLAYNAME;
        }
        $elements['ownerformat'] = array(
            'type'         => 'select',
            'title'        => get_string('ownerformat','view'),
            'description'  => get_string('ownerformatdescription','view'),
            'options'      => $ownerformatoptions,
            'defaultvalue' => $default,
            'rules'        => array('required' => true),
        );
    }
387
388
389
390
391
392
393
394
    if (get_config('allowanonymouspages')) {
        $elements['anonymise'] = array(
            'type'         => 'switchbox',
            'title'        => get_string('anonymise','view'),
            'description'  => get_string('anonymisedescription','view'),
            'defaultvalue' => $view->get('anonymise'),
        );
    }
395

396
397
398
399
400
401
402
403
404
405
    $folder = ArtefactTypeImage::get_coverimage_folder($USER, $group, $institution);

    $highlight = array(0);

    $elements['coverimage'] = array(
        'type'         => 'filebrowser',
        'title'        => get_string('coverimage', 'view'),
        'description'  => get_string('coverimagedescription', 'view'),
        'folder'       => $folder,
        'highlight'    => $highlight,
406
        'accept'       => 'image/*',
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
        'institution'  => $institution,
        'group'        => $group,
        'page'         => $view->get_url() . '&browse=1',
        'filters'      => array(
             'artefacttype' => array('image'),
        ),
        'config'       => array(
            'upload'          => true,
            'uploadagreement' => get_config_plugin('artefact', 'file', 'uploadagreement'),
            'resizeonuploaduseroption' => get_config_plugin('artefact', 'file', 'resizeonuploaduseroption'),
            'resizeonuploaduserdefault' => $USER->get_account_preference('resizeonuploaduserdefault'),
            'createfolder'    => false,
            'edit'            => false,
            'select'          => true,
            'selectone'       => true,
        ),
        'defaultvalue'       => ($view->get('coverimage') ? array($view->get('coverimage')) : null),
        'selectlistcallback' => 'artefact_get_records_by_id',
        'selectcallback'     => 'add_view_coverimage',
        'unselectcallback'   => 'delete_view_coverimage',
    );

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    if (!$view->is_instruction_locked()) { //later i'll need to check the role of the login user
        $elements['locktemplate'] = array(
          'type'         => 'switchbox',
          'title'        => get_string('locktemplate','view'),
          'description'  => get_string('locktemplatedescription','view'),
          'defaultvalue' => $view->get('locktemplate'),
        );
    }
    else {
        if ($originaltemplate = $view->get_original_template()) {
            $originaltemplate = new View($originaltemplate);
            if (can_view_view($view)) {
                $html = '<a href="' . $originaltemplate->get_url() . '">' . $originaltemplate->get('title') . '</a>';
            }
            else {
                $html = $originaltemplate->get('title');
            }
            $description = get_string('linktooriginaltemplatedescription', 'view');
        }
        else {
            $html = get_string('deletedview', 'view');
            $description = get_string('linktooriginaltemplatedescriptiondeleted', 'view');
        }
        $elements['linktooriginaltemplate'] = array(
            'type'  => 'html',
            'title' => get_string('linktooriginaltemplate', 'view'),
            'value' => $html,
            'description' => $description,
        );
    }
    // give possibility to unlock the view to some roles
    // site admins in institution and site pages
    // institution admins in institution pages
    // group admins in group pages
    if (record_exists('view_instructions_lock', 'view', $view->get('id'))) {
        $canremovelock = false;
        // site admin
        if ($USER->get('admin') && $view->get('institution')) {
            $canremovelock = true;
        }
        //institution admin
        else if ($institution = $view->get('institution') && $USER->is_institutional_admin($institution)) {
            $canremovelock = true;
        }
        // group admin
        else if ($group = $view->get('group')) {
            $role = get_field('group_member', 'role', 'group', $group, 'member', $USER->get('id'));
            if ($role == 'admin') {
                $canremovelock = true;
            }
        }
        if ($canremovelock) {
            $elements['copylocked'] = array(
              'type'         => 'switchbox',
              'title'        => get_string('copylocked','view'),
              'description'  => get_string('copylockeddescription','view'),
              'defaultvalue' => $view->is_instruction_locked(),
            );
        }
    }

490
491
492
    // Theme dropdown
    $theme = $view->set_user_theme();
    $allowedthemes = get_user_accessible_themes();
493
494
    $allowedthemes = array_merge(array('' => get_string('nothemeselected1', 'view')), $allowedthemes);

495
496
497
    if ($theme && !isset($allowedthemes[$theme])) {
        // We have page set with an unknown theme
        // So redirect it to the choose theme page first
498
        redirect(get_config('wwwroot') . 'view/blocks.php?id=' . $view->get('id'));
499
500
501
502
503
504
505
506
507
508
509
    }

    if (get_config('userscanchooseviewthemes') && $view->is_themeable()) {
        $elements['theme'] = array(
            'type'          => 'select',
            'title'         => get_string('theme', 'view'),
            'description'   => get_string('choosethemedesc', 'view'),
            'options'       => $allowedthemes,
            'defaultvalue'  => $theme,
        );
    };
510
511
512
513
514
515
516
517

    $inlinejs = <<<EOF
function settings_callback(form, data) {
    settings_coverimage.callback(form, data);
};
EOF;

    return array($elements, $inlinejs);
518
519
}

520
function get_skin_elements() {
521
    global $view, $USER, $pieformname;
522
    $issiteview = $view->get('institution') == 'mahara';
523

524
525
526
    if (!can_use_skins(null, false, $issiteview)) {
        throw new FeatureNotEnabledException();
    }
527

528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
    // Is page skin already saved/set for current page?
    $skin = param_integer('skin', null);
    $saved = false;
    if (!isset($skin)) {
        $skin = $view->get('skin');
        $saved = true;
    }
    if (!$skin || !($currentskin = get_record('skin', 'id', $skin))) {
        $currentskin = new stdClass();
        $currentskin->id = 0;
        $currentskin->title = get_string('skinnotselected', 'skin');
    }
    $incompatible = (isset($THEME->skins) && $THEME->skins === false && $currentskin->id != 0);
    if ($incompatible) {
        $incompatible = ($view->get('theme')) ? 'notcompatiblewithpagetheme' : 'notcompatiblewiththeme';
        $incompatible = get_string($incompatible, 'skin', $THEME->displayname);
    }
    $metadata = array();
    if (!empty($currentskin->id)) {
        $owner = new User();
        $owner->find_by_id($currentskin->owner);
        $currentskin->metadata = array(
            'displayname' => '<a href="' . get_config('wwwroot') . 'user/view.php?id=' . $currentskin->owner . '">' . display_name($owner) . '</a>',
            'description' => nl2br($currentskin->description),
            'ctime' => format_date(strtotime($currentskin->ctime)),
            'mtime' => format_date(strtotime($currentskin->mtime)),
         );
    }

    $userskins   = Skin::get_user_skins();
    $favorskins  = Skin::get_favorite_skins();
    $siteskins   = Skin::get_site_skins();
    $defaultskin = Skin::get_default_skin();

    if (!$USER->can_edit_view($view)) {
        throw new AccessDeniedException();
    }
    $displaylink = $view->get_url();

    $snippet = smarty_core();
    $snippet->assign('saved', $saved);
    $snippet->assign('incompatible', $incompatible);
    $snippet->assign('currentskin', $currentskin->id);
    $snippet->assign('currenttitle', $currentskin->title);
    $snippet->assign('currentmetadata', (!empty($currentskin->metadata)) ? $currentskin->metadata : null);
    $snippet->assign('userskins', $userskins);
574
    $snippet->assign('favorskins',$favorskins);
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
    $snippet->assign('siteskins', $siteskins);
    $snippet->assign('defaultskin', $defaultskin);
    $snippet->assign('viewid', $view->get('id'));
    $snippet->assign('viewtype', $view->get('type'));
    $snippet->assign('edittitle', $view->can_edit_title());
    $snippet->assign('issiteview', $issiteview);
    $skinform = array(
        'skins_html' => array(
            'type' => 'html',
            'value' => $snippet->fetch('view/skin.tpl'),
        )
    );

    $hiddenelements = array(
        'skinid' => array(
            'type' => 'hidden',
            'value' =>  $currentskin->id,
            'sesskey' =>  $USER->get('sesskey'),
        ),
    );

    $inlinejs = <<<JAVASCRIPT

function change_skin(view, skin) {
  var pd   = {
       'id': view,
       'skin': skin,
       'pieformname': "{$pieformname}"
       }
  sendjsonrequest(config['wwwroot'] + 'view/skins.json.php', pd, 'POST', function(data) {
605
606
607
      jQuery('#settings_skins_html_container').html(data.html);
      jQuery('#settings_skinid').val(data.skin);
      formchangemanager.setFormState(jQuery('#' + data.pieformname), FORM_CHANGED);
608
609
610
611
612
613
614
  });
};

JAVASCRIPT;

    return array($skinform, $hiddenelements, $inlinejs);
}
615

616
function settings_validate(Pieform $form, $values) {
617
    global $view, $issiteview, $issitetemplate, $canuseskins;
618

619
620
621
622
623
624
625
626
627
628
629
    if (isset($values['urlid']) && $values['urlid'] != $view->get('urlid')) {
        if (strlen($values['urlid']) < 3) {
            $form->set_error('urlid', get_string('rule.minlength.minlength', 'pieforms', 3));
        }
        else if ($group = $view->get('group') and record_exists('view', 'group', $group, 'urlid', $values['urlid'])) {
            $form->set_error('urlid', get_string('groupviewurltaken', 'view'));
        }
        else if ($owner = $view->get('owner') and record_exists('view', 'owner', $owner, 'urlid', $values['urlid'])) {
            $form->set_error('urlid', get_string('userviewurltaken', 'view'));
        }
    }
630
631
632
633
634
635
636

    if ($canuseskins && isset($values['skinid']) && $values['skinid']) {
        $skin = new Skin($values['skinid']);
        if (!$skin->can_use()) {
            throw new AcessDeniedException();
        }
    }
637
638
}

639
function settings_submit(Pieform $form, $values) {
640
    global $view, $SESSION, $issiteview, $issitetemplate, $canedittitle, $canuseskins;
641
642
643

    if ($canedittitle) {
        set_view_title_and_description($form, $values);
644
        set_view_advanced($form, $values);
645
646
647
648
649
    }

    if ($canuseskins && isset($values['skinid'])) {
        $view->set('skin', $values['skinid']);
    }
650
    $view->set('coverimage', (isset($values['coverimage']) ? $values['coverimage'] : null));
651

652
653
654
655
656
657
658
659
660
    if (isset($values['copylocked'])) {
        if ($values['copylocked']) {
            $view->lock_instructions_edit($view->get_original_template());
        }
        else {
            $view->unlock_instructions_edit();
        }
    }

661
    $view->commit();
662
663
664
665

    $result = array(
        'error'   => false,
        'message' => get_string('viewsavedsuccessfully', 'view'),
666
        'goto'    => get_config('wwwroot') . 'view/blocks.php?id=' . $view->get('id'),
667
668
669
670
671
672
673
    );
    if ($form->submitted_by_js()) {
        // Redirect back to the page from within the iframe
        $SESSION->add_ok_msg($result['message']);
        $form->json_reply(PIEFORM_OK, $result, false);
    }
    $form->reply(PIEFORM_OK, $result);
674
}
675

676
function create_block($bt, $configdata, $view, $blockinfo = null, $dimension=null) {
677
678
679
680
681
682
683
684
685
    if ($bt == 'taggedposts') {
        $tagselect = $configdata['tagselect'];
        unset($configdata['tagselect']);
    }
    safe_require('blocktype', $bt);
    $bi = new BlockInstance(0, array('blocktype' => $bt, 'view' => $view->get('id')));
    $blocktypeclass = generate_class_name('blocktype', $bt);
    if (method_exists($blocktypeclass, 'get_instance_title')) {
        $title = call_static_method($blocktypeclass, 'get_instance_title', $bi);
686
        $defaulttitle = false;
687
688
689
    }
    else {
        $title = $blocktypeclass::get_title();
690
        $defaulttitle = true;
691
    }
692

693
    $bi->set('title', $title);
694
695
696
697
698
699
700
701
702
703
    $bi->set('positionx', 0);
    $bi->set('positiony', 0);
    if ($dimension) {
        $bi->set('height', $dimension->height);
        $bi->set('width', $dimension->width);
    }
    else {
        $bi->set('height', 3);
        $bi->set('width', 4);
    }
704
705
706
707
    $configdata['retractable'] = false;
    $configdata['retractedonload'] = false;
    $bi->set('configdata', $configdata);
    $bi->commit();
708
709
710
711
712
713
714
715
716
717
718
719
720
721
    // Now we have committed the block we can check if we can use something other than default block title
    if ($defaulttitle) {
        if (!empty($configdata['artefactid']) && $title = $bi->get_artefact_instance($configdata['artefactid'])->get('title')) {
            $bi->set('title', $title);
        }
        else if (!empty($blockinfo)) {
            $oldbi = new BlockInstance($blockinfo['oldid']);
            $title = $oldbi->get('title');
            $bi->set('title', $title);
        }
    }

    if ($blockinfo['tags']) {
        $bi->set('tags', $blockinfo['tags']);
722
723
724
    }
    if ($bt == 'taggedposts') {
        $blocktypeclass::save_tag_selection($tagselect, $bi);
725
726
        // Need to make the block save again now we have made the tag selections
        $bi->set('dirty', true);
727
    }
728
    $bi->commit();
729
730
731
    return $bi->get('id');
}

732
function set_view_title_and_description(Pieform $form, $values) {
733
    global $view, $urlallowed, $new, $USER;
734

735
    $view->set('title', $values['title']);
736
    $view->set('description', trim($values['description']));
737
738
    $tags = $values['tags'] ? $values['tags'] : array();
    $view->set('tags', $tags);
739
740
741
742
    if (isset($values['createtags'])) {
        $createtags = $values['createtags'] ? $values['createtags'] : array();
        if ($createtags) {
            require_once('searchlib.php');
743
            require_once('collection.php');
744
745
746
747
748
749
750
751
752
753
754
755
            $data = array();
            // Get all the items containing any of the tags
            foreach ($createtags as $tag) {
                $tagowner  = (object) array('type' => 'user', 'id' => $USER->get('id'));
                $tagdata = get_portfolio_items_by_tag($tag, $tagowner, 0, 0, 'date', 'all');
                $data = array_merge($data, $tagdata->data);
            }

            if ($data) {
                $combineddata = array();
                // Now check what we have so we know what to do with them
                foreach ($data as $item) {
756
757
758
759
                    // If collection but tag is in one of it's views then no $item->tags so skip
                    if (!isset($item->tags)) {
                        continue;
                    }
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
                    // Check that the block has all of the tags we entered, and if not skip it
                    if (array_diff($createtags, $item->tags)) {
                        continue;
                    }
                    // Check if the block we are about to add is from the current page, and if so skip it
                    if (isset($item->views) && isset($item->views[$view->get('id')])) {
                        continue;
                    }
                    $type = isset($item->specialtype) ? $item->specialtype : $item->artefacttype;
                    if (!isset($combineddata[$item->type])) {
                        $combineddata[$item->type] = array();
                    }
                    if (!isset($combineddata[$item->type][$type])) {
                        $combineddata[$item->type][$type] = array('count' => 1, 'ids' => array($item->id));
                    }
                    else {
                        $combineddata[$item->type][$type]['count'] ++;
                        $combineddata[$item->type][$type]['ids'][] = $item->id;
                    }
                }
                // Now lets make decisions about what we have
                if (!empty($combineddata['blocktype'])) {
                    foreach ($combineddata['blocktype'] as $bk => $bv) {
                        $bt = false;
                        foreach($bv['ids'] as $bid) {
                            $configdata = unserialize(get_field('block_instance', 'configdata', 'id', $bid));
                            $tags = get_column('tag', 'tag', 'resourcetype', 'blocktype', 'resourceid', $bid);
787
788
789
790
791
792
793
794
                            foreach($tags as &$t) {
                                if (preg_match('/^tagid\_(.*)/', $t, $matches)) {
                                     if ($itag = get_record('tag', 'id', $matches[1])) {
                                         $instname = get_field('institution', 'displayname', 'id', $itag->resourceid);
                                         $t = $instname . ': ' . $itag->tag;
                                      }
                                  }
                            }
795
796
                            $dimension = get_record('block_instance_dimension', 'block', $bid);
                            $id = create_block($bk, $configdata, $view, array('oldid' => $bid, 'tags' => $tags), $dimension);
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
                        }
                    }
                }
                if (!empty($combineddata['artefact'])) {
                    $filedownload = array();
                    $plans = array();
                    foreach ($combineddata['artefact'] as $ak => $av) {
                        safe_require('artefact', 'file');
                        $bt = false;
                        if ($ak == 'plan') {
                            // Pass to plans to create later
                            $plans = array_merge($plans, $av['ids']);
                        }
                        if ($ak == 'task') {
                            // We need to add the plan block that the task(s) relate to
                            $taskplans = get_column_sql("SELECT DISTINCT parent FROM {artefact}
                                                         WHERE id IN (" . join(',', $av['ids']) . ")");
                            $plans = array_unique(array_merge($plans, $taskplans));
                        }
                        if ($ak == 'html') { // This is an artefact related to the 'note' block (not 'html' block)
                            // Need to do a loop for each folder
                            foreach($av['ids'] as $noteid) {
                                // Need to add a note block
                                $bt = 'textbox';
                                $configdata = array('artefactid' => $noteid,
                                                    'licensereadonly' => '', // default license placeholder
                                                    'tagsreadonly' => '', // default tag placeholder
                                                   );
                                // We need to get an example of an existing note (textbox) block to find out
                                // if there are meant to be attachments for the note
                                // @TODO: fix this up - we should have a artefact_note_attachment table rather than
                                //        having every note block containing the info
                                if ($oldconfigdata = get_field_sql("
                                        SELECT bi.configdata
                                        FROM {block_instance} bi
                                        JOIN {view_artefact} va ON va.block = bi.id
                                        WHERE va.artefact = ?
                                        AND bi.blocktype = ?
                                        LIMIT 1", array($noteid, 'textbox'))) {
                                    $oldconfigdata = unserialize($oldconfigdata);
                                    $configdata['artefactids'] = !empty($oldconfigdata['artefactids']) ? $oldconfigdata['artefactids'] : null;
                                }
839
840

                                $id = create_block($bt, $configdata, $view);
841
842
843
844
845
846
847
848
849
850
851
852
                            }
                            $bt = false;
                        }
                        if ($ak == 'blog') {
                            // Need to do a loop for each folder
                            foreach($av['ids'] as $blogid) {
                                // Need to add a blog block
                                $bt = 'blog';
                                $configdata = array('artefactid' => $blogid,
                                                    'count' => '5', // default number of posts to display
                                                    'copytype' => 'nocopy', // default copy type
                                                   );
853
                                $id = create_block($bt, $configdata, $view);
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
                            }
                            $bt = false;
                        }
                        if ($ak == 'blogpost') {
                            // Need to add a taggedpost block
                            $bt = 'taggedposts';
                            $configdata = array('tagselect' => $createtags,
                                                'count' => '10', // default number of posts to display
                                                'copytype' => 'nocopy', // default copy type
                                                'full' => false,
                                               );
                        }
                        if ($ak == 'folder') {
                            // Need to do a loop for each folder
                            foreach($av['ids'] as $folderid) {
                                // Need to add a folder block
                                $bt = 'folder';
                                $configdata = array('artefactid' => $folderid,
                                                    'sortorder' => 'asc',
                                                   );
874
                                $id = create_block($bt, $configdata, $view);
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
                            }
                            $bt = false;
                        }
                        if ($ak == 'video' || $ak == 'audio') {
                            if ($av['count'] > 1) {
                                // Need to add a files to download block
                                $filedownload = array_merge($filedownload, $av['ids']);
                            }
                            else {
                                // Need to add an internalmedia block
                                $bt = 'internalmedia';
                                $configdata = array('artefactid' => $av['ids'][0]);
                            }
                        }
                        if ($ak == 'file') {
                            // Need to add a files to download block
                            $filedownload = array_merge($filedownload, $av['ids']);
                        }
                        if ($ak == 'pdf') {
                            if ($av['count'] > 1) {
                                // Need to add a files to download block
                                $filedownload = array_merge($filedownload, $av['ids']);
                            }
                            else {
                                // Need to add a pdf block
                                $bt = 'pdf';
                                $configdata = array('artefactid' => $av['ids'][0],
                                                    'pdfwarning' => get_string('pdfwarning', 'blocktype.file/pdf'),
                                                   );
                            }
                        }
                        if ($ak == 'image') {
                            if ($av['count'] > 1) {
                                // Need to add an image gallery block
                                $bt = 'gallery';
                                $configdata = array('artefactids' => $av['ids'],
                                                    'user' => $view->get('owner'), // normally 'user' is for external gallery but we set it to page owner for interal gallery
                                                    'select' => '1', // to select images by ids
                                                    'style' => '1',  // to display the images as slideshow
                                                    'showdescription' => false,
                                                    'width' => '75', // the default value added to config form
                                                   );
                            }
                            else {
                                // Need to add an image block
                                $bt = 'image';
                                $configdata = array('artefactid' => $av['ids'][0],
                                                    'showdescription' => false,
                                                   'width' => "",
                                                   );
                            }
                        }
                        if ($bt) {
                            // Add the block to the page
929
                            $id = create_block($bt, $configdata, $view);
930
931
932
933
934
935
936
937
                        }
                    }
                    // We add the plan block now
                    if (!empty($plans)) {
                        $bt = 'plans';
                        $configdata = array('artefactids' => $plans,
                                            'count' => 10, // default tasks
                                           );
938
                        $id = create_block($bt, $configdata, $view);
939
940
941
942
943
                    }
                    // We add in the file to download block once we work out what should be in it
                    if (!empty($filedownload)) {
                        $bt = 'filedownload';
                        $configdata = array('artefactids' => $filedownload);
944
                        $id = create_block($bt, $configdata, $view);
945
946
947
948
949
                    }
                }
            }
        }
    }
950
951
952
    if (isset($values['locked'])) {
        $view->set('locked', (int)$values['locked']);
    }
953
954
955
    if (isset($values['lockblocks'])) {
        $view->set('lockblocks', (int)$values['lockblocks']);
    }
956
957
958
    if (isset($values['theme'])) {
        $view->set('theme', $values['theme']);
    }
959
960
961
962
963
964
    if (isset($values['ownerformat']) && $view->get('owner')) {
        $view->set('ownerformat', $values['ownerformat']);
    }
    if (isset($values['anonymise'])) {
        $view->set('anonymise', (int)$values['anonymise']);
    }
965
    if (isset($values['accessibleview'])) {
966
        $view->set('accessibleview', (int)$values['accessibleview']);
967
    }
968
969
970
    if (isset($values['locktemplate'])) {
        $view->set('locktemplate', (int)$values['locktemplate']);
    }
971
972
973
974
975
}

function set_view_advanced(Pieform $form, $values) {
    global $view, $urlallowed, $new;

976
    if (isset($values['instructions']) && trim($values['instructions']) !== '') {
977
978
979
980
981
982
983
984
985
        require_once('embeddedimage.php');
        $view->set('instructions', EmbeddedImage::prepare_embedded_images($values['instructions'], 'instructions', $view->get('id')));
    }
    else {
        $view->set('instructions', '');
    }
    if (isset($values['ownerformat']) && $view->get('owner')) {
        $view->set('ownerformat', $values['ownerformat']);
    }
986
987
    // Change the 'untitled' urlid on first save
    if ($new && $urlallowed) {
988
989
990
991
992
        // Generate one automatically based on the title
        $desired = generate_urlid($values['title'], get_config('cleanurlviewdefault'), 3, 100);
        $ownerinfo = (object) array('owner' => $view->get('owner'), 'group' => $view->get('group'));
        $view->set('urlid', View::new_urlid($desired, $ownerinfo));
    }
993
994
995
    else if (isset($values['urlid'])) {
        $view->set('urlid', strlen($values['urlid']) == 0 ? null : $values['urlid']);
    }
996
}
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011


function add_view_coverimage($coverimageid) {
    global $view;
    if ($view) {
        $view->set('coverimage', $coverimageid);
    }
}

function delete_view_coverimage($coverimageid=null) {
    global $view;
    if ($view) {
        $view->set('coverimage', 0);
    }
}