23fe8f470131476e7d9306eab953452b4f74ddf5
[freeside.git] / httemplate / search / elements / search.html
1 <%doc>
2
3 Example:
4
5   include( 'elements/search.html',
6
7     ###
8     # required
9     ###
10
11     'title'         => 'Page title',
12     
13     'name_singular' => 'item',  #singular name for the records returned
14        #OR#                     # (preferred, will be pluralized automatically)
15     'name'          => 'items', #plural name for the records returned
16                                 # (deprecated, will be singularlized
17                                 #  simplisticly)
18
19     #literal SQL query string (deprecated?) or qsearch hashref
20     'query'       => {
21                        'table'     => 'tablename',
22                        #everything else is optional...
23                        'hashref'   => { 'field' => 'value',
24                                         'field' => { 'op'    => '<',
25                                                      'value' => '54',
26                                                    },
27                                       },
28                        'select'    => '*',
29                        'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
30                        'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
31                        'order_by'  => 'ORDER BY something',
32    
33                      },
34                      # "select * from tablename";
35    
36     #required unless 'query' is an SQL query string (shouldn't be...)
37     'count_query' => 'SELECT COUNT(*) FROM tablename',
38
39     ###
40     # recommended / common
41     ###
42
43     #listref of column labels, <TH>
44     #recommended unless 'query' is an SQL query string
45     # (if not specified the database column names will be used)
46     'header'      => [ '#',
47                        'Item',
48                        { 'label' => 'Another Item',
49                          
50                        },
51                      ],
52
53     #listref - each item is a literal column name (or method) or coderef
54     #if not specified all columns will be shown
55     'fields'      => [
56                        'column',
57                        sub { my $row = shift; $row->column; },
58                      ],
59
60     #redirect if there's only one item...
61     # listref of URL base and column name (or method)
62     # or a coderef that returns the same
63     'redirect' =>
64    
65     ###
66     # optional
67     ###
68    
69     # some HTML callbacks...
70     'menubar'          => '', #menubar arrayref
71     'html_init'        => '', #after the header/menubar and before the pager
72     'html_form'        => '', #after the pager, right before the results
73                               # (only shown if there are results)
74                               # (use this for any form-opening tag rather than
75                               #  html_init, to avoid a nested form)
76     'html_foot'        => '', #at the bottom
77     'html_posttotal'   => '', #at the bottom
78                               # (these three can be strings or coderefs)
79     
80     'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
81                         # [ $money_char.'%.2f total paid', ],
82    
83     #second (smaller) header line, currently only for HTML
84     'header2      => [ '#',
85                        'Item',
86                        { 'label' => 'Another Item',
87                          
88                        },
89                      ],
90
91     #listref of column footers
92     'footer'      => [],
93     
94     #disabling things
95     'disable_download'  => '', # set true to hide the CSV/Excel download links
96     'disable_total'     => '', # set true to hide the total"
97     'disable_maxselect' => '', # set true to disable record/page selection
98     'disable_nonefound' => '', # set true to disable the "No matching Xs found"
99                                # message
100    
101     #handling "disabled" fields in the records
102     'disableable' => 1,  # set set to 1 (or column position for "disabled"
103                          # status col) to enable if this table has a "disabled"
104                          # field, to hide disabled records & have
105                          # "show disabled/hide disabled" links
106                          #(can't be used with a literal query)
107     'disabled_statuspos' => 3, #optional position (starting from 0) to insert
108                                #a Status column when showing disabled records
109                                #(query needs to be a qsearch hashref and
110                                # header & fields need to be defined)
111
112     #handling agent virtualization
113     'agent_virt'            => 1, # set true if this search should be
114                                   # agent-virtualized
115     'agent_null_right'      => 'Access Right', # optional right to view global
116                                                # records
117     'agent_null_right_link' => 'Access Right'  # optional right to link to
118                                                # global records; defaults to
119                                                # same as agent_null_right
120     'agent_pos'             => 3, # optional position (starting from 0) to
121                                   # insert an Agent column (query needs to be a
122                                   # qsearch hashref and header & fields need to
123                                   # be defined)
124
125     # link & display properties for fields
126    
127     #listref - each item is the empty string,
128     #          or a listref of link and method name to append,
129     #          or a listref of link and coderef to run and append
130     #          or a coderef that returns such a listref
131     'links'       => [],`
132
133     #listref - each item is the empty string,
134     #          or a string onClick handler for the corresponding link
135     #          or a coderef that returns string onClick handler
136     'link_onclicks' => [],
137
138     #one letter for each column, left/right/center/none
139     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
140     'align'       => 'lrc.',
141    
142     #listrefs of ( scalars or coderefs )
143     #currently only HTML, maybe eventually Excel too
144     'color'       => [],
145     'size'        => [],
146     'style'       => [], #<B> or <I>, etc.
147     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
148     
149   );
150
151 </%doc>
152 % if ( $type eq 'csv' ) {
153 %
154 %   #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
155 %   http_header('Content-Type' => 'text/plain' );
156 %
157 %   my $csv = new Text::CSV_XS { 'always_quote' => 1,
158 %                                'eol'          => "\n", #"\015\012", #"\012"
159 %                              };
160 %
161 %   $csv->combine(@$header); #or die $csv->status;
162 %    
163 <% $csv->string %>
164 %
165 %
166 %   foreach my $row ( @$rows ) {
167 %
168 %     if ( $opt{'fields'} ) {
169 %
170 %       my @line = ();
171 %
172 %       foreach my $field ( @{$opt{'fields'}} ) {
173 %         if ( ref($field) eq 'CODE' ) {
174 %           push @line, map {
175 %                             ref($_) eq 'ARRAY'
176 %                               ? '(N/A)' #unimplemented
177 %                               : $_;
178 %                           }
179 %                           &{$field}($row);
180 %         } else {
181 %           push @line, $row->$field();
182 %         }
183 %       }
184 %
185 %       $csv->combine(@line); #or die $csv->status;
186 %
187 %     } else {
188 %       $csv->combine(@$row); #or die $csv->status;
189 %     }
190 %
191 %      
192 <% $csv->string %>
193 %
194 %
195 %   }
196 %
197 % #} elsif ( $type eq 'excel' ) {
198 % } elsif ( $type =~ /\.xls$/ ) {
199 %
200 %   #http_header('Content-Type' => 'application/excel' ); #eww
201 %   #http_header('Content-Type' => 'application/msexcel' ); #alas
202 %   #http_header('Content-Type' => 'application/x-msexcel' ); #?
203 %
204 %   #http://support.microsoft.com/kb/199841
205 %   http_header('Content-Type' => 'application/vnd.ms-excel' );
206 %
207 %   #http://support.microsoft.com/kb/812935
208 %   #http://support.microsoft.com/kb/323308
209 %   $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
210 %
211 %   my $data = '';
212 %   my $XLS = new IO::Scalar \$data;
213 %   my $workbook = Spreadsheet::WriteExcel->new($XLS)
214 %     or die "Error opening .xls file: $!";
215 %
216 %   my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
217 %
218 %   my($r,$c) = (0,0);
219 %
220 %   $worksheet->write($r, $c++, $_) foreach @$header;
221 %
222 %   foreach my $row ( @$rows ) {
223 %     $r++;
224 %     $c = 0;
225 %
226 %     if ( $opt{'fields'} ) {
227 %
228 %       #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
229 %       #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
230 %
231 %       foreach my $field ( @{$opt{'fields'}} ) {
232 %         #my $align = $aligns ? shift @$aligns : '';
233 %         #$align = " ALIGN=$align" if $align;
234 %         #my $a = '';
235 %         #if ( $links ) {
236 %         #  my $link = shift @$links;
237 %         #  $link = &{$link}($row) if ref($link) eq 'CODE';
238 %         #  if ( $link ) {
239 %         #    my( $url, $method ) = @{$link};
240 %         #    if ( ref($method) eq 'CODE' ) {
241 %         #      $a = $url. &{$method}($row);
242 %         #    } else {
243 %         #      $a = $url. $row->$method();
244 %         #    }
245 %         #    $a = qq(<A HREF="$a">);
246 %         #  }
247 %         #}
248 %         if ( ref($field) eq 'CODE' ) {
249 %           foreach my $value ( &{$field}($row) ) {
250 %             if ( ref($value) eq 'ARRAY' ) { 
251 %               $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
252 %             } else {
253 %               $worksheet->write($r, $c++, $value );
254 %             }
255 %           }
256 %         } else {
257 %           $worksheet->write($r, $c++, $row->$field() );
258 %         }
259 %       }
260 %
261 %     } else {
262 %       $worksheet->write($r, $c++, $_) foreach @$row;
263 %     }
264 %
265 %   }
266 %
267 %   $workbook->close();# or die "Error creating .xls file: $!";
268 %
269 %   http_header('Content-Length' => length($data) );
270 %    
271 <% $data %>
272 %
273 %
274 % } else { # regular HTML
275 %
276 %   if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
277 %        && $type ne 'html-print'
278 %      ) {
279 %     my $redirect = $opt{'redirect'};
280 %     $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
281 %     my( $url, $method ) = @$redirect;
282 %     redirect( $url. $rows->[0]->$method() );
283 %   } else {
284 %     if ( $opt{'name_singular'} ) {
285 %       $opt{'name'} = PL($opt{'name_singular'});
286 %     }
287 %     ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
288 %     if ( $total == 1 ) {
289 %       if ( $opt{'name_singular'} ) {
290 %         $opt{'name'} = $opt{'name_singular'}
291 %       } else {
292 %         #$opt{'name'} =~ s/s$// if $total == 1;
293 %         $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
294 %       }
295 %     }
296 %
297 %     if ( $type eq 'html-print' ) {
298
299         <% include( '/elements/header-popup.html', $opt{'title'} ) %>
300
301 %     } elsif ( $type eq 'select' ) {
302
303         <% include( '/elements/header-popup.html', $opt{'title'} ) %>
304         <% defined($opt{'html_init'}) 
305               ? ( ref($opt{'html_init'})
306                     ? &{$opt{'html_init'}}()
307                     : $opt{'html_init'}
308                 )
309               : ''
310         %>
311
312 %     } else {
313 %
314 %       my @menubar = ();
315 %       if ( $opt{'menubar'} ) {
316 %         @menubar = @{ $opt{'menubar'} };
317 %       #} else {
318 %       #  @menubar = ( 'Main menu' => $p );
319 %       }
320
321         <% include( '/elements/header.html', $opt{'title'},
322                       include( '/elements/menubar.html', @menubar )
323                   )
324         %>
325
326         <% defined($opt{'html_init'}) 
327               ? ( ref($opt{'html_init'})
328                     ? &{$opt{'html_init'}}()
329                     : $opt{'html_init'}
330                 )
331               : ''
332         %>
333
334 %     }
335
336 %     unless ( $total ) { 
337 %       unless ( $opt{'disable_nonefound'} ) { 
338           No matching <% $opt{'name'} %> found.<BR>
339 %       } 
340 %     }
341 %
342 %     if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
343
344         <TABLE>
345           <TR>
346
347             <TD VALIGN="bottom">
348
349               <FORM>
350
351 %               if (! $opt{'disable_total'}) {
352                   <% $total %> total <% $opt{'name'} %>
353 %               }
354
355 %               if ( $confmax && $total > $confmax
356 %                    && ! $opt{'disable_maxselect'}
357 %                    && $type ne 'html-print' )
358 %               {
359 %                 $cgi->delete('maxrecords');
360 %                 $cgi->param('_dummy', 1);
361
362                   ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
363
364 %                   foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
365                   <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
366 %                   }
367
368                   </SELECT> per page )
369
370 %                 $cgi->param('maxrecords', $maxrecords);
371 %               }
372
373 %               if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
374                     <% ref($opt{'html_posttotal'})
375                          ? &{$opt{'html_posttotal'}}()
376                          : $opt{'html_posttotal'}
377                     %>
378 %               }
379                 <BR>
380
381 %               if ( $opt{'count_addl'} ) { 
382 %                 my $n=0;
383 %                 foreach my $count ( @{$opt{'count_addl'}} ) { 
384 %                   my $data = $count_arrayref->[++$n];
385 %                   if ( ref($count) ) {
386                       <% &{ $count }( $data ) %>
387 %                   } else {
388                       <% sprintf( $count, $data ) %><BR>
389 %                   }
390 %                 } 
391 %               } 
392               </FORM>
393
394             </TD>
395
396 %           unless ( $opt{'disable_download'} || $type eq 'html-print' ) { 
397
398               <TD ALIGN="right">
399
400                 Download full results<BR>
401
402 %               $cgi->param('_type', "$xlsname.xls" ); 
403                 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
404
405 %               $cgi->param('_type', 'csv'); 
406                 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
407
408 %               $cgi->param('_type', 'html-print'); 
409                 as <A HREF="<% $cgi->self_url %>">printable copy</A>
410
411               <% $opt{'extra_choices_callback'}
412                  ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
413                  : ''
414               %>
415
416               </TD>
417 %             $cgi->param('_type', "html" ); 
418 %           } 
419
420           </TR>
421           <TR>
422             <TD COLSPAN=2>
423
424 %             my $pager = '';
425 %             unless ( $type eq 'html_print' ) {
426
427                 <% $pager = include( '/elements/pager.html',
428                                        'offset'     => $offset,
429                                        'num_rows'   => scalar(@$rows),
430                                        'total'      => $total,
431                                        'maxrecords' => $maxrecords,
432                                    )
433                 %>
434
435                 <% defined($opt{'html_form'}) 
436                      ? ( ref($opt{'html_form'})
437                            ? &{$opt{'html_form'}}()
438                            : $opt{'html_form'}
439                        )
440                      : ''
441                 %>
442
443 %             }
444
445               <% include('/elements/table-grid.html') %>
446
447                 <TR>
448 %                 my $h2 = 0;
449 %                 foreach my $header ( @{ $opt{header} } ) { 
450 %                   my $label = ref($header) ? $header->{label} : $header;
451 %                   my $rowspan = 1;
452 %                   my $style = '';
453 %                   if ( $opt{header2} ) {
454 %                     if ( !length($opt{header2}->[$h2]) ) {
455 %                       $rowspan = 2;
456 %                       splice @{ $opt{header2} }, $h2, 1;
457 %                     } else {
458 %                       $h2++;
459 %                       $style = 'STYLE="border-bottom: none"'
460 %                     }
461 %                   }
462                     <TH CLASS   = "grid"
463                         BGCOLOR = "#cccccc"
464                         ROWSPAN = "<% $rowspan %>"
465                         <% $style %>
466
467                     >
468                       <% $label %>
469                     </TH>
470 %                 } 
471                 </TR>
472
473 %               if ( $opt{header2} ) {
474                   <TR>
475 %                   foreach my $header ( @{ $opt{header2} } ) { 
476 %                     my $label = ref($header) ? $header->{label} : $header;
477                       <TH CLASS="grid" BGCOLOR="#cccccc">
478                         <FONT SIZE="-1"><% $label %></FONT>
479                       </TH>
480 %                   } 
481                   </TR>
482 %               }
483
484 %               my $bgcolor1 = '#eeeeee';
485 %               my $bgcolor2 = '#ffffff';
486 %               my $bgcolor;
487 %
488 %               foreach my $row ( @$rows ) {
489 %
490 %                 if ( $bgcolor eq $bgcolor1 ) {
491 %                   $bgcolor = $bgcolor2;
492 %                 } else {
493 %                   $bgcolor = $bgcolor1;
494 %                 }
495
496                   <TR>
497
498 %                   if ( $opt{'fields'} ) {
499 %
500 %                     my $links    = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
501 %                     my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
502 %                     my $aligns   = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
503 %                     my $colors   = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
504 %                     my $sizes    = $opt{'size'}  ? [ @{$opt{'size'}}  ] : [];
505 %                     my $styles   = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
506 %                     my $cstyles  = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
507 %
508 %                     foreach my $field (
509 %
510 %                       map {
511 %                             if ( ref($_) eq 'ARRAY' ) {
512 %
513 %                               my $tableref = $_;
514 %
515 %                               '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
516 %
517 %                               join('', map {
518 %
519 %                                 my $rowref = $_;
520 %
521 %                                 '<tr>'.
522 %
523 %                                 join('', map {
524 %
525 %                                   my $e = $_;
526 %
527 %                                   '<TD '.
528 %                                     join(' ', map {
529 %                                       uc($_).'="'. $e->{$_}. '"';
530 %                                     }
531 %                                     grep exists($e->{$_}),
532 %                                          qw( align bgcolor colspan rowspan
533 %                                              style valign width )
534 %                                     ).
535 %                                   '>'.
536 %
537 %                                   ( $e->{'link'}
538 %                                       ? '<A HREF="'. $e->{'link'}. '">'
539 %                                       : ''
540 %                                   ).
541 %                                   ( $e->{'size'}
542 %                                      ? '<FONT SIZE="'.uc($e->{'size'}).'">'
543 %                                      : ''
544 %                                   ).
545 %                                   ( $e->{'data_style'}
546 %                                       ? '<'. uc($e->{'data_style'}). '>'
547 %                                       : ''
548 %                                   ).
549 %                                   $e->{'data'}.
550 %                                   ( $e->{'data_style'}
551 %                                       ? '</'. uc($e->{'data_style'}). '>'
552 %                                       : ''
553 %                                   ).
554 %                                   ( $e->{'size'} ? '</FONT>' : '' ).
555 %                                   ( $e->{'link'} ? '</A>'    : '' ).
556 %                                   '</td>';
557 %
558 %                                 } @$rowref ).
559 %
560 %                                 '</tr>';
561 %                               } @$tableref ).
562 %
563 %                               '</table>';
564 %
565 %                             } else {
566 %                               $_;
567 %                             }
568 %                           }
569 %
570 %                       map {
571 %                             if ( ref($_) eq 'CODE' ) {
572 %                               &{$_}($row);
573 %                             } else {
574 %                               $row->$_();
575 %                             }
576 %                           }
577 %                       @{$opt{'fields'}}
578 %
579 %                     ) {
580 %
581 %                       my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
582 %
583 %                       my $align = $aligns ? shift @$aligns : '';
584 %                       $align = " ALIGN=$align" if $align;
585 %
586 %                       my $a = '';
587 %                       if ( $links ) {
588 %                         my $link = shift @$links;
589 %                         my $onclick = shift @$onclicks;
590 %
591 %                         if (    ! $opt{'agent_virt'}
592 %                              || ( $null_link && ! $row->agentnum )
593 %                              || grep { $row->agentnum == $_ }
594 %                                      @link_agentnums
595 %                            ) {
596 %        
597 %                           $link = &{$link}($row)
598 %                             if ref($link) eq 'CODE';
599 %
600 %                           $onclick = &{$onclick}($row)
601 %                             if ref($onclick) eq 'CODE';
602 %                           $onclick = qq( onClick="$onclick") if $onclick;
603 %
604 %                           if ( $link ) {
605 %                             my( $url, $method ) = @{$link};
606 %                             if ( ref($method) eq 'CODE' ) {
607 %                               $a = $url. &{$method}($row);
608 %                             } else {
609 %                               $a = $url. $row->$method();
610 %                             }
611 %                             $a = qq(<A HREF="$a"$onclick>);
612 %                           }
613 %
614 %                         }
615 %
616 %                       }
617 %
618 %                       my $font = '';
619 %                       my $color = shift @$colors;
620 %                       $color = &{$color}($row) if ref($color) eq 'CODE';
621 %                       my $size = shift @$sizes;
622 %                       $size = &{$size}($row) if ref($size) eq 'CODE';
623 %                       if ( $color || $size ) {
624 %                         $font = '<FONT '.
625 %                                 ( $color ? "COLOR=#$color "   : '' ).
626 %                                 ( $size  ? qq(SIZE="$size" )  : '' ).
627 %                                 '>';
628 %                       }
629 %
630 %                       my($s, $es) = ( '', '' );
631 %                       my $style = shift @$styles;
632 %                       $style = &{$style}($row) if ref($style) eq 'CODE';
633 %                       if ( $style ) {
634 %                         $s = join( '', map "<$_>", split('', $style) );
635 %                         $es = join( '', map "</$_>", split('', $style) );
636 %                       }
637 %
638 %                       my $cstyle = shift @$cstyles;
639 %                       $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
640 %                       $cstyle = qq(STYLE="$cstyle")
641 %                         if $cstyle;
642
643                         <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
644
645 %                     } 
646 %
647 %                   } else { 
648 %
649 %                     foreach ( @$row ) { 
650                         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
651 %                     }
652 %
653 %                   }
654
655                   </TR>
656
657 %               } 
658
659 %               if ( $opt{'footer'} ) { 
660
661                   <TR>
662
663 %                   foreach my $footer ( @{ $opt{'footer'} } ) { 
664                       <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
665 %                   } 
666
667                   </TR>
668 %               } 
669             
670               </TABLE>
671
672               <% $pager %>
673   
674             </TD>
675           </TR>
676         </TABLE>
677 %     }
678
679 %     if ( $type eq 'html-print' ) {
680
681         </BODY></HTML>
682       
683 %     } else {
684
685         <% defined($opt{'html_foot'}) 
686               ? ( ref($opt{'html_foot'})
687                     ? &{$opt{'html_foot'}}()
688                     : $opt{'html_foot'}
689                 )
690               : ''
691         %>
692
693         <% include( '/elements/footer.html' ) %>
694
695 %     }
696
697 %   } 
698 %
699 % } 
700 <%init>
701
702 my(%opt) = @_;
703 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
704
705 my $curuser = $FS::CurrentUser::CurrentUser;
706
707 my %align = (
708   'l' => 'left',
709   'r' => 'right',
710   'c' => 'center',
711   ' ' => '',
712   '.' => '',
713 );
714 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
715   unless !$opt{align} || ref($opt{align});
716
717 $opt{disable_download} = 0
718   if $opt{disable_download} && $curuser->access_right('Configuration download');
719
720 my @link_agentnums = ();
721 my $null_link = '';
722 if ( $opt{'agent_virt'} ) {
723
724   @link_agentnums = $curuser->agentnums;
725   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
726                                        || $opt{'agent_null_right'}      );
727
728   my $agentnums_sql = $curuser->agentnums_sql(
729                         'null_right' => $opt{'agent_null_right'}
730                       );
731
732   $opt{'query'}{'extra_sql'} .=
733     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
734       ? ' AND '
735       : ' WHERE ' ). $agentnums_sql;
736
737   $opt{'count_query'} .=
738     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
739
740   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
741        and scalar($curuser->agentnums) > 1           ) {
742     #false laziness w/statuspos above
743     my $pos = $opt{'agent_pos'};
744
745     foreach my $att (qw( align style color size )) {
746       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
747     }
748
749     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
750     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
751     splice @{ $opt{'style'}  }, $pos, 0, ''; 
752     splice @{ $opt{'size'}   }, $pos, 0, ''; 
753     splice @{ $opt{'fields'} }, $pos, 0,
754       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
755     splice @{ $opt{'color'}  }, $pos, 0, '';
756     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
757       if $opt{'links'};
758     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
759       if $opt{'link_onclicks'};
760
761   }
762
763 }
764
765 if ( $opt{'disableable'} ) {
766
767   unless ( $cgi->param('showdisabled') ) { #modify searches
768
769     $opt{'query'}{'hashref'}{'disabled'} = '';
770     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
771
772     $opt{'count_query'} .=
773       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
774       "( disabled = '' OR disabled IS NULL )";
775
776   } elsif (    $opt{'disabled_statuspos'}
777             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
778
779     my $pos = $opt{'disabled_statuspos'};
780
781     foreach my $att (qw( align style color size )) {
782       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
783     }
784
785     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
786     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
787     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
788     splice @{ $opt{'size'}   }, $pos, 0, ''; 
789     splice @{ $opt{'fields'} }, $pos, 0,
790       sub { shift->disabled ? 'DISABLED' : 'Active'; };
791     splice @{ $opt{'color'}  }, $pos, 0,
792       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
793     splice @{ $opt{'links'}  }, $pos, 0, ''
794       if $opt{'links'};
795     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
796       if $opt{'link_onlicks'};
797   }
798
799   #add show/hide disabled links
800   my $items = $opt{'name'} || PL($opt{'name_singular'});
801   if ( $cgi->param('showdisabled') ) {
802     $cgi->param('showdisabled', 0);
803     $opt{'html_posttotal'} .=
804       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
805     $cgi->param('showdisabled', 1);
806   } else {
807     $cgi->param('showdisabled', 1);
808     $opt{'html_posttotal'} .=
809       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
810     $cgi->param('showdisabled', 0);
811   }
812
813 }
814
815 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
816            ? $1 : 'html';
817
818 my $limit = '';
819 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
820
821 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
822
823   unless (exists($opt{count_query}) && length($opt{count_query})) {
824     ( $opt{count_query} = $opt{query} ) =~
825       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
826   }
827
828   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
829     $opt{count_query} .=
830       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
831       "( disabled = '' OR disabled IS NULL )";
832   }
833
834   unless ( $type eq 'html-print' ) {
835
836     #setup some pagination things if we're in html mode
837
838     my $conf = new FS::Conf;
839     $confmax = $conf->config('maxsearchrecordsperpage');
840     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
841       $maxrecords = $1;
842     } else {
843       $maxrecords ||= $confmax;
844     }
845
846     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
847
848     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
849     $limit .= " OFFSET $offset" if $offset;
850
851   }
852
853   my $count_sth = dbh->prepare($opt{'count_query'})
854     or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
855   $count_sth->execute
856     or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
857   $count_arrayref = $count_sth->fetchrow_arrayref;
858   $total = $count_arrayref->[0];
859
860 }
861
862 # run the query
863
864 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
865 my $rows;
866 if ( ref($opt{query}) ) {
867
868   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
869     #%search = ( 'disabled' => '' );
870     $opt{'query'}->{'hashref'}->{'disabled'} = '';
871     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
872   }
873
874   #eval "use FS::$opt{'query'};";
875   $rows = [ qsearch({
876     'select'    => $opt{'query'}->{'select'},
877     'table'     => $opt{'query'}->{'table'}, 
878     'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
879     'hashref'   => $opt{'query'}->{'hashref'} || {}, 
880     'extra_sql' => $opt{'query'}->{'extra_sql'},
881     'order_by'  => $opt{'query'}->{'order_by'}. " $limit",
882   }) ];
883 } else {
884   my $sth = dbh->prepare("$opt{'query'} $limit")
885     or die "Error preparing $opt{'query'}: ". dbh->errstr;
886   $sth->execute
887     or die "Error executing $opt{'query'}: ". $sth->errstr;
888
889   #can get # of rows without fetching them all?
890   $rows = $sth->fetchall_arrayref;
891
892   $header ||= $sth->{NAME};
893 }
894
895 </%init>