aboutsummaryrefslogtreecommitdiff
path: root/extensions/Dashboard/lib/Legacy/Util.pm
blob: a7604aad00e251e6ac01aeb3887c9ad398049674 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Unified Dashboard Bugzilla Extension.
#
# The Initial Developer of the Original Code is "Nokia Corporation"
# Portions created by the Initial Developer are Copyright (C) 2010 the
# Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   David Wilson <ext-david.3.wilson@nokia.com>
#   Jari Savolainen <ext-jari.a.savolainen@nokia.com>
#

package Bugzilla::Extension::Dashboard::Legacy::Util;

use strict;
use warnings;

use Exporter 'import';
our @EXPORT = qw(
    dir_glob
    first_free_id
    get_mtime
    get_overlay_dir
    get_overlays_dir
    merge
    migrate_workspace
    overlay_from_dir
    overlays_for_user
    overlay_to_dir
    trim_workspace_overlays
);

use Data::Dumper;
use File::Basename;
use File::Copy qw(move);
use File::Path qw(mkpath remove_tree);
use File::Spec;
use List::Util qw(sum);
use POSIX qw(getpid strftime);
use Storable qw(store retrieve);

use Bugzilla::Constants;
use Bugzilla::Extension::Dashboard::Config;
use Bugzilla::Extension::Dashboard::Legacy::Schema;
use Bugzilla::User;
use Bugzilla::Util;


#
# Data helper functions.
#

# Given a list of hashrefs, return a new hashref which is the result of
# assigning the elements from each hash in order to an empty hash. Skips list
# items that aren't hashrefs.
sub merge {
    my $out = {};
    for my $hash (@_) {
        if(! UNIVERSAL::isa($hash, 'HASH')) {
            next;
        }

        while(my ($key, $value) = each(%$hash)) {
            $out->{$key} = $value;
        }
    }
    return $out;
};


#
# Filesystem helper functions.
#


# Create a directory if it doesn't already exist.
sub make_path {
    my ($path) = @_;

    if(-d $path) {
        return;
    }

    mkpath($path, {
        verbose => 0,
        mode    => 0755,
        error   => \my $err
    });

    if (@$err) {
        for my $diag (@$err) {
            my ($file, $message) = each %$diag;
            print "Problem making $file: $message\n";
        }
        die("Couldn't create $path");
    }
}


# Glob some pattern and detaint each returned result.
sub dir_glob {
    my @out;
    foreach my $path (glob File::Spec->catfile(@_)) {
        trick_taint $path;
        push @out, $path;
    }
    return @out;
}


# Return the modification time of a path in seconds since epoch.
sub get_mtime {
    my ($path) = @_;
    my @st = lstat $path;
    return $st[9];
}


# Find an unused overlay ID we can use to store the loaded page's unsaved
# changes to. When the user explicitly saves the workspace, this overlay is
# destroyed.
sub first_free_id {
    my ($dir) = @_;
    my $dest_dir;
    my $found = 0;
    my $id;

    make_path($dir);

    do {
        $id = time() | getpid();
        $dest_dir = File::Spec->catdir($dir, $id);
        $found = mkdir($dest_dir);
        if(! $found) {
            sleep 1;
        }
    } until($found);

    return int($id);
}


# Return a user's data directory.
sub get_user_dir {
    my ($user_id) = @_;
    $user_id = Bugzilla->user->id if !defined($user_id);
    trick_taint $user_id;

    my $ext_dir = File::Spec->catdir(bz_locations()->{datadir},
        'extensions/Dashboard');
    return File::Spec->catdir($ext_dir, $user_id);
}


# Return the directory containing the overlays for the given user.
sub get_overlays_dir {
    my ($user_id) = @_;
    return File::Spec->catdir(get_user_dir($user_id), 'overlay');
}


# Return the directory containing a particular overlay.
sub get_overlay_dir {
    my ($user_id, $overlay_id) = @_;
    return File::Spec->catdir(get_overlays_dir($user_id), $overlay_id);
}


#
# Widget IO functions.
#


# Write a list of widgets to the given directory, then delete any other widget
# files from the directory that weren't in the list.
sub widgets_to_dir {
    my ($dir, $widgets) = @_;

    my $paths;
    foreach my $widget (@{$widgets}) {
        my $path = File::Spec->catfile($dir, $widget->{id} . '.widget');
        store $widget, $path;
        $paths->{$path} = 1;
    }

    my @old = dir_glob($dir, '*.widget');
    unlink grep { !$paths->{$_} } @old;
}


# Return widgets from the given directory as an arrayref.
sub widgets_from_dir {
    my ($dir) = @_;
    my @widgets = map { retrieve $_; } dir_glob($dir, '*.widget');
    return [ map { parse(WIDGET_DEFS, $_) } @widgets ];
}


# Given an array ref of widget hashrefs, remove any private fields present.
sub blank_private_fields {
    my ($defs, $widgets) = @_;

    my @private;
    while(my ($field, $def) = each(%$defs)) {
        push @private, $field if $def->{private};
    }

    map { delete @$_{@private} } @$widgets;
}


#
# Overlay IO functions.
#


# Read an overlay from a directory.
sub overlay_from_dir {
    my ($user_id, $dir) = @_;

    my $path = File::Spec->catfile($dir, 'overlay');
    if(! -f $path) {
        die "Cannot load, overlay file missing.";
    }
    my $overlay = retrieve($path);

    $path = File::Spec->catfile($dir, 'preferences');
    if(-f $path) {
        $overlay = merge($overlay, retrieve($path));
    }

    normalize_columns($overlay);
    $overlay->{widgets} = widgets_from_dir($dir);

    if($user_id != $overlay->{user_id}) {
        blank_private_fields(WIDGET_DEFS, $overlay->{widgets});
    }

    return $overlay;
};


# Write an overlay to a directory.
sub overlay_to_dir {
    my ($dir, $overlay) = @_;

    my $tmp = $dir . '.tmp';
    if(-d $tmp) {
        remove_tree $tmp;
    }
    make_path $tmp;

    normalize_columns($overlay);
    $overlay = parse(OVERLAY_DEFS, $overlay);
    $overlay->{modified} = time;

    my $path = File::Spec->catfile($tmp, 'overlay');
    if($overlay->{pending}) {
        $path .= '.pending';
    }

    # Widgets are stored separately for now; copy $prefs to preserve the hash
    # for any callers.
    widgets_to_dir($tmp, $overlay->{widgets});
    my $copy = merge($overlay);
    delete $copy->{widgets};
    store $copy, $path;

    # Everything written, now drop any old dir and replace with the new one.
    if(-d $dir) {
        remove_tree $dir;
    }
    move $tmp, $dir;
};


# Return a list of all overlays for a user.
sub overlays_for_user {
    my ($user_id) = @_;
    $user_id = Bugzilla->user->id if !defined($user_id);

    my @overlays;
    foreach my $dir (dir_glob(get_overlays_dir($user_id), '*')) {
        my $active  = File::Spec->catfile($dir, 'overlay');
        my $prefs = File::Spec->catfile($dir, 'preferences');
        my $pending = File::Spec->catfile($dir, 'overlay.pending');

        my $base = {};
        if(-f $prefs) {
            $base = retrieve($prefs);
        }

        foreach my $path (($active, $pending)) {
            next if !-f $path;
            my $overlay = merge($base, retrieve($path));
            $overlay->{id} = int(basename dirname $path);
            $overlay->{user_id} = $user_id;
            $overlay->{user_login} = user_id_to_login($overlay->{owner});
            $overlay->{pending} = int($path eq $pending);
            if(! $overlay->{modified}) {
                $overlay->{modified} = get_mtime $path;
            }
            normalize_columns($overlay);
            push @overlays, parse(OVERLAY_DEFS, $overlay);
        }
    }

    return @overlays;
}


# Migrate an old style user workspace to a private overlay, if necessary.
sub migrate_workspace {
    my ($user_id) = @_;
    $user_id = Bugzilla->user->id if !defined($user_id);

    my $user_dir = get_user_dir($user_id);
    my $prefs_path = File::Spec->catfile($user_dir, 'preferences');
    if(! -f $prefs_path) {
        return;
    }

    my $mtime = get_mtime $prefs_path;
    my $time_str = strftime('%a, %Y-%m-%d %H:%M:%S', gmtime $mtime);

    my $prefs = retrieve($prefs_path)
        or die $!;
    normalize_columns($prefs);

    my $overlay = parse(OVERLAY_DEFS, merge($prefs, {
        created => $mtime,
        modified => $mtime,
        description => 'Last active workspace from old Dashboard',
        name => 'Workspace from ' . $time_str,
        owner => $user_id,
        widgets => widgets_from_dir($user_dir),
        workspace => 1,
    }));

    # Must remove 'overlay' file first as it shadows overlay subdirectory.
    my $overlay_path = File::Spec->catfile($user_dir, 'overlay');
    unlink $overlay_path if(-f $overlay_path);

    my $overlay_dir = get_overlay_dir($user_id, $mtime);
    overlay_to_dir $overlay_dir, $overlay;
    unlink $prefs_path, grep { -f $_ } $user_dir;
}


# Convert old Dashboard's list of column keys to a new style columns structure,
# if necessary. Then normalize the column widths.
sub normalize_columns {
    my ($prefs) = @_;

    if(! UNIVERSAL::isa($prefs->{columns}, "ARRAY")) {
        my @keys = grep /^column[0-9]/, sort keys %{$prefs};
        $prefs->{columns} = [ map { { width => $prefs->{$_} } } @keys ];
        map { delete $prefs->{$_} } @keys;
    }

    if(! @{$prefs->{columns}}) {
        $prefs->{columns} = [
            { width => 33 },
            { width => 33 },
            { width => 33 }
        ];
    }

    # If column totals don't add up to 100%, spread the difference out.
    my $total = sum map { $_->{width} } @{$prefs->{columns}};
    my $delta = int((100 - $total) / @{$prefs->{columns}});
    map { $_->{width} += $delta } @{$prefs->{columns}};
}


# Remove all but the newest <Params.dashboard_max_workspaces> 'workspace'
# overlays from a user's overlay directory.
sub trim_workspace_overlays {
    my @overlays = overlays_for_user(@_);
    my @workspaces = grep { $_->{workspace} == 1 } @overlays;
    @workspaces = sort { $b->{modified} <=> $a->{modified} } @workspaces;

    while(@workspaces > Bugzilla->params->{'dashboard_max_workspaces'}) {
        my $info = pop @workspaces;
        my $overlay = Bugzilla::Extension::Dashboard::Overlay->from_store(
            $info->{user_id}, $info->{id});
        $overlay->delete();
    }
}


1;