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 | --------------------------------------------------------------------- |
---|
32 | echo 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 | |
---|
40 | class HTML |
---|
41 | { |
---|
42 | |
---|
43 | // Browsers add names and ids of form controls as properties to the FORM. This results in the properties of the form being replaced. |
---|
44 | // Use this list to warn the programmer if he uses an unsafe name. |
---|
45 | // http://jibbering.com/faq/names/unsafe_names.html |
---|
46 | 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', |
---|
47 | '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'); |
---|
48 | |
---|
49 | /** |
---|
50 | * Prints submit buttons based on given array of submit button names and titles. If the array includes an 'href' key, the |
---|
51 | * button is created using a <a> otherwise an <input type="âŠ" /> is used. |
---|
52 | * |
---|
53 | * @access public |
---|
54 | * @param array $buttons Array of buttons, the key being the button name, and value being the title of the button. |
---|
55 | * @return void |
---|
56 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
57 | * @version 1.0 |
---|
58 | * @since 12 Sep 2014 00:17:38 |
---|
59 | */ |
---|
60 | static public function printButtons($buttons=array(), $class='button-group') |
---|
61 | { |
---|
62 | $app =& App::getInstance(); |
---|
63 | |
---|
64 | if (!isset($buttons[0]) || !is_array($buttons[0])) { |
---|
65 | $app =& App::getInstance(); |
---|
66 | $app->logMsg(sprintf('Incorrect parameters passed to HTML::buttons(): %s', getDump($buttons)), LOG_DEBUG, __FILE__, __LINE__); |
---|
67 | return false; |
---|
68 | } |
---|
69 | if (empty($buttons)) { |
---|
70 | return ''; |
---|
71 | } |
---|
72 | ?><ul class="<?php echo oTxt($class) ?>"><?php |
---|
73 | foreach ($buttons as $i => $b) { |
---|
74 | $defaults = array(); |
---|
75 | $defaults['type'] = isset($b['type']) ? $b['type'] : 'submit'; |
---|
76 | $b = array_merge($defaults, $b); |
---|
77 | if (isset($b['href'])) { |
---|
78 | echo '<li><a'; |
---|
79 | foreach (array_diff_key($b, array('value' => null)) as $key => $value) { |
---|
80 | printf(' %s="%s"', $key, oTxt($value)); |
---|
81 | } |
---|
82 | echo '>' . oTxt($b['value']) . '</a></li>'; |
---|
83 | } else if (isset($b['name'])) { |
---|
84 | if (in_array($b['name'], self::$unsafe_form_control_names)) { |
---|
85 | $app->logMsg(sprintf('Unsafe form control name: %s', $b['name']), LOG_NOTICE, __FILE__, __LINE__); |
---|
86 | } |
---|
87 | $defaults['id'] = isset($b['id']) ? $b['id'] : sprintf('sc-%s-button', $b['name']); |
---|
88 | echo '<li><input'; |
---|
89 | foreach ($b as $key => $value) { |
---|
90 | printf(' %s="%s"', $key, oTxt($value)); |
---|
91 | } |
---|
92 | echo ' /></li>'; |
---|
93 | } else { |
---|
94 | $app->logMsg(sprintf('Button missing name or href: %s', getDump($b)), LOG_ERR, __FILE__, __LINE__); |
---|
95 | continue; |
---|
96 | } |
---|
97 | } |
---|
98 | ?></ul><?php |
---|
99 | } |
---|
100 | |
---|
101 | /* |
---|
102 | * Return an array of key-value pairs matching a database query for the given parameters. This is useful for |
---|
103 | * injecting into HTML::printSelectOptions(). |
---|
104 | * |
---|
105 | * @access public |
---|
106 | * @param string $db_table database table to lookup |
---|
107 | * @param string $key_column column containing the human-readable titles for the select menu |
---|
108 | * @param string $val_column column containing the computer values for the select menu |
---|
109 | * @param string $preselected the currently selected value of the menu. compared to the $val_column |
---|
110 | * @param bool $first Optional first item; set true for a blank item, array for item with name and value. |
---|
111 | * @param string $extra_clause SQL exclude clause. Something like "WHERE girls != 'buckteeth'" |
---|
112 | * @return array Array of options suitable to pass into HTML::printSelectOptions(). |
---|
113 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
114 | * @version 1.0 |
---|
115 | * @since 12 Sep 2014 11:43:23 |
---|
116 | */ |
---|
117 | 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') |
---|
118 | { |
---|
119 | $db =& DB::getInstance(); |
---|
120 | |
---|
121 | // Sometimes preselected comes as a comma list. |
---|
122 | if (!is_array($preselected)) { |
---|
123 | $preselected = array($preselected); |
---|
124 | } |
---|
125 | |
---|
126 | $options = array(); |
---|
127 | if (true === $first) { |
---|
128 | // Include a blank first option. |
---|
129 | $options[] = array( |
---|
130 | 'value' => '', |
---|
131 | 'selected' => in_array('', $preselected), |
---|
132 | 'text' => '', |
---|
133 | ); |
---|
134 | } else if (is_array($first)) { |
---|
135 | // When the 'blank' first option needs a specific key->val pair. |
---|
136 | foreach ($first as $key => $val) { |
---|
137 | $options[] = array( |
---|
138 | 'value' => $key, |
---|
139 | 'selected' => in_array($key, $preselected), |
---|
140 | 'text' => $val, |
---|
141 | ); |
---|
142 | } |
---|
143 | } |
---|
144 | |
---|
145 | $db =& DB::getInstance(); |
---|
146 | $qid = $db->query(sprintf($sql_format, $key_column, $val_column, $db_table, $extra_clause), false); |
---|
147 | while ($row = mysql_fetch_assoc($qid)) { |
---|
148 | $options[] = array( |
---|
149 | 'value' => $row[$val_column], |
---|
150 | 'selected' => in_array($row[$val_column], $preselected), |
---|
151 | 'text' => $row[$key_column], |
---|
152 | ); |
---|
153 | } |
---|
154 | return $options; |
---|
155 | } |
---|
156 | |
---|
157 | /* |
---|
158 | * |
---|
159 | * |
---|
160 | * @access public |
---|
161 | * @param array $options Array of options, with keys: value, selected, text |
---|
162 | * @param array $deselected Array of values to disable in options. |
---|
163 | * @return array Same options, but those with a value matching an element in $deselected will have a 'disabled' element of true. |
---|
164 | * @author Quinn Comendant <quinn@strangecode.com> |
---|
165 | * @version 1.0 |
---|
166 | * @since 24 Jul 2015 01:41:33 |
---|
167 | */ |
---|
168 | static public function disableSelectOptions($options, $deselected) |
---|
169 | { |
---|
170 | $app =& App::getInstance(); |
---|
171 | $n = sizeof($options); |
---|
172 | for ($i=0; $i < $n; $i++) { |
---|
173 | $app->logMsg(sprintf('Disable check: %s == %s', $options[$i]['value'], getDump($deselected)), LOG_DEBUG, __FILE__, __LINE__); |
---|
174 | $options[$i]['disabled'] = in_array($options[$i]['value'], $deselected); |
---|
175 | } |
---|
176 | return $options; |
---|
177 | } |
---|
178 | |
---|
179 | /** |
---|
180 | * Get an array of option fields for a select form. Works only with enum or set |
---|
181 | * data types in table columns. |
---|
182 | * |
---|
183 | * @param string $db_table Database table to lookup |
---|
184 | * @param string $db_col Database column to lookup |
---|
185 | * @param string $preselected The currently selected value of the menu. compared to the $val_column |
---|
186 | * @param bool $first Optional first item; set true for a blank item, array for item with name and value. |
---|
187 | * @param bool $sort Sort the output. |
---|
188 | */ |
---|
189 | static public function getSelectOptionsEnum($db_table, $db_col, $preselected, $first=false, $sort=false) |
---|
190 | { |
---|
191 | // Sometimes preselected comes as a comma list. |
---|
192 | if (!is_array($preselected)) { |
---|
193 | $preselected = array($preselected); |
---|
194 | } |
---|
195 | |
---|
196 | $options = array(); |
---|
197 | if (true === $first) { |
---|
198 | // Include a blank first option. |
---|
199 | $options[] = array( |
---|
200 | 'value' => '', |
---|
201 | 'selected' => in_array('', $preselected), |
---|
202 | 'text' => '', |
---|
203 | ); |
---|
204 | } else if (is_array($first)) { |
---|
205 | // When the 'blank' first option needs a specific key->val pair. |
---|
206 | foreach ($first as $key => $val) { |
---|
207 | $options[] = array( |
---|
208 | 'value' => $key, |
---|
209 | 'selected' => in_array($key, $preselected), |
---|
210 | 'text' => $val, |
---|
211 | ); |
---|
212 | } |
---|
213 | } |
---|
214 | |
---|
215 | $db =& DB::getInstance(); |
---|
216 | $values = $db->getEnumValues($db_table, $db_col, $sort); |
---|
217 | foreach ($values as $v) { |
---|
218 | $options[] = array( |
---|
219 | 'value' => $v, |
---|
220 | 'selected' => in_array($v, $preselected), |
---|
221 | 'text' => $v, |
---|
222 | ); |
---|
223 | } |
---|
224 | |
---|
225 | return $options; |
---|
226 | } |
---|
227 | |
---|
228 | /** |
---|
229 | * Prints select menu options with the specified array of keys and values. |
---|
230 | * |
---|
231 | */ |
---|
232 | static public function printSelectOptions($options) |
---|
233 | { |
---|
234 | if (!isset($options) || !is_array($options)) { |
---|
235 | $app =& App::getInstance(); |
---|
236 | $app->logMsg(sprintf('Incorrect parameters passed to HTML::printSelectOptions(): %s', getDump($options)), LOG_DEBUG, __FILE__, __LINE__); |
---|
237 | return false; |
---|
238 | } |
---|
239 | if (empty($options)) { |
---|
240 | return ''; |
---|
241 | } |
---|
242 | |
---|
243 | foreach ($options as $o) { |
---|
244 | printf('<option value="%s"%s%s>%s</option>', |
---|
245 | oTxt($o['value']), |
---|
246 | (isset($o['selected']) && $o['selected'] ? ' selected' : ''), |
---|
247 | (isset($o['disabled']) && $o['disabled'] ? ' disabled' : ''), |
---|
248 | oTxt($o['text']) |
---|
249 | ); |
---|
250 | } |
---|
251 | } |
---|
252 | |
---|
253 | /** |
---|
254 | * Get a Gravatar URL for a specified email address. |
---|
255 | * |
---|
256 | * @param string $email The email address |
---|
257 | * @param string $size Size in pixels, defaults to 80px [ 1 - 2048 ] |
---|
258 | * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ] |
---|
259 | * @param string $r Maximum rating (inclusive) [ g | pg | r | x ] |
---|
260 | * @return String containing a URL to a gravatar image. |
---|
261 | * @source http://gravatar.com/site/implement/images/php/ |
---|
262 | */ |
---|
263 | static public function getGravatarURL($email, $size=80, $defset='mm', $rating='g') { |
---|
264 | return sprintf('https://www.gravatar.com/avatar/%s?s=%s&d=%s&r=%s', |
---|
265 | md5(strtolower(trim($email))), |
---|
266 | $size, |
---|
267 | $defset, |
---|
268 | $rating |
---|
269 | ); |
---|
270 | } |
---|
271 | } |
---|