view.php 84.9 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
Penny Leach's avatar
Penny Leach committed
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Penny Leach's avatar
Penny Leach committed
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Penny Leach's avatar
Penny Leach committed
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Penny Leach's avatar
Penny Leach committed
18
19
20
 *
 * @package    mahara
 * @subpackage core
21
 * @author     Catalyst IT Ltd
Penny Leach's avatar
Penny Leach committed
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
Penny Leach's avatar
Penny Leach committed
24
25
26
27
28
29
30
 *
 */

defined('INTERNAL') || die();

class View {

31
32
33
34
35
    private $dirty;
    private $deleted;
    private $id;
    private $owner;
    private $ownerformat;
36
    private $group;
37
    private $institution;
38
39
40
    private $ctime;
    private $mtime;
    private $atime;
41
42
    private $startdate;
    private $stopdate;
43
44
45
46
47
48
49
50
    private $submittedto;
    private $title;
    private $description;
    private $loggedin;
    private $friendsonly;
    private $artefact_instances;
    private $artefact_metadata;
    private $ownerobj;
51
    private $groupobj;
52
    private $numcolumns;
53
    private $layout;
54
    private $columns;
55
    private $dirtycolumns; // for when we change stuff
56
    private $tags;
57
    private $editingroles;
58
    private $template;
59
    private $copynewuser = 0;
60
    private $copynewgroups;
61
    private $copyconfig;
62
    private $type;
Penny Leach's avatar
Penny Leach committed
63
64
65

    public function __construct($id=0, $data=null) {
        if (!empty($id)) {
66
67
68
            $tempdata = get_record('view','id',$id);
            if (empty($tempdata)) {
                throw new ViewNotFoundException("View with id $id not found");
Penny Leach's avatar
Penny Leach committed
69
            }    
70
71
72
73
74
75
            if (!empty($data)) {
                $data = array_merge((array)$tempdata, $data);
            }
            else {
                $data = $tempdata; // use what the database has
            }
Penny Leach's avatar
Penny Leach committed
76
            $this->id = $id;
Penny Leach's avatar
Penny Leach committed
77
78
79
        }
        else {
            $this->ctime = time();
80
            $this->mtime = time();
Penny Leach's avatar
Penny Leach committed
81
            $this->dirty = true;
Penny Leach's avatar
Penny Leach committed
82
83
84
85
86
87
88
89
90
91
92
        }

        if (empty($data)) {
            $data = array();
        }
        foreach ((array)$data as $field => $value) {
            if (property_exists($this, $field)) {
                $this->{$field} = $value;
            }
        }
        $this->atime = time();
93
94
        $this->columns = array();
        $this->dirtycolumns = array();
95
96
        if ($this->group) {
            $group = get_record('group', 'id', $this->group);
97
            safe_require('grouptype', $group->grouptype);
98
            $this->editingroles = call_static_method('GroupType' . ucfirst($group->grouptype), 'get_view_editing_roles');
99
        }
Penny Leach's avatar
Penny Leach committed
100
101
    }

Penny Leach's avatar
Penny Leach committed
102
103
104
105
    public function get($field) {
        if (!property_exists($this, $field)) {
            throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
        }
106
107
108
        if ($field == 'tags') { // special case
            return $this->get_tags();
        }
Penny Leach's avatar
Penny Leach committed
109
110
111
        return $this->{$field};
    }

112
113
114
115
116
117
118
119
120
121
122
123
124
    public function set($field, $value) {
        if (property_exists($this, $field)) {
            if ($this->{$field} != $value) {
                // only set it to dirty if it's changed
                $this->dirty = true;
            }
            $this->{$field} = $value;
            $this->mtime = time();
            return true;
        }
        throw new InvalidArgumentException("Field $field wasn't found in class " . get_class($this));
    }

125
126
127
128
129
130
131
    public function get_tags() {
        if (!isset($this->tags)) {
            $this->tags = get_column('view_tag', 'tag', 'view', $this->get('id'));
        }
        return $this->tags;
    }

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    /**
     * View destructor. Calls commit if necessary.
     *
     * A special case is when the object has just been deleted.  In this case,
     * we do nothing.
     */
    public function __destruct() {
        if ($this->deleted) {
            return;
        }
      
        if (!empty($this->dirty)) {
            return $this->commit();
        }
    }

    /** 
     * This method updates the contents of the view table only.
     */
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }
        $fordb = new StdClass;
        foreach (get_object_vars($this) as $k => $v) {
            $fordb->{$k} = $v;
158
            if (in_array($k, array('mtime', 'ctime', 'atime', 'startdate', 'stopdate')) && !empty($v)) {
159
160
161
                $fordb->{$k} = db_format_timestamp($v);
            }
        }
162
163
164

        db_begin();

165
        if (empty($this->id)) {
166
167
168
169
            // users are only allowed one profile view
            if ($this->type == 'profile' && record_exists('view', 'owner', $this->owner, 'type', 'profile')) {
                throw new ViewLimitException(get_string('onlonlyyoneprofileviewallowed', 'error'));
            }
170
171
172
173
174
            $this->id = insert_record('view', $fordb, 'id', true);
        }
        else {
            update_record('view', $fordb, 'id');
        }
175
176
177
178
179
180

        delete_records('view_tag', 'view', $this->get('id'));
        foreach ($this->get_tags() as $tag) {
            insert_record('view_tag', (object)array( 'view' => $this->get('id'), 'tag' => $tag));
        }

181
182
183
184
185
186
187
        if (isset($this->copynewgroups)) {
            delete_records('view_autocreate_grouptype', 'view', $this->get('id'));
            foreach ($this->copynewgroups as $grouptype) {
                insert_record('view_autocreate_grouptype', (object)array( 'view' => $this->get('id'), 'grouptype' => $grouptype));
            }
        }

188
189
        db_commit();

190
191
192
193
        $this->dirty = false;
        $this->deleted = false;
    }

Penny Leach's avatar
Penny Leach committed
194
195
196
197
198
199
200
201
    public function get_artefact_instances() {
        if (!isset($this->artefact_instances)) {
            $this->artefact_instances = false;
            if ($instances = $this->get_artefact_metadata()) {
                foreach ($instances as $instance) {
                    safe_require('artefact', $instance->plugin);
                    $classname = generate_artefact_class_name($instance->artefacttype);
                    $i = new $classname($instance->id, $instance);
Penny Leach's avatar
Penny Leach committed
202
                    $this->childreninstances[] = $i;
Penny Leach's avatar
Penny Leach committed
203
204
205
206
207
208
209
                }
            }
        }
        return $this->artefact_instances;
    }

    public function get_artefact_metadata() {
Penny Leach's avatar
Penny Leach committed
210
        if (!isset($this->artefact_metadata)) {
211
            $sql = 'SELECT a.*, i.name, va.block
212
213
214
                    FROM {view_artefact} va
                    JOIN {artefact} a ON va.artefact = a.id
                    JOIN {artefact_installed_type} i ON a.artefacttype = i.name
Penny Leach's avatar
Penny Leach committed
215
                    WHERE va.view = ?';
216
            $this->artefact_metadata = get_records_sql_array($sql, array($this->id));
Penny Leach's avatar
Penny Leach committed
217
218
219
        }
        return $this->artefact_metadata;
    }
Penny Leach's avatar
Penny Leach committed
220

221
    public function find_artefact_children($artefact, $allchildren, &$refs) {
222
223

        $children = array();        
224
225
226
227
228
229
230
231
232
233
        if ($allchildren) {
            foreach ($allchildren as $child) {
                if ($child->parent != $artefact->id) {
                    continue;
                }
                $children[$child->id] = array();
                $children[$child->id]['artefact'] = $child;
                $refs[$child->id] = $child;
                $children[$child->id]['children'] = $this->find_artefact_children($child, 
                                                            $allchildren, $refs);
234
235
236
237
238
239
            }
        }

        return $children;
    }

Penny Leach's avatar
Penny Leach committed
240

Penny Leach's avatar
Penny Leach committed
241
242
243
244
245
246
    public function has_artefacts() {
        if ($this->get_artefact_metadata()) {
            return true;
        }
        return false;
    }
Penny Leach's avatar
Penny Leach committed
247
248
249
250
251
252
253
254

    public function get_owner_object() {
        if (!isset($this->ownerobj)) {
            $this->ownerobj = get_record('usr', 'id', $this->get('owner'));
        }
        return $this->ownerobj;
    }

255
256
257
258
259
260
261
    public function get_group_object() {
        if (!isset($this->groupobj)) {
            $this->groupobj = get_record('group', 'id', $this->get('group'));
        }
        return $this->groupobj;
    }

Penny Leach's avatar
Penny Leach committed
262
    
263
264
265
266
267
    public function delete() {
        delete_records('artefact_feedback','view',$this->id);
        delete_records('view_feedback','view',$this->id);
        delete_records('view_artefact','view',$this->id);
        delete_records('view_access','view',$this->id);
268
        delete_records('view_access_group','view',$this->id);
269
        delete_records('view_access_usr','view',$this->id);
270
        delete_records('view_tag','view',$this->id);
271
        delete_records('usr_watchlist_view','view',$this->id);
272
        delete_records('block_instance', 'view', $this->id);
273
        delete_records('view','id',$this->id);
274
275
276
        $this->deleted = true;
    }

277
278
    public function get_access() {

279
280
281
282
283
        $data = get_records_sql_array("
            SELECT accesstype AS type, NULL AS id, NULL AS role, NULL AS grouptype, startdate, stopdate
                FROM {view_access}
                WHERE view = ?
        UNION
284
            SELECT 'user' AS type, usr AS id, NULL AS role, NULL AS grouptype, startdate, stopdate
285
286
287
                FROM {view_access_usr}
                WHERE view = ?
        UNION
288
            SELECT 'group', \"group\", role, grouptype, startdate, stopdate FROM {view_access_group}
289
                INNER JOIN {group} g ON (\"group\" = g.id AND g.deleted = ?)
290
291
292
293
294
295
                WHERE view = ?", array($this->id, $this->id, 0, $this->id));
        if ($data) {
            foreach ($data as &$item) {
                $item = (array)$item;
                if ($item['role']) {
                    $item['roledisplay'] = get_string($item['role'], 'grouptype.'.$item['grouptype']);
296
                }
297
            }
298
299
300
        }
        else {
            $data = array();
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        }
        return $data;
    }

    public function set_access($accessdata) {
        global $USER;

        // For users who are being removed from having access to this view, they
        // need to have the view and any attached artefacts removed from their
        // watchlist.
        $oldusers = array();
        foreach ($this->get_access() as $item) {
            if ($item['type'] == 'user') {
                $oldusers[] = $item;
            }
        }

        $newusers = array();
        if ($accessdata) {
            foreach ($accessdata as $item) {
                if ($item['type'] == 'user') {
                    $newusers[] = $item;
                }
            }
        }

        $userstodelete = array();
        foreach ($oldusers as $olduser) {
            foreach ($newusers as $newuser) {
                if ($olduser['id'] == $newuser['id']) {
                    continue(2);
                }
            }
            $userstodelete[] = $olduser;
        }

        if ($userstodelete) {
            $userids = array();
            foreach ($userstodelete as $user) {
                $userids[] = intval($user['id']);
            }
            $userids = implode(',', $userids);

            execute_sql('DELETE FROM {usr_watchlist_view}
                WHERE view = ' . $this->get('id') . '
                AND usr IN (' . $userids . ')');
        }

        $beforeusers = activity_get_viewaccess_users($this->get('id'), $USER->get('id'), 'viewaccess');

        // Procedure:
        // get list of current friends - this is available in global $data
        // compare with list of new friends
        // work out which friends are being removed
        // foreach friend
        //     // remove record from usr_watchlist_view where usr = ? and view = ?
        //     // remove records from usr_watchlist_artefact where usr = ? and view = ?
        // endforeach
        //
        db_begin();
        delete_records('view_access', 'view', $this->get('id'));
        delete_records('view_access_usr', 'view', $this->get('id'));
        delete_records('view_access_group', 'view', $this->get('id'));
        $time = db_format_timestamp(time());

        // View access
        if ($accessdata) {
            foreach ($accessdata as $item) {
                $accessrecord = new StdClass;
                $accessrecord->view = $this->get('id');
                $accessrecord->startdate = db_format_timestamp($item['startdate']);
                $accessrecord->stopdate  = db_format_timestamp($item['stopdate']);
                switch ($item['type']) {
                    case 'public':
                    case 'loggedin':
                    case 'friends':
                        $accessrecord->accesstype = $item['type'];
                        insert_record('view_access', $accessrecord);
                        break;
                    case 'user':
                        $accessrecord->usr = $item['id'];
                        insert_record('view_access_usr', $accessrecord);
                        break;
                    case 'group':
                        $accessrecord->group = $item['id'];
386
387
388
                        if ($item['role']) {
                            $accessrecord->role = $item['role'];
                        }
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
                        insert_record('view_access_group', $accessrecord);
                        break;
                }
            }
        }

        $data = new StdClass;
        $data->view = $this->get('id');
        $data->owner = $USER->get('id');
        $data->oldusers = $beforeusers;
        activity_occurred('viewaccess', $data);
        handle_event('saveview', $this->get('id'));

        db_commit();
    }

405
406
407
408
409
410
    public function get_autocreate_grouptypes() {
        if (!isset($this->copynewgroups)) {
            $this->copynewgroups = get_column('view_autocreate_grouptype', 'grouptype', 'view', $this->id);
        }
        return $this->copynewgroups;
    }
411

412
413
    public function release($groupid, $releaseuser=null) {
        if ($this->get('submittedto') != $groupid) {
414
            throw new ParameterException("View with id " . $this->get('id') .
415
                                         " has not been submitted to group $groupid");
416
417
418
419
        }
        $releaseuser = optional_userobj($releaseuser);
        $this->set('submittedto', null);
        $this->commit();
420
        $ownerlang = get_user_language($this->get('owner'));
421
422
423
        require_once('activity.php');
        activity_occurred('maharamessage', 
                  array('users'   => array($this->get('owner')),
424
425
                  'subject' => get_string_from_language($ownerlang, 'viewreleasedsubject', 'group'),
                  'message' => get_string_from_language($ownerlang, 'viewreleasedmessage', 'group',
426
                       get_field('group', 'name', 'id', $groupid), 
427
                       display_name($releaseuser, $this->get_owner_object()))));
428
429
    }

430
431
432
433
434
435
    /**
     * Returns HTML for the category list
     *
     * @param string $defaultcategory The currently selected category
     * @param View   $view            The view we're currently using
    */
436
    public static function build_category_list($defaultcategory, View $view, $new=0) {
437
        require_once(get_config('docroot') . '/blocktype/lib.php');
438
        // Change to a left join to show tabs with no results
439
        $cats = get_records_sql_array('SELECT bc.name, COUNT(*) AS "count"
440
441
            FROM {blocktype_category} bc
            INNER JOIN {blocktype_installed_category} bic ON (bc.name = bic.category)
442
443
444
445
446
447
448
            WHERE EXISTS (
                SELECT 1 
                    FROM {blocktype_installed_viewtype} bivt
                    JOIN {blocktype_installed} bi ON bi.name = bivt.blocktype
                    WHERE bivt.viewtype = ?
                    AND bic.blocktype = bi.name
            )
449
            GROUP BY bc.name
450
            ORDER BY bc.name', array($view->get('type')));
451
452
453
        $categories = array_map(
            create_function(
                '$a', 
454
455
456
                'return array(
                    "name" => $a->name,
                    "title" => call_static_method("PluginBlocktype", "category_title_from_name", $a->name) . " (" . $a->count . ")",
457
458
459
460
461
                );'
            ),
            $cats
        );

462
463
464
465
        // The 'internal' plugin is known to the outside world as 'profile', so 
        // we need to sort on the actual name
        usort($categories, create_function('$a, $b', 'return strnatcasecmp($a[\'title\'], $b[\'title\']);'));

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
        $flag = false;
        foreach ($categories as &$cat) {
            $classes = '';
            if (!$flag) {
                $flag = true;
                $classes[] = 'first';
            }
            if ($defaultcategory == $cat['name']) {
                $classes[] = 'current';
            }
            if ($classes) {
                $cat['class'] = hsc(implode(' ', $classes)); 
            }
        }

481
482
483
        // Because of the reference in the above loop, $cat refers to the last item
        $cat['class'] = (isset($cat['class'])) ? $cat['class'] . ' last' : 'last';

484
485
486
        $smarty = smarty_core();
        $smarty->assign('categories', $categories);
        $smarty->assign('viewid', $view->get('id'));
487
        $smarty->assign('new', $new);
488
489
490
491
492
493
494
495
496
497
498
        return $smarty->fetch('view/blocktypecategorylist.tpl');
    }

    /**
     * Returns HTML for the blocktype list for a particular category
     *
     * @param string $category   The category to build the blocktype list for
     * @param bool   $javascript Set to true if the caller is a json script, 
     *                           meaning that nothing for the standard HTML version 
     *                           alone should be output
     */
499
    public function build_blocktype_list($category, $javascript=false) {
500
        require_once(get_config('docroot') . 'blocktype/lib.php');
501
        $blocktypes = PluginBlockType::get_blocktypes_for_category_and_viewtype($category, $this->get('type'));
502
503
504
505
506
507
508
509
510
511
512

        $smarty = smarty_core();
        $smarty->assign_by_ref('blocktypes', $blocktypes);
        $smarty->assign('javascript', $javascript);
        return $smarty->fetch('view/blocktypelist.tpl');
    }

    /**
     * Process view changes. This function is used both by the json stuff and 
     * by normal posts
     */
513
    public function process_changes($category='', $new=0) {
514
515
516
        global $SESSION, $USER;

        // Security
517
518
        // TODO this might need to be moved below the requestdata check below, to prevent non owners of the view being 
        // rejected
519
        if (!$USER->can_edit_view($this)) {
520
521
522
523
524
525
526
527
528
529
530
            throw new AccessDeniedException(get_string('canteditdontown', 'view'));
        }

        if (!count($_POST) && count($_GET) < 3) {
            return;
        }

        $action = '';
        foreach ($_POST as $key => $value) {
            if (substr($key, 0, 7) == 'action_') {
                $action = substr($key, 7);
531
                break;
532
            }
533
534
535
536
537
            else if (substr($key, 0, 37) == 'cancel_action_configureblockinstance_'
                     && param_integer('removeoncancel', 0)) {
                $action = 'removeblockinstance_' . substr($key, 37);
                break;
            }
538
539
540
541
542
543
544
545
546
547
548
549
        }
        // TODO Scan GET for an action. The only action that is GETted is 
        // confirming deletion of a blockinstance. It _should_ be a POST, but 
        // that can be fixed later.
        if (!$action) {
            foreach ($_GET as $key => $value) {
                if (substr($key, 0, 7) == 'action_') {
                    $action = substr($key, 7);
                }
            }
        }

550
551
552
553
        if (empty($action)) {
            return;
        }
    
554
555
556
        $actionstring = $action;
        $action = substr($action, 0, strpos($action, '_'));
        $actionstring  = substr($actionstring, strlen($action) + 1);
557
558
559
560
561

        // Actions from <input type="image"> buttons send an _x and _y
        if (substr($actionstring, -2) == '_x' || substr($actionstring, -2) == '_y') {
            $actionstring = substr($actionstring, 0, -2);
        }
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        
        $values = self::get_values_for_action($actionstring);

        $result = null;
        switch ($action) {
            // the view class method is the same as the action,
            // but I've left these here in case any additional
            // parameter handling has to be done.
            case 'addblocktype': // requires action_addblocktype  (blocktype in separate parameter)
                $values['blocktype'] = param_alpha('blocktype', null);
            break;
            case 'removeblockinstance': // requires action_removeblockinstance_id_\d
                if (!defined('JSON')) {
                    if (!$sure = param_boolean('sure')) {
576
                        $yeslink = get_config('wwwroot') . '/view/blocks.php?id=' . $this->get('id') . '&c=file&new=' . $new . '&action_' . $action . '_' .  $actionstring . '=1&sure=true';
Penny Leach's avatar
Penny Leach committed
577
                        $baselink = '/view/blocks.php?id=' . $this->get('id') . '&c=' . $category . '&new=' . $new;
578
579
580
581
582
583
584
585
586
                        $SESSION->add_info_msg(get_string('confirmdeleteblockinstance', 'view') 
                            . ' <a href="' . $yeslink . '">' . get_string('yes') . '</a>'
                            . ' <a href="' . $baselink . '">' . get_string('no') . '</a>', false);
                        redirect($baselink);
                        exit;
                    }
                }
            break;
            case 'configureblockinstance': // requires action_configureblockinstance_id_\d_column_\d_order_\d
587
            case 'acsearch': // requires action_acsearch_id_\d
588
589
                if (!defined('JSON')) {
                    $this->blockinstance_currently_being_configured = $values['id'];
590
591
                    // And we're done here for now
                    return;
592
593
594
595
596
597
598
599
600
601
602
603
604
605
                }
            case 'moveblockinstance': // requires action_moveblockinstance_id_\d_column_\d_order_\d
            case 'addcolumn': // requires action_addcolumn_before_\d
            case 'removecolumn': // requires action_removecolumn_column_\d
            break;
            default:
                throw new InvalidArgumentException(get_string('noviewcontrolaction', 'error', $action));
        }
       
        $message = '';
        $success = false;
        try {
            $values['returndata'] = defined('JSON');
            $returndata = $this->$action($values);
606
607
608
609
610
611
612

            // Tell the watchlist that the view changed
            $data = (object)array(
                'view' => $this->get('id'),
            );
            activity_occurred('watchlist', $data);

613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
            if (!defined('JSON')) {
                $message = $this->get_viewcontrol_ok_string($action);
            }
            $success = true;
        }
        catch (Exception $e) {
            // if we're in ajax land, just throw it
            // the handler will deal with the message.
            if (defined('JSON')) {
                throw $e;
            }
            $message = $this->get_viewcontrol_err_string($action) . ': ' . $e->getMessage();
        }
        if (!defined('JSON')) {
            // set stuff in the session and redirect
            $fun = 'add_ok_msg';
            if (!$success) {
630
                $fun = 'add_error_msg';
631
632
            }
            $SESSION->{$fun}($message);
633
            redirect('/view/blocks.php?id=' . $this->get('id') . '&c=' . $category . '&new=' . $new);
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
        }
        return array('message' => $message, 'data' => $returndata);
    }

    /** 
     * Parses the string and returns a hash of values
     *
     * @param string $action expects format name_value_name_value
     *                       where values are all numeric
     * @return array associative
    */
    private static function get_values_for_action($action) {
        $values = array();
        $bits = explode('_', $action);
        if ((count($bits) % 2) == 1) {
            throw new ParamOutOfRangeException(get_string('invalidviewaction', 'error', $action));
        }
        $lastkey = null;
        foreach ($bits as $index => $bit) {
            if ($index % 2 == 0) { 
                $lastkey = $bit;
            }
            else {
                $values[$lastkey] = $bit;
            }
        }
        return $values;
    }

663
664
    /**
    * builds up the data structure for  this view
665
666
    * @param boolean $force force a re-read from the database
    *                       use this if a column is dirty
667
668
669
    * @private
    * @return void
    */
670
671
    private function build_column_datastructure($force=false) {
        if (!empty($this->columns) && empty($force)) { // we've already built it up
672
673
674
            return;
        }

Penny Leach's avatar
Penny Leach committed
675
676
677
678
        $sql = 'SELECT bi.*
            FROM {block_instance} bi
            WHERE bi.view = ?
            ORDER BY bi.column, bi.order';
679
680
681
682
683
684
685
686
687
        if (!$data = get_records_sql_array($sql, array($this->get('id')))) {
            $data = array();
        }

        // fill up empty columns array keys
        for ($i = 1; $i <= $this->get('numcolumns'); $i++) {
            $this->columns[$i] = array('blockinstances' => array());
        }

688
689
690
691
692
693
694
695
696
697
698
699
700
        // Set column widths
        if ($this->get('numcolumns') > 1) {
            $layout = $this->get('layout');
            if ($layout) {
                $i = 0;
                // The get_field also verifies the layout is correct for the
                // number of columns in the view
                foreach (explode(',', get_field('view_layout', 'widths', 'id', $layout, 'columns', $this->get('numcolumns'))) as $width) {
                    $this->columns[++$i]['width'] = $width;
                }
            }
        }

701
        foreach ($data as $block) {
702
            require_once(get_config('docroot') . 'blocktype/lib.php');
703
            $b = new BlockInstance($block->id, (array)$block);
704
            $this->columns[$block->column]['blockinstances'][] = $b;
705
706
707
708
709
710
711
712
713
714
715
716
        }

    }

    /*
    * returns the datastructure for the view's column(s)
    *
    * @param int $column optional, defaults to returning all columns
    * @return mixed array
    */
    public function get_column_datastructure($column=0) {
        // make sure we've already built up the structure
717
718
719
720
721
        $force = false;
        if (array_key_exists($column, $this->dirtycolumns)) {
            $force = true;
        }
        $this->build_column_datastructure($force);
722
723
724
725
726
727

        if (empty($column)) {
            return $this->columns;
        }

        if (!array_key_exists($column, $this->columns)) {
728
            throw new ParamOutOfRangeException(get_string('invalidcolumn', 'view', $column));
729
730
731
732
733
        }


        return $this->columns[$column];
    }
734
735

    // ******** functions to do with the view creation ui ************** //
736
737
738
739
740
741
    
    /**
     * small wrapper around get_string to return a success string
     * for the given view control function
     * @param string $functionname the functionname that was called
     */
742
743
744
745
    public function get_viewcontrol_ok_string($functionname) {
        return get_string('success.' . $functionname, 'view');
    }

746
747
748
749
750
    /**
     * small wrapper around get_string to return an error string
     * for the given view control function
     * @param string $functionname the functionname that was called
     */
751
752
753
754
755
    public function get_viewcontrol_err_string($functionname) {
        return get_string('err.' . $functionname, 'view');
    }


756
757
758
    /**
     * Returns the HTML for the columns of this view
     */
759
    public function build_columns($editing=false) {
760
761
762
763
        $numcols = $this->get('numcolumns');

        $result = '';
        for ($i = 1; $i <= $numcols; $i++) {
764
            $result .= $this->build_column($i, $editing);
765
766
767
768
769
770
771
772
773
774
        }

        return $result;
    }

    /**
     * Returns the HTML for a particular column
     *
     * @param int  $column     The column to build
     */
775
    public function build_column($column, $editing=false) {
776
        global $USER;
777
778
        $data = $this->get_column_datastructure($column);

779
780
781
782
        if ($editing) {
            $renderfunction = 'render_editing';
        }
        else {
783
784
            $renderfunction = 'render_viewing';
        }
785
786
        $blockcontent = '';
        foreach($data['blockinstances'] as $blockinstance) {
787
788
789
790
791
792
793
794
795
796
            $result = $blockinstance->$renderfunction($blockinstance->get('id') == $this->blockinstance_currently_being_configured);
            if ($editing) {
                $blockcontent .= $result['html'];
                // NOTE: build_column is always called in the context of column
                // operations, so the javascript returned, which is currently
                // for configuring block instances only, is not necessary
            }
            else {
                $blockcontent .= $result;
            }
797
798
        }

799
800
801
802
803
804
805
806
        // Widths don't appear to apply to divs unless they have at least
        // _some_ content - at least in gecko (make a view with a particular
        // layout like 25/50/25 and make the middle column empty and you'll see
        // what I mean)
        if ($blockcontent == '') {
            $blockcontent = '&nbsp;';
        }

807
808
809
810
811
812
        $smarty = smarty_core();
        $smarty->assign('javascript',  defined('JSON'));
        $smarty->assign('column',      $column);
        $smarty->assign('numcolumns',  $this->get('numcolumns'));
        $smarty->assign('blockcontent', $blockcontent);

813
814
815
816
        if (isset($data['width'])) {
            $smarty->assign('width', intval($data['width']));
        }

817
        $smarty->assign('addremovecolumns', $USER->get_account_preference('addremovecolumns'));
818

819
820
821
        if ($editing) {
            return $smarty->fetch('view/columnediting.tpl');
        }
822
        return $smarty->fetch('view/columnviewing.tpl');
823
824
    }

825
826
827
828
829
830
831
832
833
    /**
     * adds a block with the given type to a view
     * 
     * @param array $values parameters for this function
     *                      blocktype => string name of blocktype to add
     *                      column    => int column to add to
     *                      order     => position in column
     * 
     */
834
    public function addblocktype($values) {
835
836
837
838
839
        $requires = array('blocktype', 'column', 'order');
        foreach ($requires as $require) {
            if (!array_key_exists($require, $values) || empty($values[$require])) {
                throw new ParamOutOfRangeException(get_string('missingparam'. $require, 'error'));
            }
840
841
842
843
844
845
846
847
848
849
850
851
852
853
        }
        safe_require('blocktype', $values['blocktype']);
        $bi = new BlockInstance(0,
            array(
                'blocktype'  => $values['blocktype'],
                'title'      => call_static_method(generate_class_name('blocktype', $values['blocktype']), 'get_title'), 
                'view'       => $this->get('id'),
                'column'     => $values['column'],
                'order'      => $values['order'],
            )
        );
        $this->shuffle_column($values['column'], $values['order']);
        $bi->commit();
        $this->dirtycolumns[$values['column']] = 1;
854
855

        if ($values['returndata']) {
856
            // Make sure it's in configure mode if it has configuration
857
            return $bi->render_editing(call_static_method(generate_class_name('blocktype', $values['blocktype']), 'has_instance_config'), true);
858
        }
859
860
    }

861
862
863
864
865
866
    /** 
     * deletes a block instance from the view
     *
     * @param array $values parameters for this function
     *                      id => int id of blockinstance to remove
     */
867
    public function removeblockinstance($values) {
868
869
870
        if (!array_key_exists('id', $values) || empty($values['id'])) {
            throw new ParamOutOfRangeException(get_string('missingparamid', 'error'));
        }
871
872
873
        require_once(get_config('docroot') . 'blocktype/lib.php');
        $bi = new BlockInstance($values['id']); // get it so we can reshuffle stuff
        db_begin();
874
        $bi->delete();
875
876
877
878
879
        $this->shuffle_column($bi->get('column'), null, $bi->get('order'));
        db_commit();
        $this->dirtycolumns[$bi->get('column')] = 1;
    }

880
881
882
883
884
885
886
887
    /**
    * moves a block instance to a specified location
    *
    * @param array $values parameters for this function
    *                      id     => int of block instance to move
    *                      column => int column to move to
    *                      order  => position in new column to insert at
    */
888
    public function moveblockinstance($values) {
889
890
891
892
893
894
        $require = array('id', 'column', 'order');
        foreach ($require as $require) {
            if (!array_key_exists($require, $values) || empty($values[$require])) {
                throw new ParamOutOfRangeException(get_string('missingparam' . $require, 'error'));
            }
        }
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
        require_once(get_config('docroot') . 'blocktype/lib.php');
        $bi = new BlockInstance($values['id']);
        db_begin();
        // moving within the same column
        if ($bi->get('column') == $values['column']) {
            if ($values['order'] == $bi->get('order') + 1
                || $values['order'] == $bi->get('order') -1) {
                // we're switching two, it's a bit different
                // set the one we're moving to out of range (to 0)
                set_field('block_instance', 'order', 0,                 'view', $this->get('id'), 'column', $values['column'], 'order', $values['order']);
                // set the new order
                set_field('block_instance', 'order', $values['order'],  'view', $this->get('id'), 'column', $values['column'], 'order', $bi->get('order'));
                // move the old one back to where the moving one was.
                set_field('block_instance', 'order', $bi->get('order'), 'view', $this->get('id'), 'column', $values['column'], 'order', 0);
                // and set it in the object for good measure.
                $bi->set('order', $values['order']);
            }
912
913
914
915
916
917
918
            else if ($values['order'] == $this->get_current_max_order($values['column'])) {
                // moving to the very bottom
                set_field('block_instance', 'order', 0, 'view', $this->get('id'), 'column', $values['column'], 'order', $bi->get('order'));
                $this->shuffle_helper('order', 'down', '>=', $bi->get('order'), '"column" = ?', array($bi->get('column')));
                set_field('block_instance', 'order', $values['order'], 'view', $this->get('id'), 'column', $values['column'], 'order', 0);
                $bi->set('order', $values['order']);
            }
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
            else {
                $this->shuffle_column($bi->get('column'), $values['order'], $bi->get('order'));
            }
        } 
        // moving to another column
        else {
            // first figure out if we've asked to add it somewhere sensible
            // eg if we're moving a low down block into an empty column
            $newmax = $this->get_current_max_order($values['column']);
            if ($values['order'] > $newmax+1) {
                $values['order'] = $newmax+1;
            }
            // remove it from the old column
            $this->shuffle_column($bi->get('column'), null, $bi->get('order'));
            // and make a hole in the new column
            $this->shuffle_column($values['column'], $values['order']);
        }
        $bi->set('column', $values['column']);
        $bi->set('order', $values['order']);
        $bi->commit();
        $this->dirtycolumns[$bi->get('column')] = 1;
        $this->dirtycolumns[$values['column']] = 1;
        db_commit();
    }

944

945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
    private $blockinstance_currently_being_configured = 0;

    /**
     * Sets what blockinstance is currently being edited
     * TODO: use get()
     */
    public function set_blockinstance_currently_being_configured($id) {
        $this->blockinstance_currently_being_configured = $id;
    }

    public function get_blockinstance_currently_being_configured() {
        return $this->blockinstance_currently_being_configured;
    }

    /**
     * Configures a blockinstance
     *
     * @param array $values parameters for this function
     */
    public function configureblockinstance($values) {
965
966
        require_once(get_config('docroot') . 'blocktype/lib.php');
        $bi = new BlockInstance($values['id']);
967
        return $bi->build_configure_form();
968
969
    }

970
971
972
973
974
975
976
977
978
    /**
     * adds a column to a view
     *
     * @param array $values parameters for this function
     *                      before => int column to insert the new column before
     *                      returndata => boolean whether to return the html 
     *                                    for the new column or not (ajax requests need this)
     *
     */
979
    public function addcolumn($values) {
980
981
982
        if (!array_key_exists('before', $values) || empty($values['before'])) {
            throw new ParamOutOfRangeException(get_string('missingparamcolumn', 'error'));
        }
983
984
985
986
987
        db_begin();
        $this->set('numcolumns', $this->get('numcolumns') + 1);
        if ($values['before'] != ($this->get('numcolumns') + 1)) {
            $this->shuffle_helper('column', 'up', '>=', $values['before']);
        }
988
        $this->set('layout', null);
989
990
991
        $this->commit();
        // @TODO this could be optimised by actually moving the keys around,
        // but I don't think there's much point as the objects aren't persistent
992
        // unless we're in ajax land, in which case it would be an optimisation
993
994
995
996
997
        for ($i = $values['before']; $i <= $this->get('numcolumns'); $i++) {
            $this->dirtycolumns[$i] = 1;
        }
        $this->columns[$this->get('numcolumns')] = null; // set the key 
        db_commit();
998
        if ($values['returndata']) {
999
            return $this->build_column($values['before'], true);
1000
        }