PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/mem_simple_form/mem_simple_form.php

https://bitbucket.org/Manfre/txp-plugins
PHP | 399 lines | 304 code | 70 blank | 25 comment | 58 complexity | 0883207013a77cc4987505ecc5590a44 MD5 | raw file
  1. <?php
  2. // This is a PLUGIN TEMPLATE.
  3. // Copy this file to a new name like abc_myplugin.php. Edit the code, then
  4. // run this file at the command line to produce a plugin for distribution:
  5. // $ php abc_myplugin.php > abc_myplugin-0.1.txt
  6. // Plugin name is optional. If unset, it will be extracted from the current
  7. // file name. Uncomment and edit this line to override:
  8. $plugin['name'] = 'mem_simple_form';
  9. // 0 = Plugin help is in Textile format, no raw HTML allowed (default).
  10. // 1 = Plugin help is in raw HTML. Not recommended.
  11. # $plugin['allow_html_help'] = 1;
  12. $plugin['version'] = '0.3.2';
  13. $plugin['author'] = 'Michael Manfre';
  14. $plugin['author_uri'] = 'http://manfre.net/';
  15. $plugin['description'] = 'Store a form to a table.';
  16. // Plugin types:
  17. // 0 = regular plugin; loaded on the public web side only
  18. // 1 = admin plugin; loaded on both the public and admin side
  19. // 2 = library; loaded only when include_plugin() or require_plugin() is called
  20. $plugin['type'] = 0;
  21. if (!defined('txpinterface'))
  22. @include_once('../zem_tpl.php');
  23. if (0) {
  24. ?>
  25. # --- BEGIN PLUGIN HELP ---
  26. h1(title). mem_simple_form plugin
  27. h2(section summary). Summary
  28. p. This plugin allows for a site owner to have a form accept input and store the data in an existing table. Basic processing can be done to
  29. the data before writing to the table.
  30. p. This plugin requires mem_form.
  31. p. This plugin has MLP support.
  32. h2(section contact). Author Contact
  33. "Michael Manfre":mailto:mmanfre@gmail.com?subject=Textpattern%20mem_simple_form%20plugin
  34. "http://manfre.net":http://manfre.net
  35. h2(section license). License
  36. p. This plugin is licensed under the "GPLv2":http://www.fsf.org/licensing/licenses/info/GPLv2.html.
  37. h2(section installation). Installation
  38. p. No extra installation steps
  39. h2(section tags). Tags
  40. * "mem_simple_form":#mem_simple_form
  41. * "mem_simple_if_ps":#mem_simple_if_ps
  42. * "mem_simple_ps":#mem_simple_ps
  43. h3(tag#mem_simple_form). mem_simple_form
  44. p(tag-summary). This tag will output an HTML form. The HTML form field names must follow the pattern "@<type>_<name>@", where @<type>@ is a value from
  45. the below type list. The database table's field name must match @<name>@ exactly (case sensitive).
  46. p(tag-summary). Form Types:
  47. * now - MySQL "NOW()" function. Use with mem_form_secret or mem_form_hidden.
  48. * password - MySQL "PASSWORD()" function
  49. * oldpassword - MySQL "OLD_PASSWORD()" function
  50. * md5 - MySQL "MD5()" function
  51. * sha1 - MySQL "SHA1()" function
  52. * rand - MySQL "RAND()" function. Use with mem_form_secret or mem_form_hidden.
  53. * textile - Textile parse field
  54. * nl2br - Convert newlines to br tags
  55. * randuid - Generate a random unique id (md5 hash). Use with mem_form_secret or mem_form_hidden.
  56. * lower - Convert to lower case
  57. * upper - Convert to upper case
  58. * base64encode - Base64 encode
  59. * base64decode - Base64 decode
  60. * string - No processing
  61. * int - Field contains a numeric value
  62. *(atts) %(atts-name)table% %(atts-type)string% Name of the table to insert data on a successful form submission.
  63. *(atts) %(atts-name)id_field% %(atts-type)string% If specified, this is the name of the table field that is a PRIMARY KEY or UNIQUE INDEX. This allows updates if a record with a matching ID already exists.
  64. *(atts) %(atts-name)id_insert% %(atts-type)int% If "1", the ID field will be inserted/updated. Otherwise, the field is assumed to be auto generated by the database.
  65. *(atts) %(atts-name)ignore_fields% %(atts-type)string% A comma separated string of field names (including prefixes) that will not be written to the table. These are handy for ToS checkboxes and CAPTCHAs.
  66. *(atts) %(atts-name)form% %(atts-type)string% Name of form that contains the mem_simple_form form tags.
  67. *(atts) %(atts-name)success_form% %(atts-type)string% Name of the form that will be shown after a successful post.
  68. *(atts) %(atts-name)failure_form% %(atts-type)string% Name of the form that will be shown after a failed post.
  69. h3(tag#mem_simple_if_ps). mem_simple_if_ps
  70. p(tag-summary). Conditional tag that checks to see if a HTML field was posted, or if it has a specific value.
  71. *(atts) %(atts-name)name% %(atts-type)string% HTML field name posted with the form.
  72. *(atts) %(atts-name)equal% %(atts-type)string% Value to compare against the value of name. If not specified, tag checks to see if form posted variable HTML field name.
  73. h3(tag#mem_simple_ps). mem_simple_ps
  74. p(tag-summary). This tag will output the value of the posted HTML form field.
  75. *(atts) %(atts-name)name% %(atts-type)string% HTML field name posted with the form.
  76. # --- END PLUGIN HELP ---
  77. <?php
  78. }
  79. # --- BEGIN PLUGIN CODE ---
  80. // MLP
  81. global $mem_simple_lang;
  82. if (!is_array($mem_simple_lang))
  83. {
  84. $mem_simple_lang = array(
  85. 'table_name_required' => 'You must provide a table name as an attribute to mem_simple_form',
  86. 'form_submit_failed' => 'The form submission failed',
  87. 'no_fields_received' => 'No data submitted with form.',
  88. 'attribute_missing' => 'Required attribute {name} not provided',
  89. );
  90. }
  91. define( 'MEM_SIMPLE_PREFIX' , 'mem_self' );
  92. register_callback( 'mem_simple_enumerate_strings' , 'l10n.enumerate_strings' );
  93. function mem_simple_enumerate_strings($event , $step='' , $pre=0)
  94. {
  95. global $mem_simple_lang;
  96. $r = array (
  97. 'owner' => 'mem_simple_form', # Change to your plugin's name
  98. 'prefix' => MEM_SIMPLE_PREFIX, # Its unique string prefix
  99. 'lang' => 'en-gb', # The language of the initial strings.
  100. 'event' => 'public', # public/admin/common = which interface the strings will be loaded into
  101. 'strings' => $mem_simple_lang, # The strings themselves.
  102. );
  103. return $r;
  104. }
  105. function mem_simple_gTxt($what,$args = array())
  106. {
  107. global $mem_simple_lang, $textarray;
  108. $key = strtolower( MEM_SIMPLE_PREFIX . '-' . $what );
  109. if (isset($textarray[$key]))
  110. {
  111. $str = $textarray[$key];
  112. }
  113. else
  114. {
  115. $key = strtolower($what);
  116. if (isset($mem_simple_lang[$key]))
  117. $str = $mem_simple_lang[$key];
  118. elseif (isset($textarray[$key]))
  119. $str = $textarray[$key];
  120. else
  121. $str = $what;
  122. }
  123. if( !empty($args) )
  124. $str = strtr( $str , $args );
  125. return $str;
  126. }
  127. require_plugin('mem_form');
  128. function mem_simple_form($atts, $thing='')
  129. {
  130. $atts = lAtts(array(
  131. 'type' => 'mem_simple_form',
  132. 'table' => false,
  133. 'id_field' => false,
  134. 'id_insert' => false,
  135. 'ignore_fields' => false,
  136. 'form' => '',
  137. 'success_form' => false,
  138. 'failure_form' => false,
  139. ),$atts,0);
  140. if (empty($atts['table']))
  141. trigger_error(gTxt('attribute_required', array('{att}' => 'table')));
  142. if (!empty($atts['form'])) {
  143. $thing = fetch_form($atts['form']);
  144. unset($atts['form']);
  145. }
  146. foreach(array('table', 'id_field', 'id_insert', 'ignore_fields', 'success_form', 'failure_form') as $a) {
  147. $thing .= '<txp:mem_form_secret name="mem_simple_'.$a.'" value="'.$atts[$a].'" />';
  148. unset($atts[$a]);
  149. }
  150. return mem_form($atts, $thing);
  151. }
  152. register_callback('mem_simple_form_submitted', 'mem_form.submit');
  153. function mem_simple_form_submitted()
  154. {
  155. global $mem_form_type, $mem_form_values, $production_status;
  156. if ($mem_form_type !== 'mem_simple_form')
  157. return;
  158. $table = @$mem_form_values['mem_simple_table'];
  159. if (empty($table))
  160. {
  161. trigger_error(mem_simple_gTxt('table_name_required'));
  162. // table name required
  163. return;
  164. }
  165. $id_field = @$mem_form_values['mem_simple_id_field'];
  166. $id_insert = @$mem_form_values['mem_simple_id_insert'];
  167. $ignore_fields = @$mem_form_values['mem_simple_ignore_fields'];
  168. $ignore_fields = empty($ignore_fields) ? array() : explode(',', $ignore_fields);
  169. $ignore_fields_names = array_values($ignore_fields);
  170. $ignore_fields_names[] = 'mem_form_submit';
  171. $textile = false;
  172. $fields = array();
  173. $id = false;
  174. foreach($mem_form_values as $k=>$v)
  175. {
  176. // skip plugin config values and ignorable fields
  177. if (strncmp($k, 'mem_simple_', 11) == 0 || in_array($k, $ignore_fields_names) )
  178. {
  179. continue;
  180. }
  181. // split the type from name. int_number_value ==> int, number_value
  182. list($type, $name) = explode('_', $k, 2);
  183. if ($type == 'int')
  184. $format = "%s = %d";
  185. else
  186. {
  187. // standard string format
  188. $format = "%s = '%s'";
  189. // mysql functions
  190. $funcs = array(
  191. 'now' => "NOW()",
  192. 'password' => "PASSWORD('%s')",
  193. 'oldpassword' => "OLD_PASSWORD('%s')",
  194. 'md5' => "MD5('%s')",
  195. 'sha1' => "SHA1('%s')",
  196. 'rand' => 'RAND()',
  197. );
  198. if (array_key_exists($type, $funcs))
  199. {
  200. $format = "%s = " . $funcs[$type];
  201. }
  202. else if ($type == 'textile')
  203. {
  204. if (!$textile)
  205. {
  206. // load textile singleton
  207. include_once txpath.'/lib/classTextile.php';
  208. $textile = new Textile();
  209. }
  210. $v = $textile->TextileThis($v);
  211. }
  212. else if ($type == 'nl2br')
  213. $v = nl2br(trim($v));
  214. else if ($type == 'urltitle')
  215. $v = stripSpace($v,1);
  216. else if ($type == 'randuid')
  217. $v = md5(uniqid(rand(),true));
  218. else if ($type == 'lower')
  219. $v = strtolower($v);
  220. else if ($type == 'upper')
  221. $v = strtoupper($v);
  222. else if ($type == 'base64encode')
  223. $v = base64_encode($v);
  224. else if ($type == 'base64decode')
  225. $v = base64_decode($v);
  226. }
  227. // store the processed value so others can access
  228. $_POST[$k] = $v;
  229. $s = sprintf($format, doSlash($name), doSlash($v));
  230. if ($id_field == $name && !$id_insert)
  231. {
  232. $id = $s;
  233. // don't update id field
  234. continue;
  235. }
  236. $fields[] = $s;
  237. }
  238. if (!empty($fields))
  239. {
  240. $insert = empty($id);
  241. if ($insert)
  242. {
  243. $rs = safe_insert( doSlash($table), join(', ',$fields) );
  244. }
  245. else
  246. {
  247. $rs = safe_upsert( doSlash($table), join(', ',$fields), $id );
  248. }
  249. if ($rs)
  250. {
  251. // yay
  252. $form = @$mem_form_values['mem_simple_success_form'];
  253. if (!empty($form))
  254. {
  255. $form = @fetch_form($form);
  256. if (!empty($form))
  257. {
  258. return parse($form);
  259. }
  260. }
  261. }
  262. else
  263. {
  264. // boo
  265. if ($production_status != 'live')
  266. trigger_error('Failed to store data to table. ' . mysql_error($rs));
  267. $form = @$mem_form_values['mem_simple_failure_form'];
  268. if (!empty($form))
  269. {
  270. $form = @fetch_form($form);
  271. if (!empty($form))
  272. {
  273. return parse($form);
  274. }
  275. }
  276. return mem_simple_gTxt('form_submit_failed');
  277. }
  278. }
  279. else
  280. {
  281. return mem_simple_gTxt('no_fields_received');
  282. }
  283. }
  284. function mem_simple_ps($atts,$thing='')
  285. {
  286. extract(lAtts(array(
  287. 'name' => false,
  288. ),$atts));
  289. if (!empty($name))
  290. {
  291. $n = gps($name);
  292. if (!empty($n))
  293. return $n;
  294. }
  295. return '';
  296. }
  297. function mem_simple_if_ps($atts, $thing='')
  298. {
  299. extract(lAtts(array(
  300. 'name' => false,
  301. 'equal' => false,
  302. ),$atts));
  303. if ($name === false)
  304. trigger_error(gTxt('attribute_missing', array('{name}' => $name)));
  305. if ($equal === false)
  306. $condition = isset($_POST[$name]);
  307. else
  308. $condition = (gps('name') == $equal);
  309. $thing = EvalElse($thing, $condition);
  310. return parse($thing);
  311. }
  312. # --- END PLUGIN CODE ---
  313. ?>