source: tags/2.1.5/lib/TemplateGlue.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

File size: 18.0 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-2010 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  bool   $sort          Sort the output.
113 */
114function printSetSelectForm($db_table, $db_col, $preselected, $blank=false, $sort=false)
115{
116    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
117    if ($values === false) {
118        ?><option value="">&nbsp;</option>
119        <?php
120        return false;
121    }
122    if (true === $blank) {
123        $selected = ($preselected == '') ? ' selected' : '';
124        ?><option value=""<?php echo $selected; ?>>&nbsp;</option>
125        <?php
126    }
127    // When the 'blank' value needs a specific key->val pair.
128    if (is_array($blank)) {
129        foreach ($blank as $key=>$val) {
130            $selected = ($preselected == $val) ? ' selected="selected"' : '';
131            ?><option value="<?php echo oTxt($key); ?>"<?php echo $selected; ?>><?php echo oTxt($val); ?></option>
132            <?php
133        }
134    }
135    foreach ($values as $v) {
136        $selected = ($v == $preselected) ? ' selected' : '';
137        ?><option value="<?php echo oTxt($v); ?>"<?php echo $selected; ?>><?php echo oTxt($v); ?></option>
138        <?php
139    }
140}
141
142/**
143 * Prints radio buttons from a set/enum column.
144 *
145 * @param  string $db_table   database table to lookup
146 * @param  string $db_col     database column to lookup
147 * @param  bool   $sort          Sort the output.
148 */
149function printEnumRadios($name, $db_table, $db_col, $preselected, $blank=false, $sort=false)
150{
151    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
152    if ($values === false) {
153        return false;
154    }
155
156    foreach ($values as $v) {
157        $selected = ($v == $preselected) ? ' checked="checked"' : '';
158        ?><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>
159        <?php
160    }
161}
162
163/**
164 * Prints checkbox fields. Works only with enum or set
165 * data types in table columns.
166 *
167 * @param  string $db_table      database table to lookup
168 * @param  string $db_col        database column to lookup
169 * @param  array  $preselected   array of preselected values (matching the values in $db_col)
170 * @param  int    $columns       number of table columns to print
171 * @param  int    $flag          set to 'allone' for name of input fields to all be the same of a multidimensional array.
172 * @param  bool   $sort          Sort the output.
173 */
174function printSetCheckboxes($db_table, $db_col, $preselected, $columns=1, $flag=null, $sort)
175{
176    ?>
177    <table>
178        <tr>
179    <?php
180    // Sometimes preselected comes as a comma list.
181    if (!is_array($preselected)) {
182        $preselected = explode(',', $preselected);
183    }
184
185    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
186    // Here we assume in all the values of an array are 'on' that we can find the data
187    // in the array keys.
188    $ps_value_count = array_count_values($preselected);
189    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
190        $preselected = array_keys($preselected);
191    }
192
193    // Retrieve values of a Set or ENUM database column.
194    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
195
196    // Initialize the HTML table generation vars.
197    $num_cells = sizeof($values) - 1;
198    $num_rows = floor($num_cells / $columns);
199    $cols_lastrow = $num_cells % $columns;
200    $row_cnt = 0;
201    $col_cnt = 0;
202    foreach ($values as $v) {
203        if ($col_cnt == $columns) {
204            // Begin a new row.
205            ?></tr><tr><?php
206            $col_cnt = 0;
207            $row_cnt++;
208        }
209        if ($col_cnt < $cols_lastrow) {
210            $lastrow_add = $col_cnt;
211        } else {
212            $lastrow_add = $cols_lastrow;
213        }
214        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
215        $col_cnt++;
216
217        // Look for preselected value.
218        if (in_array($v, $preselected)) {
219            $checked = ' checked="checked"';
220        } else {
221            $checked = '';
222        }
223        if ('allone' == $flag) {
224            // Print a cell with multidimensional array checkboxes.
225            $html_name = 'dbcol[' . $db_col . '][' . $v . ']';
226        } else {
227            // Print a cell with basic named checkboxes.
228            $html_name = $db_col . '[' . $v . ']';
229        }
230        ?><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>
231        <?php
232    }
233    if ($col_cnt < $columns) {
234        // This last cell must expand to fill the last blank cells.
235        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
236    }
237    ?>
238        </tr>
239    </table><?php
240}
241
242/**
243 * Prints radio select fields. Works only with enum or set
244 * data types in table columns.
245 *
246 * @param  string $db_table      database table to lookup
247 * @param  string $db_col        database column to lookup
248 * @param  array  $preselected   array of preselected values (matching the values in $db_col)
249 * @param  int    $columns       number of table columns to print
250 * @param  bool   $sort          Sort the output.
251 */
252function printSetRadios($db_table, $db_col, $preselected, $columns=1, $sort=false)
253{
254    ?>
255    <table>
256        <tr>
257    <?php
258    // Sometimes preselected comes as a comma list.
259    if (!is_array($preselected)) {
260        $preselected = explode(',', $preselected);
261    }
262
263    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
264    // Here we assume in all the values of an array are 'on' that we can find the data
265    // in the array keys.
266    $ps_value_count = array_count_values($preselected);
267    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
268        $preselected = array_keys($preselected);
269    }
270
271    // Retrieve values of a Set or ENUM database column.
272    $values = getSetEnumFieldValues($db_table, $db_col, $sort);
273
274    // Initialize the HTML table generation vars.
275    $num_cells = sizeof($values) - 1;
276    $num_rows = floor($num_cells / $columns);
277    $cols_lastrow = $num_cells % $columns;
278    $row_cnt = 0;
279    $col_cnt = 0;
280    foreach ($values as $v) {
281        if ($col_cnt == $columns) {
282            // Begin a new row.
283            ?></tr><tr><?php
284            $col_cnt = 0;
285            $row_cnt++;
286        }
287        if ($col_cnt < $cols_lastrow) {
288            $lastrow_add = $col_cnt;
289        } else {
290            $lastrow_add = $cols_lastrow;
291        }
292        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
293        $col_cnt++;
294
295        // Look for preselected value.
296        if (in_array($v, $preselected)) {
297            $checked = ' checked="checked"';
298        } else {
299            $checked = '';
300        }
301        // Print a cell with basic named checkboxes.
302        ?><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>
303        <?php
304    }
305    if ($col_cnt < $columns) {
306        // This last cell must expand to fill the last blank cells.
307        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
308    }
309    ?>
310        </tr>
311    </table><?php
312}
313
314/**
315 * Prints a pulldown menu containing the specified values and keys of a table.
316 *
317 * @param  string $db_table         database table to lookup
318 * @param  string $key_column       column containing the human-readable titles for the select menu
319 * @param  string $val_column       column containing the computer values for the select menu
320 * @param  string $preselected      the currently selected value of the menu. compared to the $val_column
321 * @param  bool   $blank            leave one blank at the top?
322 * @param  string $extra_clause     SQL exclude clause. Something like "WHERE girls != 'buckteeth'"
323 */
324function printSelectForm($db_table, $key_column, $val_column, $preselected, $blank=false, $extra_clause='', $sql_format='SELECT %1$s, %2$s FROM %3$s %4$s')
325{
326    $db =& DB::getInstance();
327   
328    // Sometimes preselected comes as a comma list.
329    if (!is_array($preselected)) {
330        $preselected = array($preselected);
331    }
332
333    // Print a blank first option.
334    if (true === $blank) {
335        $selected = in_array('', $preselected) ? ' selected="selected"' : '';
336        ?><option value=""<?php echo $selected; ?>>&nbsp;</option>
337        <?php
338    }
339
340    // When the 'blank' value needs a specific key->val pair.
341    if (is_array($blank)) {
342        foreach ($blank as $key=>$val) {
343            $selected = in_array($key, $preselected) ? ' selected="selected"' : '';
344            ?><option value="<?php echo $key; ?>"<?php echo $selected; ?>><?php echo oTxt($val); ?></option>
345            <?php
346        }
347    }
348    // $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
349    $qid = $db->query(sprintf($sql_format, $key_column, $val_column, $db_table, $extra_clause),false);
350    while ($row = mysql_fetch_assoc($qid)) {
351        $selected = in_array($row[$val_column], $preselected) ? ' selected="selected"' : '';
352        ?><option value="<?php echo $row[$val_column]; ?>"<?php echo $selected; ?>><?php echo oTxt($row[$key_column]); ?></option><?php
353    }
354}
355
356/**
357 * Prints checkbox fields. Works only with enum or set
358 * data types in table columns.
359 *
360 * @param  string $db_table         database table to lookup
361 * @param  string $key_column       column containing the human-readable titles for the select menu
362 * @param  string $val_column       column containing the computer values for the select menu
363 * @param  string $preselected      the currently selected value of the menu. compared to the $val_column
364 * @param  int    $columns          number of table columns to print
365 * @param  int    $extra_clause     extra sql to send at end of select statement.
366 * @param  bool   $vert_columns     display checkboxes in vertical orientation first.
367 */
368function printDBCheckboxes($db_table, $key_column, $val_column, $preselected, $columns=1, $extra_clause='', $vert_columns=false)
369{
370    $db =& DB::getInstance();
371   
372    // Sometimes preselected comes as a comma list.
373    if (!is_array($preselected)) {
374        $preselected = explode(',', $preselected);
375    }
376
377    // Checkbox POST data has the primary data in the keys, and 'on' as the values.
378    // Here we assume in all the values of an array are 'on' that we can find the data
379    // in the array keys.
380    $ps_value_count = array_count_values($preselected);
381    if (isset($ps_value_count['on']) && $ps_value_count['on'] == sizeof($preselected)) {
382        $preselected = array_keys($preselected);
383    }
384
385    $qid = $db->query("SELECT $key_column, $val_column FROM $db_table $extra_clause",false);
386    while ($row = mysql_fetch_assoc($qid)) {
387        $values[] = $row;
388    }
389
390    // Rearrange array so sort is in vertical columns. FIXME: doesn't work.
391//  if ($vert_columns) {
392//      $per_col = ceil(sizeof($values) / $columns);
393//      $columns = ceil(sizeof($values) / $per_col);
394//      $curr_row = 0;
395//      $curr_col = 0;
396//      $pos = 0;
397//         foreach ($values as $k=>$v) {
398//             $pos = $curr_row * $columns + $curr_col;
399//             if ($curr_row <= $per_col) {
400//                 $curr_row++;
401//             } else {
402//                 $curr_row = 0;
403//                 $curr_col++;
404//             }
405// //             echo '<li>' . $pos . '-' . $v[$key_column];
406//             $new_values[$pos] = $v;
407//         }
408//         $values = $new_values;
409//         ksort($values);
410//  }
411
412    if (empty($values)) {
413        return false;
414    }
415
416    // Initialize the HTML table generation vars.
417    $num_cells = sizeof($values) - 1;
418    $num_rows = floor($num_cells / $columns);
419    $cols_lastrow = $num_cells % $columns;
420    $row_cnt = 0;
421    $col_cnt = 0;
422    ?>
423    <table border="0" cellspacing="0" cellpadding="0">
424        <tr>
425    <?php
426    foreach ($values as $box) {
427        if ($col_cnt == $columns) {
428            // Begin a new row.
429            ?></tr><tr><?php
430            $col_cnt = 0;
431            $row_cnt++;
432        }
433
434        if ($col_cnt < $cols_lastrow) {
435            $lastrow_add = $col_cnt;
436        } else {
437            $lastrow_add = $cols_lastrow;
438        }
439
440        $curr = $num_rows * $col_cnt + $lastrow_add + $row_cnt;
441        $col_cnt++;
442
443        // Look for preselected value.
444        if (in_array($box[$val_column], $preselected)) {
445            $checked = ' checked="checked"';
446        } else {
447            $checked = '';
448        }
449
450        // Print a cell with basic named checkboxes.
451        $html_name = $val_column . '[' . $box[$val_column] . ']';
452        $html_id = $val_column . '-' . $box[$val_column] . '';
453        ?>
454        <td><input type="checkbox" name="<?php echo oTxt($html_name); ?>" id="<?php echo oTxt($html_id); ?>"<?php echo $checked; ?> /></td>
455        <td><label for="<?php echo oTxt($html_id); ?>" class="sc-normal"><?php echo oTxt($box[$key_column]); ?></label></td>
456        <?php
457    }
458
459    if ($col_cnt < $columns) {
460        // This last cell must expand to fill the last blank cells.
461        ?><td colspan="<?php echo $columns - $col_cnt; ?>">&nbsp;</td><?php
462    }
463    ?>
464        </tr>
465    </table><?php
466}
467
468/**
469 * Prints submit buttons based on given array of submit button names and titles.
470 *
471 * @access  public
472 * @param   array   $submit_buttons     Array of buttons, the key being the button name, and value being the title of the button.
473 * @return  void
474 * @author  Quinn Comendant <quinn@strangecode.com>
475 * @version 1.0
476 * @since   15 Jun 2005 13:42:21
477 */
478function printSubmitButtons($submit_buttons)
479{
480    if (is_array($submit_buttons) && !empty($submit_buttons)) {
481        foreach ($submit_buttons as $i => $b) {
482            if (is_array($b)) {
483                $defaults = array();
484                $defaults['type'] = isset($b['type']) ? $b['type'] : 'submit';
485                $defaults['id'] = isset($b['id']) ? $b['id'] : sprintf('sc-%s-button', $b['name']);
486                $b = array_merge($defaults, $b);
487                echo '<input';
488                foreach ($b as $key => $value) {
489                    printf(' %s="%s"', $key, oTxt($value));
490                }
491                echo ' />';
492            } else {
493                // For backwards compatibility.
494                ?><input type="submit" name="<?php echo oTxt($i) ?>" value="<?php echo oTxt($b); ?>" /><?php
495            }
496        }
497    }
498}
499
500?>
Note: See TracBrowser for help on using the repository browser.