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