profileicons.php 11.7 KB
Newer Older
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
 *
 */

define('INTERNAL', 1);
13
define('MENUITEM', 'content/profileicons');
14
define('SECTION_PLUGINTYPE', 'artefact');
15
define('SECTION_PLUGINNAME', 'file');
16
define('SECTION_PAGE', 'profileicons');
17

18
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
19
define('TITLE', get_string('profileicons', 'artefact.file'));
20

21
$settingsform = pieform_instance(array(
22
23
24
25
26
27
28
    'name'      => 'settings',
    'renderer'  => 'oneline',
    'autofocus' => false,
    'presubmitcallback' => '',
    'elements' => array(
        'default' => array(
            'type'  => 'submit',
29
            'value' => get_string('Default', 'artefact.file'),
30
31
        ),
        'delete' => array(
32
            'type'  => 'submit',
33
            'value' => get_string('Delete', 'artefact.file'),
34
        ),
35
36
37
38
39
    )
));

$uploadform = pieform(array(
    'name'   => 'upload',
40
    'class'  => 'form-upload',
41
42
43
    'jsform' => true,
    'presubmitcallback'  => 'preSubmit',
    'postsubmitcallback' => 'postSubmit',
44
    'plugintype' => 'artefact',
45
    'pluginname' => 'file',
46
47
48
    'elements' => array(
        'file' => array(
            'type' => 'file',
49
            'title' => get_string('profileicon', 'artefact.file'),
50
51
            'rules' => array('required' => true),
            'maxfilesize'  => get_max_upload_size(false),
52
53
54
        ),
        'title' => array(
            'type' => 'text',
55
            'title' => get_string('imagetitle', 'artefact.file'),
56
57
58
        ),
        'submit' => array(
            'type' => 'submit',
59
            'class' => 'btn-primary',
60
61
62
63
64
            'value' => get_string('upload')
        )
    )
));

65
66
$strnoimagesfound = json_encode(get_string('noimagesfound', 'artefact.file'));
$struploadingfile = json_encode(get_string('uploadingfile', 'artefact.file'));
67
$wwwroot = get_config('wwwroot');
68
$notfound = $THEME->get_image_url('no_userphoto');
69
70
71
72
73
74
if (!get_config('remoteavatars')) {
    $ravatar = $notfound;
}
else {
    $ravatar = remote_avatar($USER->get('email'), array('maxw' => '100', 'maxh' => '100'), $notfound);
}
75
76
$profileiconattachedtoportfolioitems = json_encode(get_string('profileiconattachedtoportfolioitems', 'artefact.file'));
$profileiconappearsinviews = json_encode(get_string('profileiconappearsinviews', 'artefact.file'));
77
$profileiconappearsinskins = json_encode(get_string('profileiconappearsinskins', 'artefact.file'));
78
$confirmdeletefile = json_encode(get_string('confirmdeletefile', 'artefact.file'));
79

80
$IJS = <<<EOF
81
82
83
84
formchangemanager.add('settings');

var profileiconschecker = formchangemanager.find('settings');

85
86
87
88
89
var table = new TableRenderer(
    'profileicons',
    'profileicons.json.php',
    [
        function(rowdata) {
90
            if (rowdata.id) {
91
92
              return jQuery('<td>', {'class': 'profileiconcell'})
                .append(jQuery('<img>', {'src': '{$wwwroot}thumb.php?type=profileiconbyid&maxsize=100&id=' + rowdata.id, 'alt': rowdata.title ? rowdata.title : rowdata.note}))[0];
93
94
            }
            else {
95
96
              return jQuery('<td>', {'class': 'profileiconcell'})
                .append(jQuery('<img>', {'src': '{$ravatar}', 'alt': rowdata.title ? rowdata.title : rowdata.note}))[0];
97
            }
98
99
        },
        function(rowdata) {
100
            return jQuery('<td>', {'text': rowdata.title ? rowdata.title : rowdata.note})[0];
101
102
103
        },
        function(rowdata) {
            var options = {
104
                'id': 'setdefault_' + rowdata.id,
105
106
107
108
                'type': 'radio',
                'name': 'd',
                'value': rowdata.id
            };
Penny Leach's avatar
Penny Leach committed
109
            if (rowdata['isdefault'] == 't' || rowdata['isdefault'] == 1) {
110
111
                options.checked = 'checked';
            }
112
113
114
            var label = jQuery('<label>', {'class': 'accessible-hidden sr-only', 'for': 'setdefault_' + rowdata.id, 'text': rowdata.default_str});
            return jQuery('<td>', {'class': 'defaultcell'})
                .append(jQuery('<input>', options).append(label))[0];
115
116
        },
        function(rowdata) {
117
118
119
120
121
            var options = {
                'id'      : 'markdelete_' + rowdata.id,
                'type'    : 'checkbox',
                'class'   : 'checkbox',
                'name'    : 'icons[' + rowdata.id + ']',
122
                'value'   : rowdata.attachcount + ',' + rowdata.viewcount + ',' + rowdata.skincount
123
124
125
            };
            if (!rowdata.id) {
                options.disabled = 'disabled';
126
            }
127
128
129
            var label =  jQuery('<label>',{'class': 'accessible-hidden sr-only', 'for': 'markdelete_' + rowdata.id, 'text': rowdata.delete_str});
            return jQuery('<td>',{'class': 'deletecell'})
              .append(jQuery('<input>', options), label)[0];
130
131
132
133
134
135
        }
    ]
);
table.updateOnLoad();
table.emptycontent = {$strnoimagesfound};

136
137
138
139
table.postupdatecallback = function(response) {
    profileiconschecker.init();
};

140
var uploadingMessage = jQuery('<tr><td>' + {$struploadingfile} + '</td></tr>') ;
141
142
143

function preSubmit(form, data) {
    formStartProcessing(form, data);
144
    uploadingMessage.insertAfter(jQuery('#upload_submit_container'));
145
146
147
}

function postSubmit(form, data) {
Naomi Guyer's avatar
Naomi Guyer committed
148
    // removeElement(uploadingMessage);
149
150
151
    table.doupdate();
    formStopProcessing(form, data);
    quotaUpdate();
152
153
154

    jQuery(form)[0].reset();
    jQuery('#upload_title').val('');
155
156
}

157
158
jQuery(function($) {
    $('#settings_delete').on('click', function(e) {
159
160
        profileiconschecker.set(FORM_SUBMITTED);

161
        // Find form
162
163
164
165
        var form = $(this).closest('form.pieform');
        $(form).find('input.checkbox').each(function () {
            var id = $(this).prop('name').match(/\d+/)[0];
            if ($(this).prop('checked')) {
166
                var counts = $(this).prop('value').split(',', 3);
167
168
169
170
171
172
173
                var warn = '';
                if (counts[0] > 0) {
                    warn += {$profileiconattachedtoportfolioitems} + ' ';
                }
                if (counts[1] > 0) {
                    warn += {$profileiconappearsinviews} + ' ';
                }
174
175
176
                if (counts[2] > 0) {
                    warn += {$profileiconappearsinskins} + ' ';
                }
177
178
179
                if (warn != '') {
                    warn += {$confirmdeletefile};
                    if (!confirm(warn)) {
180
                        e.preventDefault();
181
182
183
184
185
186
187
188
                        return false;
                    }
                }
            }
        });
    });
});

189
EOF;
190

191
$filesize = 0;
192
function upload_validate(Pieform $form, $values) {
193
    global $USER, $filesize;
194
    require_once('file.php');
195
196
197
198
199
200
201
202
    require_once('uploadmanager.php');

    $um = new upload_manager('file');
    if ($error = $um->preprocess_file()) {
        $form->set_error('file', $error);
        return false;
    }

203
204
    $imageinfo = getimagesize($values['file']['tmp_name']);
    if (!$imageinfo || !is_image_type($imageinfo[2])) {
205
        $form->set_error('file', get_string('filenotimage'));
206
        return false;
207
208
    }

209
    if (get_field('artefact', 'COUNT(*)', 'artefacttype', 'profileicon', 'owner', $USER->id) >= 5) {
210
        $form->set_error('file', get_string('onlyfiveprofileicons', 'artefact.file'));
211
        return false;
212
    }
213

214
    $filesize = $um->file['size'];
215
    if (!$USER->quota_allowed($filesize)) {
216
        $form->set_error('file', get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot')));
217
        return false;
218
219
    }

220
    // Check the file isn't greater than the max allowable size
221
222
    $width          = $imageinfo[0];
    $height         = $imageinfo[1];
223
224
225
    $imagemaxwidth  = get_config('imagemaxwidth');
    $imagemaxheight = get_config('imagemaxheight');
    if ($width > $imagemaxwidth || $height > $imagemaxheight) {
226
        $form->set_error('file', get_string('profileiconimagetoobig', 'artefact.file', $width, $height, $imagemaxwidth, $imagemaxheight));
227
    }
228
229
230
}

function upload_submit(Pieform $form, $values) {
231
    safe_require('artefact', 'file');
232

233
234
235
    $data = new stdClass;
    $data->title = $values['title'] ? $values['title'] : $values['file']['name'];

236
    try {
237
        ArtefactTypeProfileIcon::save_uploaded_file($values['file']['tmp_name'], $data);
238
    }
239
    catch (QuotaExceededException $e) {
240
        $form->json_reply(PIEFORM_ERR, array(
241
            'message' => get_string('profileiconuploadexceedsquota', 'artefact.file', get_config('wwwroot'))
242
243
        ));
    }
244
245
246
247
248
249
250
251
252
    catch (UploadException $e) {
        $form->json_reply(PIEFORM_ERR, array(
            'message' => get_string('uploadoffilefailed', 'artefact.file',  $data->title) . ': ' . $e->getMessage()
        ));
    }
    catch (Exception $e) {
        $form->json_reply(PIEFORM_ERR, array(
            'message' => get_string('uploadoffilefailed', 'artefact.file',  $data->title) . ': ' . $e->getMessage()
        ));
253
    }
254

255
    $form->json_reply(PIEFORM_OK, get_string('profileiconaddedtoimagesfolder', 'artefact.file', get_string('imagesdir', 'artefact.file')));
256
257
258
259
260
261
262
}

function settings_submit_default(Pieform $form, $values) {
    global $USER, $SESSION;

    $default = param_integer('d');

263
264
265
266
    if ($default) {
        if (1 != get_field('artefact', 'COUNT(*)', 'id', $default, 'artefacttype', 'profileicon', 'owner', $USER->id)) {
            throw new UserException(get_string('profileiconsetdefaultnotvalid', 'artefact.file'));
        }
267

268
269
270
271
272
        $USER->profileicon = $default;
    }
    else {
        $USER->profileicon = null;
    }
273
274
275
276
    $USER->commit();

    $SESSION->add_ok_msg(get_string('profileiconsdefaultsetsuccessfully', 'artefact.file'));
    redirect('/artefact/file/profileicons.php');
277
278
279
}

function settings_submit_delete(Pieform $form, $values) {
280
    require_once(get_config('docroot') . 'artefact/lib.php');
281
282
283
284
285
286
287
    require_once('file.php');
    global $USER, $SESSION;

    $icons = param_variable('icons', array());
    $icons = array_keys($icons);

    if ($icons) {
288
        db_begin();
289
290
291
292
        foreach ($icons as $icon) {
            $iconartefact = artefact_instance_from_id($icon);
            // Just to be sure
            if ($iconartefact->get('artefacttype') == 'profileicon' && $iconartefact->get('owner') == $USER->get('id')) {
293
294
295
                // Remove the skin background and update the skin thumbs
                require_once(get_config('libroot') . 'skin.php');
                Skin::remove_background($iconartefact->get('id'));
296
297
298
299
300
301
                $iconartefact->delete();
            }
            else {
                throw new AccessDeniedException();
            }
        }
302

303
        if (in_array($USER->get('profileicon'), $icons)) {
304
            $USER->profileicon = null;
305
            $USER->commit();
306
307
308
309
        }

        db_commit();

310
311
312
        $SESSION->add_ok_msg(
            get_string('filethingdeleted', 'artefact.file', get_string('nprofilepictures', 'artefact.file', count($icons)))
        );
313
314
    }
    else {
315
        $SESSION->add_info_msg(get_string('profileiconsnoneselected', 'artefact.file'));
316
317
    }

318
    redirect('/artefact/file/profileicons.php');
319
320
}

321
$smarty = smarty(
322
    array('tablerenderer'),
323
324
325
326
327
328
329
330
331
332
333
334
335
    array(),
    array(),
    array(
        'sideblocks' => array(
            array(
                'name'   => 'quota',
                'weight' => -10,
                'data'   => array(),
            ),
        ),
    )
);
$smarty->assign('INLINEJAVASCRIPT', $IJS);
336
337
338
339
340
$smarty->assign('uploadform', $uploadform);
// This is a rare case where we don't actually care about the form, because
// it only contains submit buttons (which we can just write as HTML), and
// the buttons need to be inside the tablerenderer.
$smarty->assign('settingsformtag', $settingsform->get_form_tag());
341
$smarty->assign('imagemaxdimensions', array(get_config('imagemaxwidth'), get_config('imagemaxheight')));
342
$smarty->display('artefact:file:profileicons.tpl');