artefactchooser.php 16.7 KB
Newer Older
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)
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.
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.
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/>.
18
19
20
 *
 * @package    mahara
 * @subpackage form-element
21
 * @author     Catalyst IT Ltd
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
24
25
26
27
28
 *
 */

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

29
$pagination_js = '';
30
31
32
33
34
35
36
37
/**
 * Provides a mechanism for choosing one or more artefacts from a list of them.
 *
 * @param Pieform  $form    The form to render the element for
 * @param array    $element The element to render
 * @return string           The HTML for the element
 */
function pieform_element_artefactchooser(Pieform $form, $element) {
38
    global $USER, $pagination_js;
39
40

    $value = $form->get_value($element);
41
    $element['offset'] = param_integer('offset', 0);
42
    list($html, $pagination, $count) = View::build_artefactchooser_data($element, $form->get_property('viewgroup'), $form->get_property('viewinstitution'));
43

44
    $smarty = smarty_core();
45
    $smarty->assign('datatable', $element['name'] . '_data');
46
    $smarty->assign('artefacts', $html);
47
48
    $smarty->assign('pagination', $pagination['html']);

49
50
51
    $formname = $form->get_name();
    $smarty->assign('blockinstance', substr($formname, strpos($formname, '_') + 1));

52
53
54
    // Save the pagination javascript for later, when it is asked for. This is 
    // messy, but can't be helped until Pieforms goes to a more OO way of 
    // managing stuff.
55
    $pagination_js = $pagination['javascript'];
56

57
    $baseurl = View::make_base_url();
58
59
60
61
    $smarty->assign('browseurl', $baseurl);
    $smarty->assign('searchurl', $baseurl . '&s=1');
    $smarty->assign('searchable', !empty($element['search']));

62
63
64
65
66
67
68
69
    return $smarty->fetch('form/artefactchooser.tpl');
}

function pieform_element_artefactchooser_get_value(Pieform $form, $element) {
    $name = $element['name'];

    $global = ($form->get_property('method') == 'get') ? $_GET : $_POST;

70
71
    if (isset($global[$name]) || isset($global["{$name}_onpage"])) {
        $value  = (isset($global[$name])) ? $global[$name] : array();
72

73
74
75
76
77
        if ($element['selectone']) {
            if (!$value) {
                return null;
            }

78
            if (preg_match('/^\d+$/', $value)) {
79
80
                return intval($value);
            }
81
        }
82
83
84
85
        else {
            $onpage = (isset($global["{$name}_onpage"])) ? $global["{$name}_onpage"] : array();
            $selected = (is_array($value)) ? array_map('intval', array_keys($value)) : array();
            $default  = (is_array($element['defaultvalue'])) ? $element['defaultvalue'] : array();
86

87
88
89
            // 1) Start with what's currently available
            // 2) Remove everything on the page that was active when submitted
            // 3) Add in everything that was selected
90
            $value = array_merge(array_diff($default, $onpage), $selected);
91
            return array_map('intval', $value);
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        }

        throw new PieformException("Invalid value for artefactchooser form element '$name' = '$value'");
    }

    if (isset($element['defaultvalue'])) {
        return $element['defaultvalue'];
    }

    return null;
}

//function pieform_element_artefactchooser_rule_required(Pieform $form, $value, $element) {
//    if (is_array($value) && count($value)) {
//        return null;
//    }
//
//    return $form->i18n('rule', 'required', 'required', $element);
//}

function pieform_element_artefactchooser_set_attributes($element) {
    if (!isset($element['selectone'])) {
        $element['selectone'] = true;
    }
    if (!isset($element['limit'])) {
        $element['limit'] = 10;
    }
119
120
121
    if (!isset($element['template'])) {
        $element['template'] = 'form/artefactchooser-element.tpl';
    }
122
123
124
    if (!isset($element['search'])) {
        $element['search'] = true;
    }
125

126
127
128
129
    return $element;
}

/**
130
131
132
 * Extension by Mahara. This api function returns the javascript required to 
 * set up the element, assuming the element has been placed in the page using 
 * javascript. This feature is used in the views interface.
133
134
135
136
137
138
139
 *
 * In theory, this could go upstream to pieforms itself
 *
 * @param Pieform $form     The form
 * @param array   $element  The element
 */
function pieform_element_artefactchooser_views_js(Pieform $form, $element) {
140
    global $pagination_js;
141
142
143
144
145
146
147

    // NOTE: $element['name'] is not set properly at this point
    $element = pieform_element_artefactchooser_set_attributes($element);
    $element['name'] = (!empty($element['selectone'])) ? 'artefactid' : 'artefactids';

    $pagination_js = 'var p = ' . $pagination_js;

148
149
    // TODO: This is quite a lot of javascript to be sending inline, especially the ArtefactChooserData 
    // class.
150
151
152
153
154
155
156

    if (!empty($element['selectone'])) {
        $artefactchooserdata = '';
    }
    else {
        $artefactchooserdata = 'new ArtefactChooserData();';
    }
157
    $pagination_js .= <<<EOF
158
159
160
161
var ul = getFirstElementByTagAndClassName('ul', 'artefactchooser-tabs', '{$form->get_name()}_{$element['name']}_container');
var doneBrowse = false;
var browseA = null;
var searchA = null;
162
var browseTabCurrent = true;
163
164
165
166
167
168
169
170
171
172
173
174
175
176
if (ul) {
    forEach(getElementsByTagAndClassName('a', null, ul), function(a) {
        p.rewritePaginatorLink(a);
        if (!doneBrowse) {
            doneBrowse = true;

            browseA = a;
            // Hide the search form
            connect(a, 'onclick', function(e) {
                hideElement('artefactchooser-searchform');
                removeElementClass(searchA.parentNode, 'current');
                addElementClass(browseA.parentNode, 'current');
                browseA.blur();
                $('artefactchooser-searchfield').value = ''; // forget the search for now, easier than making the tabs remember it
177
                if (!browseTabCurrent) {
178
                    {$artefactchooserdata}
179
180
                    browseTabCurrent = true;
                }
181
182
183
184
185
186
187
188
189
190
191
192
                e.stop();
            });
        }
        else {
            searchA = a;

            // Display the search form
            connect(a, 'onclick', function(e) {
                showElement('artefactchooser-searchform');
                removeElementClass(browseA.parentNode, 'current');
                addElementClass(searchA.parentNode, 'current');
                $('artefactchooser-searchfield').focus();
193
                if (browseTabCurrent) {
194
                    {$artefactchooserdata}
195
196
                    browseTabCurrent = false;
                }
197
198
                e.stop();
            });
199

200
201
202
203
204
205
206
            connect('artefactchooser-searchfield', 'onkeypress', function(e) {
                if (e.key().code == 13) { // enter pressed - submitting form
                    e.stop();
                    signal('artefactchooser-searchsubmit', 'onclick', true);
                }
            });

207
208
            // Wire up the search button
            connect('artefactchooser-searchsubmit', 'onclick', function(e) {
209
210
211
                if (e._event != true) {
                    e.stop();
                }
212

213
214
215
216
217
218
219
                var loc = searchA.href.indexOf('?');
                var queryData = [];
                if (loc != -1) {
                    queryData = parseQueryString(searchA.href.substring(loc + 1, searchA.href.length));
                    queryData.extradata = serializeJSON(p.extraData);
                    queryData.search = $('artefactchooser-searchfield').value;
                }
220

221
                sendjsonrequest(p.jsonScript, queryData, 'GET', function(data) {
222
223
                    var tbody = getFirstElementByTagAndClassName('tbody', null, p.datatable);
                    if (tbody) {
224
225
226
227
                        if (
                            (document.all && document.documentElement && typeof(document.documentElement.style.maxHeight) != "undefined" && !window.opera)
                            ||
                            (/Konqueror|AppleWebKit|KHTML/.test(navigator.userAgent))) {
228
229
                            var temp = DIV({'id':'ie-workaround'});
                            temp.innerHTML = '<table><tbody>' + data.data.tablerows + '</tbody></table>';
230
                            swapDOM(tbody, temp.childNodes[0].childNodes[0]);
231
                            removeElement(temp);
232
233
234
235
236
237
238
                        }
                        else {
                            // This does not work in IE and Konqueror, the tbody 
                            // innerHTML property is readonly.
                            // http://www.ericvasilik.com/2006/07/code-karma.html
                            tbody.innerHTML = data['data']['tablerows'];
                        }
239
                    }
240

241
                    {$artefactchooserdata}
242

243
                    // Update the pagination
244
245
246
247
                    if ($(p.id)) {
                        var tmp = DIV();
                        tmp.innerHTML = data['data']['pagination'];
                        swapDOM(p.id, tmp.firstChild);
248

249
250
                        // Run the pagination js to make it live
                        eval(data['data']['pagination_js']);
251

252
253
254
255
256
                        // Update the result count
                        var results = getFirstElementByTagAndClassName('div', 'results', p.id);
                        if (results) {
                            results.innerHTML = data['data']['results'];
                        }
257
                    }
258
                });
259
            });
260
261
262
        }
    });
}
263
264
265
EOF;
    if (empty($element['selectone'])) {
        $pagination_js .=<<<EOF
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
/**
 * Manages the problem of changing pages in the artefact chooser losing what 
 * things were selected/not selected
 */
function ArtefactChooserData() {
    var self = this;

    this.init = function() {
        self.insertElementContainers();
        self.connectPagination();
        self.connectCheckboxes();
        self.scrapeForOnpage();
        self.scrapeForSelected();
    }

    /**
     * Puts two containers into the DOM, that will each contain hidden form elements 
     * - one for all the elements on the current page of results, and one for 
     * the currently selected options.
     *
     * Clears out existing containers instead of making new ones, if containers 
     * already exist. This happens when changing tabs on the artefact chooser
     */
    this.insertElementContainers = function() {
        self.seenElementsContainer     = $('seen-elements-container');
        self.selectedElementsContainer = $('selected-elements-container');

        if (self.seenElementsContainer) {
            // Clear out the list of seen elements
            replaceChildNodes(self.seenElementsContainer);
        }
        else {
            self.seenElementsContainer = DIV({'id': 'seen-elements-container', 'style': 'display: none;'});
            insertSiblingNodesAfter('artefactchooser-body', self.seenElementsContainer);
        }

        if (self.selectedElementsContainer) {
            // Clear out the list of selected elements
            replaceChildNodes(self.selectedElementsContainer);
        }
        else {
            self.selectedElementsContainer = DIV({'id': 'selected-elements-container', 'style': 'display: none;'});
            insertSiblingNodesAfter('artefactchooser-body', self.selectedElementsContainer);
        }
    }

    /**
     * Connects pagination so that when a page is changed, we are told about it
     */
    this.connectPagination = function() {
        paginatorProxy.addObserver(self);
        connect(self, 'pagechanged', self.pageChanged);
    }

    /**
     * Connects checkboxes so when they're clicked we can deal with it
     */
    this.connectCheckboxes = function() {
        forEach(getElementsByTagAndClassName('input', 'artefactid-checkbox', 'artefactchooser-body'), function(checkBox) {
            connect(checkBox, 'onclick', partial(self.checkboxClicked, checkBox));
        });
    }

    /**
     * Find all hidden onpage inputs, and move them to the container, otherwise 
     * destroy them if they're already in there (which happens if we go to a 
     * page we've already seen)
     */
    this.scrapeForOnpage = function() {
        forEach(getElementsByTagAndClassName('input', 'artefactid-onpage', 'artefactchooser-body'), function(i) {
            var append = true;
            forEach(self.seenElementsContainer.childNodes, function(seen) {
                if (seen.value == i.value) {
                    append = false;
                    throw MochiKit.Iter.StopIteration;
                }
            });
            if (append) {
                appendChildNodes(self.seenElementsContainer, i);
            }
            else {
                // Element is surplus to requirements
                removeElement(i);
            }
        });
    }

    /**
     * Find all hidden currently selected inputs, and move them to the selected container
     */
    this.scrapeForSelected = function() {
        forEach(getElementsByTagAndClassName('input', 'artefactid-checkbox', 'artefactchooser-body'), function(i) {
            if (i.checked) {
                self.ensureSelectedElement(i);
            }
        });
    }

    /**
     * When a checkbox is clicked, update the list of selected inputs
     */
    this.checkboxClicked = function(checkbox) {
        if (checkbox.checked) {
            // Add to the list if it's not there
            self.ensureSelectedElement(checkbox);
        }
        else {
            // Remove from the list if it's there
            self.removeSelectedElement(checkbox);
        }
    }

    /**
     * When a pagination link is clicked, update the list of seen inputs
     */
    this.pageChanged = function(data) {
        self.scrapeForOnpage();
        if (findValue(self.seenOffsets, data.offset) == -1) {
            self.scrapeForSelected();
            self.seenOffsets.push(data.offset);
        }
        else {
            self.syncroniseCheckboxStateFromContainer();
        }
        self.connectCheckboxes();
    }

    /**
     * Ensures that the element we have been given is in the list of selected 
     * elements
     */
    this.ensureSelectedElement = function(element) {
        var append = true;
        forEach(self.selectedElementsContainer.childNodes, function(selected) {
            if (selected.name == element.name) {
                append = false;
                throw MochiKit.Iter.StopIteration;
            }
        });

        if (append) {
            appendChildNodes(self.selectedElementsContainer,
                INPUT({'type': 'hidden', 'name': element.name, 'value': 1})
            );
        }
    }

    /**
     * Ensures that the element we have been given is NOT in the list of 
     * selected elements
     */
    this.removeSelectedElement = function(element) {
        forEach(self.selectedElementsContainer.childNodes, function(selected) {
            if (selected.name == element.name) {
                removeElement(selected);
                throw MochiKit.Iter.StopIteration;
            }
        });
    }

    /**
     * Called when the user browses back to a page they have already seen. They 
     * may have added/removed what they have checked on that page, so we need 
     * to syncronise the display with their choices
     */
    this.syncroniseCheckboxStateFromContainer = function() {
        forEach(getElementsByTagAndClassName('input', 'artefactid-checkbox', 'artefactchooser-body'), function(checkbox) {
            checkbox.checked = false;
            forEach(self.selectedElementsContainer.childNodes, function(selected) {
                if (selected.name == checkbox.name) {
                    // Checkbox should be checked
                    checkbox.checked = true;
                    throw MochiKit.Iter.StopIteration;
                }
            });
        });
    }

    // Contains hidden elements representing every artefact we have seen, 
    // regardless of whether it has been selected
    this.seenElementsContainer = null;

    // Contains hidden elements representing every artefact that has been 
    // selected on any page we have seen
    this.selectedElementsContainer = null;

    // Pagination offsets we have already seen. We have always seen offset 0 
    // when we begin.
    this.seenOffsets = [0];

    self.init();
}

new ArtefactChooserData();

461
EOF;
462
    }
463
    return $pagination_js;
464
465
466
}

?>