source: trunk/lib/TemplateGlue.inc.php @ 407

Last change on this file since 407 was 407, checked in by anonymous, 12 years ago

Renamed function arguments to improve readability; added missing param comments.

File size: 18.5 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/**
24 * TemplateGlue.inc.php
25 */
26
27/**
28 * Print URL to download file with BBEdit/Interarchy. "USER" must be a pre-set
29 * environment variable. Files must reside within and be relative to env "DOCUMENT_ROOT".
30 *
31 * @access  public
32 * @param   mixed   $file   File path relative to DOCUMENT_ROOT (i.e. '/_templates/index.ihtml').
33 * @return  string  <a> with file basename as text.
34 */
35function bbftp($file)
36{
37    return sprintf('<a href="bbftp://%s@%s:%s%s" title="%s" style="text-decoration: none; border-bottom: blue 1px dotted;">%s</a>', $_SERVER['USER'], $_SERVER['HTTP_HOST'], $_SERVER['DOCUMENT_ROOT'], $file, $file, basename($file));
38}
39
40/**
41 * Returns an image tag for image specified in $src.
42 *
43 * @param  string $src     File name of the image, including path and file extension.
44 * @param  string $alt     Alt tag text.
45 * @param  string $extra   Additional attributes.
46 */
47function oImg($src, $alt='', $extra='')
48{
49    $filepath = preg_match('!://!', $src) ? $src : getenv('DOCUMENT_ROOT') . $src;
50
51    if (true === ($gis = @getimagesize($filepath)) && !preg_match('/width|height/', $extra)) {
52        $image_size = $gis[3];
53    } else {
54        $image_size = '';
55    }
56
57    return sprintf('<img src="%s" %s alt="%s" %s />',
58        $src,
59        $image_size,
60        oTxt($alt),
61        $extra
62    );
63}
64
65/**
66 * Prints an image tag for image specified in $src.
67 *
68 * @param  string $src     File name of the image, including path and file extension.
69 * @param  string $alt     Alt tag text.
70 * @param  string $extra   Additional attributes.
71 */
72function printImg($src, $alt='', $extra='')
73{
74    echo oImg($src, $alt, $extra);
75}
76
77/**
78 * Finds the values of an enumeration or set column of a MySQL database, returning them in an array.
79 * Use this to generate a pull-down menu of options or to validate the existence
80 * of options. (Quinn 10 Feb 2001)
81 *
82 * @param  string $db_table   database table to lookup
83 * @param  string $db_col     database column to lookup
84 * @param  bool   $sort          Sort the output.
85 * @return array    Array of the set/enum values on success, false on failure.
86 */
87function getSetEnumFieldValues($db_table, $db_col, $sort=false)
88{
89    $app =& App::getInstance();
90    $db =& DB::getInstance();
91   
92    $qid = $db->query("SHOW COLUMNS FROM " . $db->escapeString($db_table) . " LIKE '" . $db->escapeString($db_col) . "'",false);
93
94    $row = mysql_fetch_row($qid);
95    if (preg_match('/^enum|^set/i', $row[1]) && preg_match_all("/'([^']*)'/", $row[1], $enum)) {
96        if ($sort) {
97            natsort($enum[1]);           
98        }
99        return $enum[1];
100    } else {
101        $app->logMsg(sprintf('No set or enum fields found.', null), LOG_ERR, __FILE__, __LINE__);
102        return false;
103    }
104}
105
106/**
107 * Prints option fields for a select form. Works only with enum or set
108 * data types in table columns.
109 *
110 * @param  string $db_table     Database table to lookup
111 * @param  string $db_col       Database column to lookup
112 * @param  string $preselected  The currently selected value of the menu. compared to the $val_column
113 * @param  bool   $first        Optional first item; set true for a blank item, array for item with name and value.
114 * @param  bool   $sort         Sort the output.
115 */
116function printSetSelectForm($db_table, $db_col, $preselected, $first=false, $sort=false)
117{
118    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
119    if ($values === false) {
120        ?><option value="">&nbsp;</option>
121        <?php
122        return false;
123    }
124    if (true === $first) {
125        $selected = ($preselected == '') ? ' selected' : '';
126        ?><option value=""<?php echo $selected; ?>>&nbsp;</option>
127        <?php
128    }
129    // When the 'blank' value needs a specific key->val pair.
130    if (is_array($first)) {
131        foreach ($first as $key=>$val) {
132            $selected = ($preselected == $val) ? ' selected="selected"' : '';
133            ?><option value="<?php echo oTxt($key); ?>"<?php echo $selected; ?>><?php echo oTxt($val); ?></option>
134            <?php
135        }
136    }
137    foreach ($values as $v) {
138        $selected = ($v == $preselected) ? ' selected' : '';
139        ?><option value="<?php echo oTxt($v); ?>"<?php echo $selected; ?>><?php echo oTxt($v); ?></option>
140        <?php
141    }
142}
143
144/**
145 * Prints radio buttons from a set/enum column.
146 *
147 * @param  string $db_table     Database table to lookup
148 * @param  string $db_col       Database column to lookup
149 * @param  string $preselected  The currently selected value of the menu. compared to the $val_column
150 * @param  bool   $first        Optional first item; set true for a blank item, array for item with name and value.
151 * @param  bool   $sort         Sort the output.
152 */
153function printEnumRadios($name, $db_table, $db_col, $preselected, $first=false, $sort=false)
154{
155    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
156    if ($values === false) {
157        return false;
158    }
159
160    foreach ($values as $v) {
161        $selected = ($v == $preselected) ? ' checked="checked"' : '';
162        ?><label class="sc-label-secondary"><input type="radio" name="<?php echo oTxt($name) ?>" id="<?php echo oTxt($v); ?>" value="<?php echo oTxt($v); ?>"<?php echo $selected; ?> /> <?php echo oTxt($v); ?></label>
163        <?php
164    }
165}
166
167/**
168 * Prints checkbox fields. Works only with enum or set
169 * data types in table columns.
170 *
171 * @param  string $db_table      database table to lookup
172 * @param  string $db_col        database column to lookup
173 * @param  array  $preselected   array of preselected values (matching the values in $db_col)
174 * @param  int    $columns       number of table columns to print
175 * @param  int    $flag          set to 'allone' for name of input fields to all be the same of a multidimensional array.
176 * @param  bool   $sort          Sort the output.
177 */
178function printSetCheckboxes($db_table, $db_col, $preselected, $columns=1, $flag=null, $sort)
179{
180    ?>
181    <table>
182        <tr>
183    <?php
184    // Sometimes preselected comes as a comma list.
185    if (!is_array($preselected)) {
186        $preselected = explode(',', $preselected);
187    }
188
189    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
190    // Here we assume in all the values of an array are 'on' that we can find the data
191    // in the array keys.
192    $ps_value_count = array_count_values($preselected);
193    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
194        $preselected = array_keys($preselected);
195    }
196
197    // Retrieve values of a Set or ENUM database column.
198    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
199
200    // Initialize the HTML table generation vars.
201    $num_cells = sizeof($values) - 1;
202    $num_rows = floor($num_cells / $columns);
203    $cols_lastrow = $num_cells % $columns;
204    $row_cnt = 0;
205    $col_cnt = 0;
206    foreach ($values as $v) {
207        if ($col_cnt == $columns) {
208            // Begin a new row.
209            ?></tr><tr><?php
210            $col_cnt = 0;
211            $row_cnt++;
212        }
213        if ($col_cnt < $cols_lastrow) {
214            $lastrow_add = $col_cnt;
215        } else {
216            $lastrow_add = $cols_lastrow;
217        }
218        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
219        $col_cnt++;
220
221        // Look for preselected value.
222        if (in_array($v, $preselected)) {
223            $checked = ' checked="checked"';
224        } else {
225            $checked = '';
226        }
227        if ('allone' == $flag) {
228            // Print a cell with multidimensional array checkboxes.
229            $html_name = 'dbcol[' . $db_col . '][' . $v . ']';
230        } else {
231            // Print a cell with basic named checkboxes.
232            $html_name = $db_col . '[' . $v . ']';
233        }
234        ?><td><label class="sc-label-secondary"><input type="checkbox" name="<?php echo oTxt($html_name); ?>" id="<?php echo oTxt($html_name); ?>"<?php echo $checked; ?> /> <?php echo oTxt($v); ?></label></td>
235        <?php
236    }
237    if ($col_cnt < $columns) {
238        // This last cell must expand to fill the last blank cells.
239        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
240    }
241    ?>
242        </tr>
243    </table><?php
244}
245
246/**
247 * Prints radio select fields. Works only with enum or set
248 * data types in table columns.
249 *
250 * @param  string $db_table      database table to lookup
251 * @param  string $db_col        database column to lookup
252 * @param  array  $preselected   array of preselected values (matching the values in $db_col)
253 * @param  int    $columns       number of table columns to print
254 * @param  bool   $sort          Sort the output.
255 */
256function printSetRadios($db_table, $db_col, $preselected, $columns=1, $sort=false)
257{
258    ?>
259    <table>
260        <tr>
261    <?php
262    // Sometimes preselected comes as a comma list.
263    if (!is_array($preselected)) {
264        $preselected = explode(',', $preselected);
265    }
266
267    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
268    // Here we assume in all the values of an array are 'on' that we can find the data
269    // in the array keys.
270    $ps_value_count = array_count_values($preselected);
271    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
272        $preselected = array_keys($preselected);
273    }
274
275    // Retrieve values of a Set or ENUM database column.
276    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
277
278    // Initialize the HTML table generation vars.
279    $num_cells = sizeof($values) - 1;
280    $num_rows = floor($num_cells / $columns);
281    $cols_lastrow = $num_cells % $columns;
282    $row_cnt = 0;
283    $col_cnt = 0;
284    foreach ($values as $v) {
285        if ($col_cnt == $columns) {
286            // Begin a new row.
287            ?></tr><tr><?php
288            $col_cnt = 0;
289            $row_cnt++;
290        }
291        if ($col_cnt < $cols_lastrow) {
292            $lastrow_add = $col_cnt;
293        } else {
294            $lastrow_add = $cols_lastrow;
295        }
296        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
297        $col_cnt++;
298
299        // Look for preselected value.
300        if (in_array($v, $preselected)) {
301            $checked = ' checked="checked"';
302        } else {
303            $checked = '';
304        }
305        // Print a cell with basic named checkboxes.
306        ?><td><label class="sc-label-secondary"><input type="radio" name="<?php echo oTxt($db_col); ?>" id="<?php echo oTxt($db_col . '-' . $v); ?>" value="<?php echo oTxt($v); ?>"<?php echo $checked; ?> /> <?php echo oTxt($v); ?></label></td>
307        <?php
308    }
309    if ($col_cnt < $columns) {
310        // This last cell must expand to fill the last blank cells.
311        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
312    }
313    ?>
314        </tr>
315    </table><?php
316}
317
318/**
319 * Prints a pulldown menu containing the specified values and keys of a table.
320 *
321 * @param  string $db_table         database table to lookup
322 * @param  string $key_column       column containing the human-readable titles for the select menu
323 * @param  string $val_column       column containing the computer values for the select menu
324 * @param  string $preselected      the currently selected value of the menu. compared to the $val_column
325 * @param  bool   $first            Optional first item; set true for a blank item, array for item with name and value.
326 * @param  string $extra_clause     SQL exclude clause. Something like "WHERE girls != 'buckteeth'"
327 */
328function printSelectForm($db_table, $key_column, $val_column, $preselected, $first=false, $extra_clause='', $sql_format='SELECT %1$s, %2$s FROM %3$s %4$s')
329{
330    $db =& DB::getInstance();
331   
332    // Sometimes preselected comes as a comma list.
333    if (!is_array($preselected)) {
334        $preselected = array($preselected);
335    }
336
337    // Print a blank first option.
338    if (true === $first) {
339        $selected = in_array('', $preselected) ? ' selected="selected"' : '';
340        ?><option value=""<?php echo $selected; ?>>&nbsp;</option>
341        <?php
342    }
343
344    // When the 'blank' value needs a specific key->val pair.
345    if (is_array($first)) {
346        foreach ($first as $key=>$val) {
347            $selected = in_array($key, $preselected) ? ' selected="selected"' : '';
348            ?><option value="<?php echo $key; ?>"<?php echo $selected; ?>><?php echo oTxt($val); ?></option>
349            <?php
350        }
351    }
352    // $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
353    $qid = $db->query(sprintf($sql_format, $key_column, $val_column, $db_table, $extra_clause),false);
354    while ($row = mysql_fetch_assoc($qid)) {
355        $selected = in_array($row[$val_column], $preselected) ? ' selected="selected"' : '';
356        ?><option value="<?php echo $row[$val_column]; ?>"<?php echo $selected; ?>><?php echo oTxt($row[$key_column]); ?></option><?php
357    }
358}
359
360/**
361 * Prints checkbox fields. Works only with enum or set
362 * data types in table columns.
363 *
364 * @param  string $db_table         database table to lookup
365 * @param  string $key_column       column containing the human-readable titles for the select menu
366 * @param  string $val_column       column containing the computer values for the select menu
367 * @param  string $preselected      the currently selected value of the menu. compared to the $val_column
368 * @param  int    $columns          number of table columns to print
369 * @param  int    $extra_clause     extra sql to send at end of select statement.
370 * @param  bool   $vert_columns     display checkboxes in vertical orientation first.
371 */
372function printDBCheckboxes($db_table, $key_column, $val_column, $preselected, $columns=1, $extra_clause='', $vert_columns=false)
373{
374    $db =& DB::getInstance();
375   
376    // Sometimes preselected comes as a comma list.
377    if (!is_array($preselected)) {
378        $preselected = explode(',', $preselected);
379    }
380
381    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
382    // Here we assume in all the values of an array are 'on' that we can find the data
383    // in the array keys.
384    $ps_value_count = array_count_values($preselected);
385    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
386        $preselected = array_keys($preselected);
387    }
388
389    $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
390    while ($row = mysql_fetch_assoc($qid)) {
391        $values[] = $row;
392    }
393
394    // Rearrange array so sort is in vertical columns. FIXME: doesn't work.
395//  if ($vert_columns) {
396//      $per_col = ceil(sizeof($values) / $columns);
397//      $columns = ceil(sizeof($values) / $per_col);
398//      $curr_row = 0;
399//      $curr_col = 0;
400//      $pos = 0;
401//         foreach ($values as $k=>$v) {
402//             $pos = $curr_row * $columns + $curr_col;
403//             if ($curr_row <= $per_col) {
404//                 $curr_row++;
405//             } else {
406//                 $curr_row = 0;
407//                 $curr_col++;
408//             }
409// //             echo '<li>' . $pos . '-' . $v[$key_column];
410//             $new_values[$pos] = $v;
411//         }
412//         $values = $new_values;
413//         ksort($values);
414//  }
415
416    if (empty($values)) {
417        return false;
418    }
419
420    // Initialize the HTML table generation vars.
421    $num_cells = sizeof($values) - 1;
422    $num_rows = floor($num_cells / $columns);
423    $cols_lastrow = $num_cells % $columns;
424    $row_cnt = 0;
425    $col_cnt = 0;
426    ?>
427    <table border="0" cellspacing="0" cellpadding="0">
428        <tr>
429    <?php
430    foreach ($values as $box) {
431        if ($col_cnt == $columns) {
432            // Begin a new row.
433            ?></tr><tr><?php
434            $col_cnt = 0;
435            $row_cnt++;
436        }
437
438        if ($col_cnt < $cols_lastrow) {
439            $lastrow_add = $col_cnt;
440        } else {
441            $lastrow_add = $cols_lastrow;
442        }
443
444        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
445        $col_cnt++;
446
447        // Look for preselected value.
448        if (in_array($box[$val_column], $preselected)) {
449            $checked = ' checked="checked"';
450        } else {
451            $checked = '';
452        }
453
454        // Print a cell with basic named checkboxes.
455        $html_name = $val_column . '[' . $box[$val_column] . ']';
456        $html_id = $val_column . '-' . $box[$val_column] . '';
457        ?>
458        <td><input type="checkbox" name="<?php echo oTxt($html_name); ?>" id="<?php echo oTxt($html_id); ?>"<?php echo $checked; ?> /></td>
459        <td><label for="<?php echo oTxt($html_id); ?>" class="sc-normal"><?php echo oTxt($box[$key_column]); ?></label></td>
460        <?php
461    }
462
463    if ($col_cnt < $columns) {
464        // This last cell must expand to fill the last blank cells.
465        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
466    }
467    ?>
468        </tr>
469    </table><?php
470}
471
472/**
473 * Prints submit buttons based on given array of submit button names and titles.
474 *
475 * @access  public
476 * @param   array   $submit_buttons     Array of buttons, the key being the button name, and value being the title of the button.
477 * @return  void
478 * @author  Quinn Comendant <quinn@strangecode.com>
479 * @version 1.0
480 * @since   15 Jun 2005 13:42:21
481 */
482function printSubmitButtons($submit_buttons)
483{
484    if (is_array($submit_buttons) && !empty($submit_buttons)) {
485        foreach ($submit_buttons as $i => $b) {
486            if (is_array($b)) {
487                $defaults = array();
488                $defaults['type'] = isset($b['type']) ? $b['type'] : 'submit';
489                $defaults['id'] = isset($b['id']) ? $b['id'] : sprintf('sc-%s-button', $b['name']);
490                $b = array_merge($defaults, $b);
491                echo '<input';
492                foreach ($b as $key => $value) {
493                    printf(' %s="%s"', $key, oTxt($value));
494                }
495                echo ' />';
496            } else {
497                // For backwards compatibility.
498                ?><input type="submit" name="<?php echo oTxt($i) ?>" value="<?php echo oTxt($b); ?>" /><?php
499            }
500        }
501    }
502}
503
504?>
Note: See TracBrowser for help on using the repository browser.