Sessions.pm 38.3 KB
Newer Older
1
2
3
4
5
## @file
# Session explorer

## @class
# Session explorer.
6
7
8
9
package Lemonldap::NG::Manager::Sessions;

use strict;
use Lemonldap::NG::Handler::CGI qw(:globalStorage :locationRules);
10
use Lemonldap::NG::Common::Apache::Session;    #inherits
11
12
use Lemonldap::NG::Common::Conf; #link protected conf Configuration
use Lemonldap::NG::Common::Conf::Constants; #inherits
13

14
#inherits Apache::Session
15

16
17
18
our $whatToTrace;
*whatToTrace = \$Lemonldap::NG::Handler::_CGI::whatToTrace;

19
our $VERSION = '0.11';
20

21
use base qw(Lemonldap::NG::Handler::CGI);
22

23
24
25
26
27
28
29
30
## @cmethod Lemonldap::NG::Manager::Sessions new(hashRef args)
# Constructor.
# @param $args Arguments for Lemonldap::NG::Handler::CGI::new(). Must contains
# 3 keys for Lemonldap::NG::Manager::Sessions:
# - jqueryUri HTTP path to jquery.js
# - personnalCss Optional HTTP path to custom CSS file
# - imagePath HTTP path to the images directory
# @return New Lemonldap::NG::Manager::Sessions object
31
32
33
sub new {
    my ( $class, $args ) = @_;
    my $self = $class->SUPER::new($args)
34
35
      or $class->abort( 'Unable to start ' . __PACKAGE__,
        'See Apache logs for more' );
36
37
38
39
40
41
42
43
44
45
46
47
48
49

    # Try to get configuration values from local configuration
    my $config = Lemonldap::NG::Common::Conf->new( $self->{configStorage} );
    unless ( $config ) {
        $self->abort( "Unable to start",
        "Configuration not loaded\n" . $Lemonldap::NG::Common::Conf::msg );
    }
    my $localconf = $config->getLocalConf( MANAGERSECTION );

    if ( $localconf ) {
        $self->{$_} = $args->{$_} || $localconf->{$_} foreach ( keys %$localconf );
    }

    # Check some paramaters
50
    foreach (qw(jqueryUri personnalCss imagePath)) {
51
52
        $self->{$_}
          or $self->lmLog( "$_ is not set, falling to default value", 'debug' );
53
54
    }
    eval "use $globalStorage";
55
    $class->abort( "Unable to load $globalStorage", $@ ) if ($@);
56
57
58
    return $self;
}

Yadd's avatar
Yadd committed
59
## @method void process()
60
# Main method.
61
62
63
64
sub process {
    my $self = shift;

    if ( $ENV{PATH_INFO} eq "/css" ) {
65
        print $self->header_public( $ENV{SCRIPT_FILENAME}, -type => 'text/css',
66
67
68
69
70
        );
        $self->css;
        exit;
    }
    elsif ( $ENV{PATH_INFO} eq "/js" ) {
71
72
        print $self->header_public( $ENV{SCRIPT_FILENAME},
            -type => 'text/javascript', );
73
74
75
76
        $self->js;
        exit;
    }

77
78
79
    # Check if we use X-FORWARDED-FOR header for IP
    my $ipField = $self->{useXForwardedForIP} ? "xForwardedForAddr" : "ipAddr";

80
81
82
83
84
85
86
87
88
89
    # Beginning of the job

    # User connected from more than 1 IP
    if ( $self->param('doubleIp') ) {
        my ( $byUid, $byIp );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
                my $id    = shift;
Yadd's avatar
Yadd committed
90
91
92
                next if ( $entry->{_httpSessionType} );
                push @{ $byUid->{ $entry->{$whatToTrace} }
                      ->{ $entry->{$ipField} } },
93
94
95
96
97
98
99
100
101
102
103
104
                  { id => $id, _utime => $entry->{_utime} };
                undef;
            }
        );
        $self->start('Sessions multi-IP');
        $self->window("Sessions multi-IP");
        foreach my $uid (
            sort { ( keys %{ $byUid->{$b} } ) <=> ( keys %{ $byUid->{$a} } ) }
            keys %$byUid
          )
        {
            last if ( ( keys %{ $byUid->{$uid} } ) == 1 );
105
            print "<li id=\"di$uid\" class=\"closed\"><span>$uid</span><ul>";
106
            foreach my $ip ( sort keys %{ $byUid->{$uid} } ) {
107
                print "<li class=\"open\" id=\"di$ip\"><span>$ip</span><ul>";
Yadd's avatar
Yadd committed
108
109
110
                foreach my $session ( sort { $a->{_utime} <=> $b->{_utime} }
                    @{ $byUid->{$uid}->{$ip} } )
                {
111
112
                    print
"<li id=\"di$session->{id}\"><span onclick=\"display('$session->{id}');\">"
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
                      . localtime( $session->{_utime} )
                      . "</span></li>";
                }
                print "</ul></li>";
            }
            print "</ul></li>";
        }
        $self->end();
    }

    # Request for IP addresses
    elsif ( my $req = $self->param('fullip') ) {
        my $byUid;
        my $reip = quotemeta($req);
        $reip =~ s/\\\*/\.\*/g;
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
                my $id    = shift;
Yadd's avatar
Yadd committed
133
                next if ( $entry->{_httpSessionType} );
134
                if ( $entry->{$ipField} eq $reip ) {
135
                    push @{ $byUid->{ $entry->{$ipField} }
136
                          ->{ $entry->{$whatToTrace} } },
137
138
139
140
141
142
143
144
                      { id => $id, _utime => $entry->{_utime} };
                }
                undef;
            }
        );
        $self->start("IP : $req");
        $self->window("$req");
        foreach my $ip ( sort keys %$byUid ) {
145
            print "<li id=\"fi$ip\"><span>$ip</span><ul>";
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
            foreach my $uid ( sort keys %{ $byUid->{$ip} } ) {
                $self->ajaxNode(
                    $uid,
                    $uid
                      . (
                        @{ $byUid->{$ip}->{$uid} } > 1
                        ? " <i><u><small>("
                          . @{ $byUid->{$ip}->{$uid} }
                          . " sessions)</small></u></i>"
                        : ''
                      ),
                    "uid=$uid"
                );
            }
            print "</ul></li>";
        }
        $self->end();
    }

    # Request for users
    elsif ( my $req = $self->param('fulluid') ) {
        my $byUid;
        my $reuser = quotemeta($req);
        $reuser =~ s/\\\*/\.\*/g;
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
                my $id    = shift;
Yadd's avatar
Yadd committed
175
                next if ( $entry->{_httpSessionType} );
176
177
                if ( $entry->{$whatToTrace} =~ /^$reuser$/ ) {
                    push @{ $byUid->{ $entry->{$whatToTrace} } },
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
                      { id => $id, _utime => $entry->{_utime} };
                }
                undef;
            }
        );
        $self->start("Users : $req");
        $self->window("$req");
        foreach my $uid ( sort keys %$byUid ) {
            $self->ajaxNode(
                $uid,
                $uid
                  . (
                    @{ $byUid->{$uid} } > 1
                    ? " <i><u><small>("
                      . @{ $byUid->{$uid} }
                      . " sessions)</small></u></i>"
                    : ''
                  ),
                "uid=$uid"
            );
        }
        $self->end();
    }

    # Ajax request to delete a session
    elsif ( my $id = $self->param('delete') ) {
        my %h;
        print $self->header( -type => 'text/html; charset=utf8' );
        eval { tie %h, $globalStorage, $id, $globalStorageOptions; };
        if ($@) {
            print "<strong>Error : $@</strong>\n";
        }
        else {
            my $uid = $h{uid};
Yadd's avatar
Yadd committed
212
            if ( $h{_httpSession} ) {
213
                my %h2;
Yadd's avatar
Yadd committed
214
215
216
217
218
                eval {
                    tie %h2, $globalStorage, $h{_httpSession},
                      $globalStorageOptions;
                    tied(%h2)->delete();
                };
219
220
221
222
                if ($@) {
                    print "<strong>Error : $@</strong><br/>";
                }
            }
223
224
            eval { tied(%h)->delete(); };
            if ($@) {
225
                print "<strong>Error : $@</strong><br/>";
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
            }
            else {
                print "<strong>Session effac&eacute;e ($uid)</strong>";
            }

        }
    }

    # Ajax request to dump a session
    elsif ( my $id = ( $self->param('session') || $self->param('id') ) ) {
        my %h;
        print $self->header( -type => 'text/html; charset=utf8' );
        eval { tie %h, $globalStorage, $id, $globalStorageOptions; };
        if ($@) {
            print "<strong>Error : $@</strong>\n";
        }
        else {
            print
"<input type=\"button\" onclick=\"del('$id');\" value=\"Effacer la session\" /><p><b>Session d&eacute;marr&eacute;e le</b> "
              . localtime( $h{_utime} )
              . '</p><p><b>Membre des groupes SSO :</b><ul>';
Yadd's avatar
Yadd committed
247
            print "<li>$_</li>" foreach ( sort split /\s+/, $h{groups} );
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
            print '</ul></p>';
            print
'<p><b>Attributs et macros :</b></p><table border="0" witdh="100%">';
            foreach my $attr ( sort keys %h ) {
                next if ( $attr =~ /^(?:_utime|groups)$/ );
                print '<tr valign="top"><th style="text-align:left;">'
                  . htmlquote($attr)
                  . '</th><td>:</td><td>'
                  . htmlquote( $h{$attr} )
                  . '</td></tr>'
                  if ( $h{$attr} );
            }
            print '</table>';
            untie %h;
        }
    }

265
266
267
268
269
270
271
272
273
    # Ajax request to see users by IP
    elsif ( my $ip = $self->param('uidByIp') ) {
        my $byUser;
        print $self->header( -type => 'text/html; charset=utf8' );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
                my $id    = shift;
Yadd's avatar
Yadd committed
274
                next if ( $entry->{_httpSessionType} );
275
                if ( $entry->{$ipField} eq $ip ) {
276
                    push @{ $byUser->{ $entry->{$whatToTrace} } },
277
278
279
280
281
                      { id => $id, _utime => $entry->{_utime} };
                }
                undef;
            }
        );
282
        foreach my $user ( sort keys %$byUser ) {
283
            print "<li id=\"ip$user\"><span>$user</span><ul>";
Yadd's avatar
Yadd committed
284
285
286
            foreach my $session ( sort { $a->{_utime} <=> $b->{_utime} }
                @{ $byUser->{$user} } )
            {
287
288
                print
"<li id=\"ip$session->{id}\"><span onclick=\"display('$session->{id}');\">"
289
290
291
292
293
294
295
                  . localtime( $session->{_utime} )
                  . "</span></li>";
            }
            print "</ul></li>";
        }
    }

296
297
298
299
300
301
302
303
304
    # Ajax request to see connexions from a user
    elsif ( my $uid = $self->param('uid') ) {
        my $byIp;
        print $self->header( -type => 'text/html; charset=utf8' );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
                my $id    = shift;
Yadd's avatar
Yadd committed
305
                next if ( $entry->{_httpSessionType} );
306
                if ( $entry->{$whatToTrace} eq $uid ) {
307
                    push @{ $byIp->{ $entry->{$ipField} } },
308
309
310
311
312
313
                      { id => $id, _utime => $entry->{_utime} };
                }
                undef;
            }
        );
        foreach my $ip ( sort keys %$byIp ) {
314
            print "<li class=\"open\" id=\"uid$ip\"><span>$ip</span><ul>";
Yadd's avatar
Yadd committed
315
316
317
            foreach my $session ( sort { $a->{_utime} <=> $b->{_utime} }
                @{ $byIp->{$ip} } )
            {
318
319
                print
"<li id=\"uid$session->{id}\"><span onclick=\"display('$session->{id}');\">"
320
321
322
323
324
325
326
327
                  . localtime( $session->{_utime} )
                  . "</span></li>";
            }
            print "</ul></li>";
        }
    }

    # Ajax request to list users starting by a letter
328
329
    elsif ( defined( $self->param('letter') ) ) {
        my $letter = $self->param('letter');
330
331
332
333
334
335
        my ($byUid);
        print $self->header( -type => 'text/html; charset=utf8' );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
Yadd's avatar
Yadd committed
336
                next if ( $entry->{_httpSessionType} );
337
338
                $entry->{$whatToTrace} =~ /^$letter/ or return undef;
                $byUid->{ $entry->{$whatToTrace} }++;
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
            },
        );
        foreach my $uid ( sort keys %$byUid ) {
            $self->ajaxNode(
                $uid,
                $uid
                  . (
                    $byUid->{$uid} > 1
                    ? " <i><u><small>($byUid->{$uid} sessions)</small></u></i>"
                    : ''
                  ),
                "uid=$uid"
            );
        }
    }

355
356
    # Display by IP classes
    elsif ( $self->param('ipclasses') ) {
357
        my $partial = $self->param('p') ? $self->param('p') . '.' : '';
358
359
360
361
362
363
        my $repartial = quotemeta($partial);
        my ( $byIp, $count );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
Yadd's avatar
Yadd committed
364
                next if ( $entry->{_httpSessionType} );
365
                $entry->{$ipField} =~ /^$repartial(\d+)/ or return undef;
366
367
368
369
370
371
372
                $byIp->{$1}++;
                $count++;
                undef;
            }
        );

        # Ajax request to list ip subclasses
373
        if ($partial) {
374
375
376
377
378
379
            print $self->header( -type => 'text/html; charset=utf8' );
        }

        # Display by IP subclass
        else {
            $self->start("Active sessions ($count)");
380
381
            $self->window(
                "Sessions par r&eacute;seaux <i><small>($count)</small></i>");
382
        }
383
384
385
386
387
388
389
390
391
392
        foreach my $ip ( sort { $a <=> $b } keys %$byIp ) {
            $self->ajaxNode(
                "$partial$ip",
                "$partial$ip <i><small>($byIp->{$ip})</small></i>",
                (
                    $partial !~ /^\d+\.\d+\.\d+/
                    ? "ipclasses=1&p=$partial$ip"
                    : "uidByIp=$partial$ip"
                )
            );
393
        }
394
        $self->end() unless ($partial);
395
396
    }

397
398
399
400
401
402
403
    # Default display
    else {
        my ( $byUid, $count );
        $globalStorage->get_key_from_all_sessions(
            $globalStorageOptions,
            sub {
                my $entry = shift;
Yadd's avatar
Yadd committed
404
                next if ( $entry->{_httpSessionType} );
405
                $entry->{$whatToTrace} =~ /^(\w)/ or return undef;
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
                $byUid->{$1}++;
                $count++;
                undef;
            }
        );
        $self->start("Active sessions ($count)");
        $self->window("Sessions <i><small>($count)</small></i>");
        foreach my $letter ( sort keys %$byUid ) {
            $self->ajaxNode( "li_$letter",
                "$letter <i><small>($byUid->{$letter} sessions)</small></i>",
                "letter=$letter" );
        }
        $self->end();
    }
}

Yadd's avatar
Yadd committed
422
## @fn protected string htmlquote(string s)
423
424
425
# Change <, > and & to HTML encoded values in the string
# @param $s HTML string
# @return HTML string
426
427
428
429
430
431
432
433
sub htmlquote {
    my $s = shift;
    $s =~ s/</&lt;/g;
    $s =~ s/>/&gt;/g;
    $s =~ s/&/&amp;/g;
    return $s;
}

Yadd's avatar
Yadd committed
434
## @method protected void start()
435
# Display HTTP and HTML headers.
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
490
491
492
sub start {
    my $self = shift;
    print $self->header( -type => 'text/html; charset=utf8', );
    print $self->start_html(
        -title => shift || 'Sessions Lemonldap::NG',
        -encoding => 'utf8',
        -script   => [
            {
                -language => 'JavaScript1.2',
                -src      => $self->{jqueryUri} || 'jquery.js',
            },
            {
                -language => 'JavaScript1.2',
                -src      => "$ENV{SCRIPT_NAME}/js",
            },
            {
                -language => 'JavaScript1.2',
                -code     => '$(document).ready(function(){
            var simpleTreeCollection
            simpleTreeCollection = $(".simpleTree").simpleTree({
                autoclose: true,
                drag: false,
                afterClick:function(node){
                //alert("text-"+$("span:first",node).text());
                },
                afterDblClick:function(node){
                //alert("text-"+$("span:first",node).text());
                },
                afterMove:function(destination, source, pos){
                //alert("destination-"+$("span:first",destination).text()+" source-"+$("span:first",source).text()+" pos-"+pos);
                },
                afterAjax:function() {
                //alert("Loaded");
                },
                animate:true
                //,docToFolderConvert:true
                });
            });
            function del(session) {
                $("#content").load("' . $ENV{SCRIPT_NAME} . '?delete="+session);
            }
            function display(session) {
                $("#content").load("'
                  . $ENV{SCRIPT_NAME} . '?session="+session);
            }
            ',
            },
        ],
        -style => {
            -src => [
                "$ENV{SCRIPT_NAME}/css",
                ( $self->{personnalCss} ? $self->{personnalCss} : () )
            ],
        },
    );
}

Yadd's avatar
Yadd committed
493
## @method protected void ajaxnode(string id, string text, string param)
494
495
496
497
# Display tree node with Ajax functions inside for opening the node.
# @param $id HTML id of the element.
# @param $text text to display
# @param $param Parameters for the Ajax query
498
499
500
501
502
503
sub ajaxNode {
    my ( $self, $id, $text, $param ) = @_;
    print
"<li id=\"$id\"><span>$text</span>\n<ul class=\"ajax\"><li id=\"sub_$id\">{url:$ENV{SCRIPT_NAME}?$param}</li></ul></li>\n";
}

Yadd's avatar
Yadd committed
504
## @method protected void window(string root)
505
506
# Design the main window
# @param $root Text to display in the root node of the tree
507
508
509
510
511
sub window {
    my $self = shift;
    my $root = shift;
    print '<table border="0" width="100%"><tr style="text-align:center;">
      <td><a href="' . $ENV{SCRIPT_NAME} . '">Sessions actives</a></td>
512
513
      <td><a href="'
      . $ENV{SCRIPT_NAME} . '?ipclasses=1">R&eacute;seaux</a></td>
514
515
516
517
518
519
520
521
522
523
524
525
526
527
      <td><a href="'
      . $ENV{SCRIPT_NAME} . '?doubleIp=1">Utilisateurs multi-IP</a></td>
      <td><form action="'
      . $ENV{SCRIPT_NAME}
      . '" method="get">Recherche par UID <input name="fulluid" /><input type="submit" value="OK" /></form></td>
      <td><form action="'
      . $ENV{SCRIPT_NAME}
      . '" method="get">Recherche par IP <input name="fullip" /><input type="submit" value="OK" /></form></td>
    </tr></table>
    <table border="0" width="100%"><tr><td width="300px" valign="top"><div style="overflow:auto;height:600px;">
    <ul class="simpleTree"><li class="root" id="root"><span>' . $root
      . '</span><ul>';
}

Yadd's avatar
Yadd committed
528
## @method protected void end()
529
# Display the end of HTML page.
530
531
532
533
534
535
536
537
538
sub end {
    my $self = shift;
    print
'</ul></li></ul></div></td><td valign="top"><div id="content" style="overflow:auto;height:600px;"></div></td></tr></table>';
    print $self->end_html();
}

1;

Yadd's avatar
Yadd committed
539
## @method protected css()
540
# Display the main CSS file (called by http://manager.example.com/sessions.pl/css)
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
574
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
sub css {
    my $self = shift;
    print <<"EOF";
body
{
	font: normal 12px arial, tahoma, helvetica, sans-serif;
	margin:0;
	padding:20px;
}
.simpleTree
{
	overflow:auto;
	margin:0;
	padding:0;
	/*
 * width: 250px;
 * height:350px;
 * overflow:auto;
 * border: 1px solid #444444;
 * */
}
.simpleTree li
{
    list-style: none;
    margin:0;
    padding:0 0 0 34px;
    line-height: 14px;
}
.simpleTree li span
{
    display:inline;
    clear: left;
    white-space: nowrap;
}
.simpleTree ul
{
    margin:0; 
    padding:0;
}
.simpleTree .root
{
    margin-left:-16px;
    background: url($self->{imagePath}root.gif) no-repeat 16px 0 #ffffff;
}
.simpleTree .line
{
    margin:0 0 0 -16px;
    padding:0;
    line-height: 3px;
    height:3px;
    font-size:3px;
    background: url($self->{imagePath}line_bg.gif) 0 0 no-repeat transparent;
}
.simpleTree .line-last
{
    margin:0 0 0 -16px;
    padding:0;
    line-height: 3px;
    height:3px;
    font-size:3px;
    background: url($self->{imagePath}spacer.gif) 0 0 no-repeat transparent;
}
.simpleTree .line-over
{
    margin:0 0 0 -16px;
    padding:0;
    line-height: 3px;
    height:3px;
    font-size:3px;
    background: url($self->{imagePath}line_bg_over.gif) 0 0 no-repeat transparent;
}
.simpleTree .line-over-last
{
    margin:0 0 0 -16px;
    padding:0;
    line-height: 3px;
    height:3px;
    font-size:3px;
    background: url($self->{imagePath}line_bg_over_last.gif) 0 0 no-repeat transparent;
}
.simpleTree .folder-open
{
    margin-left:-16px;
    background: url($self->{imagePath}collapsable.gif) 0 -2px no-repeat #fff;
}
.simpleTree .folder-open-last
{
    margin-left:-16px;
    background: url($self->{imagePath}collapsable-last.gif) 0 -2px no-repeat #fff;
}
.simpleTree .folder-close
{
    margin-left:-16px;
    background: url($self->{imagePath}expandable.gif) 0 -2px no-repeat #fff;
}
.simpleTree .folder-close-last
{
    margin-left:-16px;
    background: url($self->{imagePath}expandable-last.gif) 0 -2px no-repeat #fff;
}
.simpleTree .doc
{
    margin-left:-16px;
    background: url($self->{imagePath}leaf.gif) 0 -1px no-repeat #fff;
}
.simpleTree .doc-last
{
    margin-left:-16px;
    background: url($self->{imagePath}leaf-last.gif) 0 -1px no-repeat #fff;
}
.simpleTree .ajax
{
    background: url($self->{imagePath}spinner.gif) no-repeat 0 0 #ffffff;
    height: 16px;
    display:none;
}
.simpleTree .ajax li
{
    display:none;
    margin:0; 
    padding:0;
}
.simpleTree .trigger
{
    display:inline;
    margin-left:-32px;
    width: 28px;
    height: 11px;
    cursor:pointer;
}
.simpleTree .text
{
    cursor: default;
}
.simpleTree .active
{
    cursor: default;
    background-color:#F7BE77;
    padding:0px 2px;
    border: 1px dashed #444;
}
#drag_container
{
    background:#ffffff;
    color:#000;
    font: normal 11px arial, tahoma, helvetica, sans-serif;
    border: 1px dashed #767676;
}
#drag_container ul
{
    list-style: none;
    padding:0;
    margin:0;
}

#drag_container li
{
    list-style: none;
    background-color:#ffffff;
    line-height:18px;
    white-space: nowrap;
    padding:1px 1px 0px 16px;
    margin:0;
}
#drag_container li span
{
    padding:0;
}

#drag_container li.doc, #drag_container li.doc-last
{
    background: url($self->{imagePath}leaf.gif) no-repeat -17px 0 #ffffff;
}
#drag_container .folder-close, #drag_container .folder-close-last
{
    background: url($self->{imagePath}expandable.gif) no-repeat -17px 0 #ffffff;
}

#drag_container .folder-open, #drag_container .folder-open-last
{
    background: url($self->{imagePath}collapsable.gif) no-repeat -17px 0 #ffffff;
}
EOF
}

Yadd's avatar
Yadd committed
726
## @method protected js()
727
# Display the main javascript file (called by http://manager.example.com/sessions.pl/js)
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
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
787
788
789
790
791
792
793
794
795
796
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
sub js {
    my $self = shift;
    print <<"EOF";
/*
* jQuery SimpleTree Drag&Drop plugin
* Update on 22th May 2008
* Version 0.3
*
* Licensed under BSD <http://en.wikipedia.org/wiki/BSD_License>
* Copyright (c) 2008, Peter Panov <panov\@elcat.kg>, IKEEN Group http://www.ikeen.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of the Peter Panov, IKEEN Group nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Peter Panov, IKEEN Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Peter Panov, IKEEN Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


\$.fn.simpleTree = function(opt){
	return this.each(function(){
		var TREE = this;
		var ROOT = \$('.root',this);
		var mousePressed = false;
		var mouseMoved = false;
		var dragMoveType = false;
		var dragNode_destination = false;
		var dragNode_source = false;
		var dragDropTimer = false;
		var ajaxCache = Array();

		TREE.option = {
			drag:		true,
			animate:	false,
			autoclose:	false,
			speed:		'fast',
			afterAjax:	false,
			afterMove:	false,
			afterClick:	false,
			afterDblClick:	false,
			// added by Erik Dohmen (2BinBusiness.nl) to make context menu cliks available
			afterContextMenu:	false,
			docToFolderConvert:false
		};
		TREE.option = \$.extend(TREE.option,opt);
		\$.extend(this, {getSelected: function(){
			return \$('span.active', this).parent();
		}});
		TREE.closeNearby = function(obj)
		{
			\$(obj).siblings().filter('.folder-open, .folder-open-last').each(function(){
				var childUl = \$('>ul',this);
				var className = this.className;
				this.className = className.replace('open','close');
				if(TREE.option.animate)
				{
					childUl.animate({height:"toggle"},TREE.option.speed);
				}else{
					childUl.hide();
				}
			});
		};
		TREE.nodeToggle = function(obj)
		{
			var childUl = \$('>ul',obj);
			if(childUl.is(':visible')){
				obj.className = obj.className.replace('open','close');

				if(TREE.option.animate)
				{
					childUl.animate({height:"toggle"},TREE.option.speed);
				}else{
					childUl.hide();
				}
			}else{
				obj.className = obj.className.replace('close','open');
				if(TREE.option.animate)
				{
					childUl.animate({height:"toggle"},TREE.option.speed, function(){
						if(TREE.option.autoclose)TREE.closeNearby(obj);
						if(childUl.is('.ajax'))TREE.setAjaxNodes(childUl, obj.id);
					});
				}else{
					childUl.show();
					if(TREE.option.autoclose)TREE.closeNearby(obj);
					if(childUl.is('.ajax'))TREE.setAjaxNodes(childUl, obj.id);
				}
			}
		};
		TREE.setAjaxNodes = function(node, parentId, callback)
		{
			if(\$.inArray(parentId,ajaxCache) == -1){
				ajaxCache[ajaxCache.length]=parentId;
				var url = \$.trim(\$('>li', node).text());
				if(url && url.indexOf('url:'))
				{
					url=\$.trim(url.replace(/.*\\{url:(.*)\\}/i ,'\$1'));
					\$.ajax({
						type: "GET",
						url: url,
						contentType:'html',
						cache:false,
						success: function(responce){
							node.removeAttr('class');
							node.html(responce);
							\$.extend(node,{url:url});
							TREE.setTreeNodes(node, true);
							if(typeof TREE.option.afterAjax == 'function')
							{
								TREE.option.afterAjax(node);
							}
							if(typeof callback == 'function')
							{
								callback(node);
							}
						}
					});
				}
				
			}
		};
		TREE.setTreeNodes = function(obj, useParent){
			obj = useParent? obj.parent():obj;
			\$('li>span', obj).addClass('text')
			.bind('selectstart', function() {
				return false;
			}).click(function(){
				\$('.active',TREE).attr('class','text');
				if(this.className=='text')
				{
					this.className='active';
				}
				if(typeof TREE.option.afterClick == 'function')
				{
					TREE.option.afterClick(\$(this).parent());
				}
				return false;
			}).dblclick(function(){
				mousePressed = false;
				TREE.nodeToggle(\$(this).parent().get(0));
				if(typeof TREE.option.afterDblClick == 'function')
				{
					TREE.option.afterDblClick(\$(this).parent());
				}
				return false;
				// added by Erik Dohmen (2BinBusiness.nl) to make context menu actions
				// available
			}).bind("contextmenu",function(){
				\$('.active',TREE).attr('class','text');
				if(this.className=='text')
				{
					this.className='active';
				}
				if(typeof TREE.option.afterContextMenu == 'function')
				{
					TREE.option.afterContextMenu(\$(this).parent());
				}
				return false;
			}).mousedown(function(event){
				mousePressed = true;
				cloneNode = \$(this).parent().clone();
				var LI = \$(this).parent();
				if(TREE.option.drag)
				{
					\$('>ul', cloneNode).hide();
					\$('body').append('<div id="drag_container"><ul></ul></div>');
					\$('#drag_container').hide().css({opacity:'0.8'});
					\$('#drag_container >ul').append(cloneNode);
					\$("<img>").attr({id	: "tree_plus",src	: "$self->{imagePath}plus.gif"}).css({width: "7px",display: "block",position: "absolute",left	: "5px",top: "5px", display:'none'}).appendTo("body");
					\$(document).bind("mousemove", {LI:LI}, TREE.dragStart).bind("mouseup",TREE.dragEnd);
				}
				return false;
			}).mouseup(function(){
				if(mousePressed && mouseMoved && dragNode_source)
				{
					TREE.moveNodeToFolder(\$(this).parent());
				}
				TREE.eventDestroy();
			});
			\$('li', obj).each(function(i){
				var className = this.className;
				var open = false;
				var cloneNode=false;
				var LI = this;
				var childNode = \$('>ul',this);
				if(childNode.size()>0){
					var setClassName = 'folder-';
					if(className && className.indexOf('open')>=0){
						setClassName=setClassName+'open';
						open=true;
					}else{
						setClassName=setClassName+'close';
					}
					this.className = setClassName + (\$(this).is(':last-child')? '-last':'');

					if(!open || className.indexOf('ajax')>=0)childNode.hide();

					TREE.setTrigger(this);
				}else{
					var setClassName = 'doc';
					this.className = setClassName + (\$(this).is(':last-child')? '-last':'');
				}
			}).before('<li class="line">&nbsp;</li>')
			.filter(':last-child').after('<li class="line-last"></li>');
			TREE.setEventLine(\$('.line, .line-last', obj));
		};
		TREE.setTrigger = function(node){
			\$('>span',node).before('<img class="trigger" src="$self->{imagePath}spacer.gif" border=0>');
			var trigger = \$('>.trigger', node);
			trigger.click(function(event){
				TREE.nodeToggle(node);
			});
			if(!\$.browser.msie)
			{
				trigger.css('float','left');
			}
		};
		TREE.dragStart = function(event){
			var LI = \$(event.data.LI);
			if(mousePressed)
			{
				mouseMoved = true;
				if(dragDropTimer) clearTimeout(dragDropTimer);
				if(\$('#drag_container:not(:visible)')){
					\$('#drag_container').show();
					LI.prev('.line').hide();
					dragNode_source = LI;
				}
				\$('#drag_container').css({position:'absolute', "left" : (event.pageX + 5), "top": (event.pageY + 15) });
				if(LI.is(':visible'))LI.hide();
				var temp_move = false;
				if(event.target.tagName.toLowerCase()=='span' && \$.inArray(event.target.className, Array('text','active','trigger'))!= -1)
				{
					var parent = event.target.parentNode;
					var offs = \$(parent).offset({scroll:false});
					var screenScroll = {x : (offs.left - 3),y : event.pageY - offs.top};
					var isrc = \$("#tree_plus").attr('src');
					var ajaxChildSize = \$('>ul.ajax',parent).size();
					var ajaxChild = \$('>ul.ajax',parent);
					screenScroll.x += 19;
					screenScroll.y = event.pageY - screenScroll.y + 5;

					if(parent.className.indexOf('folder-close')>=0 && ajaxChildSize==0)
					{
						if(isrc.indexOf('minus')!=-1)\$("#tree_plus").attr('src','$self->{imagePath}plus.gif');
						\$("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
						dragDropTimer = setTimeout(function(){
							parent.className = parent.className.replace('close','open');
							\$('>ul',parent).show();
						}, 700);
					}else if(parent.className.indexOf('folder')>=0 && ajaxChildSize==0){
						if(isrc.indexOf('minus')!=-1)\$("#tree_plus").attr('src','$self->{imagePath}plus.gif');
						\$("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
					}else if(parent.className.indexOf('folder-close')>=0 && ajaxChildSize>0)
					{
						mouseMoved = false;