source: trunk/lib/HTML.inc.php @ 500

Last change on this file since 500 was 500, checked in by anonymous, 10 years ago

Many auth and crypto changes; various other bugfixes while working on pulso.

File size: 13.2 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/>
5* Copyright © 2014 Strangecode, LLC
6*
7* This program is free software: you can redistribute it and/or modify
8* it under the terms of the GNU General Public License as published by
9* the Free Software Foundation, either version 3 of the License, or
10* (at your option) any later version.
11*
12* This program is distributed in the hope that it will be useful,
13* but WITHOUT ANY WARRANTY; without even the implied warranty of
14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15* GNU General Public License for more details.
16*
17* You should have received a copy of the GNU General Public License
18* along with this program.  If not, see <http://www.gnu.org/licenses/>.
19*/
20
21/*
22* HTML()
23*
24* Tools for building HTML from PHP data.
25*
26* @author   Quinn Comendant <quinn@strangecode.com>
27* @version  1.0
28* @since    11 Sep 2014 21:08:06
29*
30* Example of use:
31---------------------------------------------------------------------
32echo HTML::buttons(array(
33    array('name' => 'submit', 'value' => _("Save changes"), 'class' => 'small button', 'accesskey' => 's'),
34    array('name' => 'reset', 'value' => _("Reset"), 'class' => 'small button secondary', 'accesskey' => 'r'),
35    array('name' => 'cancel', 'value' => _("Cancel"), 'class' => 'small button secondary', 'accesskey' => 'c'),
36));
37---------------------------------------------------------------------
38*/
39
40class HTML {
41
42    // Browsers add names and ids of form controls as properties to the FORM. This results in the properties of the form being replaced.
43    // Use this list to warn the programmer if he uses an unsafe name.
44    // http://jibbering.com/faq/names/unsafe_names.html
45    static $unsafe_form_control_names = array('accept','acceptCharset','action','addBehavior','addEventListener','addEventSource','addRepetitionBlock','addRepetitionBlockByIndex','all','appendChild','applyElement','ariaBusy','ariaChecked','ariaControls','ariaDescribability','ariaDisabled','ariaExpanded','ariaFlowto','ariaHaspopup','ariaHidden','ariaInvalid','ariaLabelledby','ariaLevel','ariaMultiselect','ariaOwns','ariaPosinset','ariaPressed','ariaReadonly','ariaRequired','ariaSecret','ariaSelected','ariaSetsize','ariaValuemax','ariaValuemin','ariaValuenow','attachEvent','attributes','ATTRIBUTE_NODE','autocomplete','baseURI','behaviorUrns','blockDiraction','blur','canHaveChildren','canHaveHTML','CDATA_SECTION_NODE','checkValidity','childElementCount','childNodes','children','className','clearAttributes','click','clientHeight','clientLeft','clientTop','clientWidth','cloneNode','COMMENT_NODE','compareDocumentPosition','componentFromPoint','constructor','contains','contentEditable','currentStyle','data','detachEvent','dir','dispatchEvent','dispatchFormChange','dispatchFormInput','document','DOCUMENT_FRAGMENT_NODE','DOCUMENT_NODE','DOCUMENT_POSITION_CONTAINED_BY','DOCUMENT_POSITION_CONTAINS','DOCUMENT_POSITION_DISCONNECTED','DOCUMENT_POSITION_FOLLOWING','DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC','DOCUMENT_POSITION_PRECEDING','DOCUMENT_TYPE_NODE','dragDrop','elements','ELEMENT_NODE','encoding','enctype','ENTITY_NODE','ENTITY_REFERENCE_NODE','fireEvent','firstChild','firstElementChild','focus','getAdjacentText','getAttribute','getAttributeNode','getAttributeNodeNS','getAttributeNS','getBoundingClientRect','getClientRects','getElementsByClassName','getElementsByTagName','getElementsByTagNameNS','getExpression','getFeature','getUserData','hasAttribute','hasAttributeNS','hasAttributes','hasChildNodes','hasOwnProperty','hideFocus','id','innerHTML','innerText','insertAdjacentElement','insertAdjacentHTML','insertAdjacentText','insertBefore','isContentEditable','isDefaultNamespace','isDefaultNamespaceURI','isDisabled','isEqualNode','isMultiLine','isPrototypeOf','isSameNode','isSupported','isTextEdit','item','lang','language','lastChild','lastElementChild','length','localName','lookupPrefix','mergeAttributes','method','moveRepetitionBlock','msBlockProgression','msBoxSizing','name','namedItem','namespaceURI','nextSibling','nodeName','nodeType','nodeValue','normalize','NOTATION_NODE','offsetHeight','offsetWidth','onabort','onactivate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate','onbeforeeditfocus','onbeforepaste','onblur','onchage','onclick','onclosecapture','oncontextmenu','oncopy','oncut','ondblclick','ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','onerror','onfocus','onfocusin','onfocusout','onhelp','oninput','onkeydown','onkeypress','onkeyup','onmousedown','onmouseenter','onmouseleave','onmousemove','onmousemultiwheel','onmouseout','onmouseover','onmouseup','onmousewheel','onmove','onmoveend','onmovestart','onOffBehavior','onpaste','onpropertychange','onreadystatechange','onresize','onresizeend','onresizestart','onscroll','onsearch','onselect','onselectstart','ontimeerror','onunload','outerHTML','outerText','ownerDocument','parentNode','parentTextEdit','prefix','previousElementSibling','previousSibling','PROCESSING_INSTRUCTION_NODE','propertyIsEnumerable','querySelector','querySelectorAll','quotes','releaseCapture','removeAttribute','removeAttributeNode','removeAttributeNS','removeBehavior','removeChild','removeEventListener','removeEventSource','removeExpression','removeNode','removeRepetitionBlock','repeatMax','repeatMin','repeatStart','repetitionBlocks','repetitionIndex','repetitionTemplate','repetitionType','replace','replaceAdjacentText','replaceChild','replaceNode','reset','resetFromData','role','runtimeStyle','schemaTypeInfo','scopeName','scrollByLines','scrollByPages','scrollHeight','scrollIntoView','scrollLeft','scrollTop','scrollWidth','selectNodes','selectSingleNode','setActive','setAttributeNode','setAttributeNodeNS','setAttributeNS','setCapture','setExpression','setIdAttribute','setIdAttributeNode','setIdAttributeNS','setUserData','sourceIndex','spellcheck','style','submit','swapNode','tabIndex','tagName','tagUrn','target','templateElements','text','textContent','TEXT_NODE','title','toLocaleString','toString','uniqueID','unselectable','unwatch','urns','valueOf','watch','window');
46
47    /**
48    * Prints submit buttons based on given array of submit button names and titles. If the array includes an 'href' key, the
49    * button is created using a <a> otherwise an <input type="
" /> is used.
50    *
51    * @access  public
52    * @param   array   $buttons     Array of buttons, the key being the button name, and value being the title of the button.
53    * @return  void
54    * @author   Quinn Comendant <quinn@strangecode.com>
55    * @version  1.0
56    * @since    12 Sep 2014 00:17:38
57    */
58    static public function printButtons($buttons=array(), $class='button-group')
59    {
60        $app =& App::getInstance();
61
62        if (!isset($buttons[0]) || !is_array($buttons[0])) {
63            $app =& App::getInstance();
64            $app->logMsg(sprintf('Incorrect parameters passed to HTML::buttons(): %s', getDump($buttons)), LOG_DEBUG, __FILE__, __LINE__);
65            return false;
66        }
67        if (empty($buttons)) {
68            return '';
69        }
70        ?><ul class="<?php echo oTxt($class) ?>"><?php
71        foreach ($buttons as $i => $b) {
72            $defaults = array();
73            $defaults['type'] = isset($b['type']) ? $b['type'] : 'submit';
74            $b = array_merge($defaults, $b);
75            if (isset($b['href'])) {
76                echo '<li><a';
77                foreach (array_diff_key($b, array('value' => null)) as $key => $value) {
78                    printf(' %s="%s"', $key, oTxt($value));
79                }
80                echo '>' . oTxt($b['value']) . '</a></li>';
81            } else if (isset($b['name'])) {
82                if (in_array($b['name'], self::$unsafe_form_control_names)) {
83                    $app->logMsg(sprintf('Unsafe form control name: %s', $b['name']), LOG_NOTICE, __FILE__, __LINE__);
84                }
85                $defaults['id'] = isset($b['id']) ? $b['id'] : sprintf('sc-%s-button', $b['name']);
86                echo '<li><input';
87                foreach ($b as $key => $value) {
88                    printf(' %s="%s"', $key, oTxt($value));
89                }
90                echo ' /></li>';
91            } else {
92                $app->logMsg(sprintf('Button missing name or href: %s', getDump($b)), LOG_ERR, __FILE__, __LINE__);
93                continue;
94            }
95        }
96        ?></ul><?php
97    }
98
99    /*
100    * Return an array of key-value pairs matching a database query for the given parameters. This is useful for
101    * injecting into HTML::printSelectOptions().
102    *
103    * @access   public
104    * @param  string $db_table         database table to lookup
105    * @param  string $key_column       column containing the human-readable titles for the select menu
106    * @param  string $val_column       column containing the computer values for the select menu
107    * @param  string $preselected      the currently selected value of the menu. compared to the $val_column
108    * @param  bool   $first            Optional first item; set true for a blank item, array for item with name and value.
109    * @param  string $extra_clause     SQL exclude clause. Something like "WHERE girls != 'buckteeth'"
110    * @return array                    Array of options suitable to pass into HTML::printSelectOptions().
111    * @author   Quinn Comendant <quinn@strangecode.com>
112    * @version  1.0
113    * @since    12 Sep 2014 11:43:23
114    */
115    static public function getSelectOptions($db_table, $key_column, $val_column, $preselected, $first=false, $extra_clause='', $sql_format='SELECT %1$s, %2$s FROM %3$s %4$s')
116    {
117        $db =& DB::getInstance();
118
119        // Sometimes preselected comes as a comma list.
120        if (!is_array($preselected)) {
121            $preselected = array($preselected);
122        }
123
124        $options = array();
125        if (true === $first) {
126            // Include a blank first option.
127            $options[] = array(
128                'value' => '',
129                'selected' => in_array('', $preselected),
130                'text' => '',
131            );
132        } else if (is_array($first)) {
133            // When the 'blank' first option needs a specific key->val pair.
134            foreach ($first as $key => $val) {
135                $options[] = array(
136                    'value' => $key,
137                    'selected' => in_array($key, $preselected),
138                    'text' => $val,
139                );
140            }
141        }
142
143        $db =& DB::getInstance();
144        $qid = $db->query(sprintf($sql_format, $key_column, $val_column, $db_table, $extra_clause), false);
145        while ($row = mysql_fetch_assoc($qid)) {
146            $options[] = array(
147                'value' => $row[$val_column],
148                'selected' => in_array($row[$val_column], $preselected),
149                'text' => $row[$key_column],
150            );
151        }
152        return $options;
153    }
154
155    /**
156     * Prints option fields for a select form. Works only with enum or set
157     * data types in table columns.
158     *
159     * @param  string $db_table     Database table to lookup
160     * @param  string $db_col       Database column to lookup
161     * @param  string $preselected  The currently selected value of the menu. compared to the $val_column
162     * @param  bool   $first        Optional first item; set true for a blank item, array for item with name and value.
163     * @param  bool   $sort         Sort the output.
164     */
165    static public function getSelectOptionsEnum($db_table, $db_col, $preselected, $first=false, $sort=false)
166    {
167        // Sometimes preselected comes as a comma list.
168        if (!is_array($preselected)) {
169            $preselected = array($preselected);
170        }
171
172        $options = array();
173        if (true === $first) {
174            // Include a blank first option.
175            $options[] = array(
176                'value' => '',
177                'selected' => in_array('', $preselected),
178                'text' => '',
179            );
180        } else if (is_array($first)) {
181            // When the 'blank' first option needs a specific key->val pair.
182            foreach ($first as $key => $val) {
183                $options[] = array(
184                    'value' => $key,
185                    'selected' => in_array($key, $preselected),
186                    'text' => $val,
187                );
188            }
189        }
190
191        $db =& DB::getInstance();
192        $values = $db->getEnumValues($db_table, $db_col, $sort);
193        foreach ($values as $v) {
194            $options[] = array(
195                'value' => $v,
196                'selected' => in_array($v, $preselected),
197                'text' => $v,
198            );
199        }
200
201        return $options;
202    }
203
204    /**
205     * Prints a select menu containing the specified values and keys of a table.
206     *
207     */
208    static public function printSelectOptions($options)
209    {
210        if (!isset($options) || !is_array($options)) {
211            $app =& App::getInstance();
212            $app->logMsg(sprintf('Incorrect parameters passed to HTML::printSelectOptions(): %s', getDump($options)), LOG_DEBUG, __FILE__, __LINE__);
213            return false;
214        }
215        if (empty($options)) {
216            return '';
217        }
218
219        foreach ($options as $o) {
220            printf('<option value="%s"%s>%s</option>',
221                oTxt($o['value']),
222                ($o['selected'] ? ' selected' : ''),
223                oTxt($o['text'])
224            );
225        }
226    }
227}
Note: See TracBrowser for help on using the repository browser.