BxDolForm.php 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. define('BX_DOL_FORM_METHOD_GET', 'get');
  10. define('BX_DOL_FORM_METHOD_POST', 'post');
  11. define('BX_DOL_FORM_METHOD_SPECIFIC', 'specific');
  12. define('BX_DOL_FORM_METHOD_DEFAULT', BX_DOL_FORM_METHOD_POST);
  13. define('BX_DATA_LISTS_KEY_PREFIX', '#!');
  14. define('BX_DATA_VALUES_DEFAULT', 'LKey'); ///< Use default values for data items, @see BxDolForm::getDataItems
  15. define('BX_DATA_VALUES_ADDITIONAL', 'LKey2'); ///< Use additional values for data items, @see BxDolForm::getDataItems
  16. define('BX_DATA_VALUES_ALL', 'all'); ///< Return all available info for data items, @see BxDolForm::getDataItems
  17. /**
  18. * Forms allows to display forms from data stored in DB tables, before it was possible to display forms from PHP arrays only.
  19. *
  20. *
  21. * The Form Objects have the following main advantages:
  22. * - Minimal coding is needed to create different forms
  23. * - Easy forms alterations
  24. * - Multiple representations of the same form
  25. * - Automated data inserting into database
  26. * - Automated data updating
  27. * - Automated data checking
  28. * - Automatic security checking
  29. * - Automatic spam filter
  30. *
  31. *
  32. * Forms API uses several definitions:
  33. * - Form or Form Object - record in sys_objects_form table, or instance of Form class.
  34. * - Form Display - set of some form inputs in particular order, displayed for some purpose; one form can have several displays, for example add and edit displays.
  35. * - Form Input or Form Field - form input field, like textarea, checkbox or set of radio buttons.
  36. *
  37. *
  38. * @section form_creating_object Creating the Form Object
  39. *
  40. * 1. Create Form Object, add record to sys_objects_form table:
  41. * - object - name of the Form Object, in the format: vendor prefix, underscore, module prefix, underscore, internal identifier or nothing; for example: bx_group - for group data processing, like group adding or editing.
  42. * - title - Form Object title to display in studio forms builder.
  43. * - action - url to submit form to, if url is not full and not empty, then site url is added automatically.
  44. * - form_attrs - serialized array of additional form attributes.
  45. * - submit_name - name of form field with submit button, it is used to determine if form is submitted.
  46. * - table - DB table name (for automatic saving/updating).
  47. * - key - DB table field with unique ID (for automatic updating).
  48. * - uri - DB table field with URI (for automatic URI generation, aling with uri_title).
  49. * - uri_title - DB table field with data title (for automatic URI generation, aling with uri).
  50. * - params - serialized array of additional form parameters:
  51. * - checker_helper - name of custom BxDolFormCheckerHelper class.
  52. * - csrf - array of Cross-site request forgery attack prevention parameters, for now only one boolean parameter is supported - disabled, so it can be disabled for particular form.
  53. * - active - 1 or 0, if form is inactive then it can not be used anywhere.
  54. * - override_class_name - user defined class name which is derived from BxTemplFormView.
  55. * - override_class_file - the location of the user defined class, leave it empty if class is located in system folders.
  56. *
  57. *
  58. * 2. Create Form Displays, add records to sys_form_displays table:
  59. * - display_name - name of the Form Display, in the format:
  60. * form object name, underscore, internal identifier or nothing;
  61. * for example: bx_group_add - for displaying group adding form, bx_group_edit - for displaying group editing form
  62. * - module - module name this display belongs to, it must be associated with name field in sys_modules table.
  63. * - object - form object name from sys_objects_form table this Form Display belongs to.
  64. * - title - Form Display title to display in studio forms builder.
  65. * - view_mode - display form as read-only.
  66. *
  67. *
  68. * 3. Create Form Fields, add records to sys_form_inputs table:
  69. * - object - form object name from sys_objects_form table this Form Field belongs to.
  70. * - module - module name this field belongs to.
  71. * - name - unique Form Field name in particular From Object.
  72. * - value - default value, or empty if there is no default value.
  73. * - values - possible values, for certain form field types.
  74. * - checked - 0 or 1, it determines if form field is checked, for certain form field types.
  75. * - type - form field type, for now the following types are supported:
  76. * - text - text input field.
  77. * - password - password input field.
  78. * - textarea - multiline input field.
  79. * - number - number input field.
  80. * - select - select one from all available values.
  81. * - select_multiple - select one, multiple or all items from all available values.
  82. * - switcher - on/off switcher.
  83. * - checkbox - one checkbox.
  84. * - checkbox_set - set of checkboxes.
  85. * - radio_set - set of radio buttons.
  86. * - slider - select some numeric value within the range using slider control.
  87. * - doublerange - select range values within the range using slider control.
  88. * - datepicker - date selection control.
  89. * - datetime - date/time selection control.
  90. * - captcha - image captcha.
  91. * - hidden - hidden input field.
  92. * - file - file upload input.
  93. * - button - button control.
  94. * - image - form image button.
  95. * - reset - form reset button.
  96. * - submit - form submit button.
  97. * - value - just displaying value without any crontol.
  98. * - block_header - start group of field.
  99. * - custom - custom control.
  100. * - input_set - set of other form controls.
  101. * detailed description of every type will be described below.
  102. * - caption - input title.
  103. * - info - some info to help user to input data into the field, it's better to specify format and limits here.
  104. * - required - indicate that the input is required by displaying asterisk near the field,
  105. * please note that this field don't perform any checking automatically,
  106. * since you mark field as required you need to specify checked function which will check entered value.
  107. * - collapsed - display section as collapsed by default, for block_header field type only.
  108. * - html - display visual editor of certain type, for textarea field type only.
  109. * - 0 - no visual editor, leave textarea field as it is.
  110. * - 1 - standard(default) visual editor, @see BxDolEditor.
  111. * - 2 - full visual editor, @see BxDolEditor.
  112. * - 3 - mini visual editor, @see BxDolEditor.
  113. * - attrs - serialized array of additional input attributes.
  114. * - attrs_tr - serialized array of additional attributes for the whole input row.
  115. * - attrs_wrapper - serialized array of additional attributes for input wrapper.
  116. * - checker_func - checked function, if you marked field as required in textarea field you need to point one of the following checked functions:
  117. * - Length - check value length, additional params must contain min and/or max values for checking.
  118. * - Date - check if date is entered correctly.
  119. * - DateTime - check if datetime is entered correctly.
  120. * - Preg - check value with provided regular expression in checker_params field.
  121. * - Avail - just check if value isn't 0 or empty string, additional function parameters are not used.
  122. * - Email - check if value is written in valid email format.
  123. * - Captcha - check if captcha is entered correctly, for captcha field type only.
  124. * You can inherit BxDolFormCheckerHelper class and add own checker functions, you will need to point your custom class in Form Object params array.
  125. * - checker_params - serialized array of checker_func parameters.
  126. * - checker_error - error message to show in case of checking function returns false.
  127. * - db_pass - function to pass value through before saving to database and after restoring from database (for example when date need to be converted from/to timestamp value),
  128. * available values are the following:
  129. * - Int - convert value to integer.
  130. * - Float - convert value to floating point number.
  131. * - Date,DateUtc - convert value to timestamp value before saving to database, and convert from timespamp value after restoring from database.
  132. * - DateTime,DateTimeUtc - convert value to timestamp value before saving to database, and convert from timespamp value after restoring from database.
  133. * - Xss - it warns you that this text can contain XSS vulnerabilities and you need to be extra careful with this, and always use Forms engine to output string to the browser or use bx_process_output if going to output text manually.
  134. * - XssHtml - this text cam have HTML tags, so perform XSS vulnerabilies cleaning before saving to database.
  135. * - All - do not perform any conversion and pass text as it is, be careful with this, use it only when no other function can be used, and make all necessary security checking by yourself.
  136. * - Preg - perform regular expression on the text before saving data to database, regular expression can be provided in db_params field.
  137. * - Boolean - this is used for checkboxes with 'on' value which need to be converted into boolean value.
  138. * - Set - convert set of values into bit integer before saving to database, and restore bit integer into array of values upon restoration from database, it can be used for select_multiple and checkbox_set field types.
  139. * Please note that values for this field must be 1,2,4,8,... (values of power of 2); the max number of values are 31 for 32bit hardware and 63 for 64bit hardware.
  140. * You can inherit BxDolFormCheckerHelper class and add own pass functions, you will need to point your custom class in Form Object params array.
  141. * - db_params - serialized array of db_pass parameters.
  142. * - editable - allow to edit this field from admin forms builder.
  143. * - deletable - allow to delete this field from admin forms builder.
  144. *
  145. *
  146. * 4. Add Form Fields and Form Displays associations, add records to sys_form_display_inputs table:
  147. * - display_name - name of the Form Display from sys_form_displays table.
  148. * - input_name - name of the Form Field from sys_form_inputs table.
  149. * - visible_for_levels - bit field with set of member level ids. To use member level id in bit field the level id minus 1 is used as power of 2, for example:
  150. * - user level id = 1 -> 2^(1-1) = 1
  151. * - user level id = 2 -> 2^(2-1) = 2
  152. * - user level id = 3 -> 2^(3-1) = 4
  153. * - user level id = 4 -> 2^(4-1) = 8
  154. * - active - 1 - form field displayed on form, or 0 - isn't displayed.
  155. * - order - fields are displayed in this order.
  156. *
  157. *
  158. * @section form_field_types Form Field Types
  159. *
  160. * Detailed description of Form Field Types.
  161. *
  162. * Almost all fields have the following common parameters:
  163. * - object
  164. * - name
  165. * - type
  166. * - caption
  167. * - info
  168. * - required
  169. * - attrs
  170. * - attrs_tr
  171. * - attrs_wrapper
  172. *
  173. * We will not describe above list of parameters in every type, since they work the same way for all types.
  174. *
  175. * The list below are field types with their unique parameters, which are designed especially for this field, or some parameters which work differently for the specified field type.
  176. *
  177. * text - text input field. It is displayed as regular single line text input.
  178. * Parameters:
  179. * - value - default value, or empty if there is no default value.
  180. * - values - not applicable here.
  181. * - checked - not applicable here.
  182. * - collapsed - not applicable here.
  183. * - html - not applicable here.
  184. * - checker_func
  185. * Can be used here: Length, Preg, Avail, Email
  186. * Make no sense to use it here: Date, DateTime, Captcha
  187. * - db_pass
  188. * Can be used here: Int, Float, Xss, All, Preg
  189. * Make no sense to use it here: Date, DateTime, XssHtml, Boolean, Set
  190. *
  191. * password - password input field. It is displayed as HTML input element with invisible input.
  192. * Parameters:
  193. * - value - default value, or empty if there is no default value.
  194. * - values - not applicable here.
  195. * - checked - not applicable here.
  196. * - collapsed - not applicable here.
  197. * - html - not applicable here.
  198. * - checker_func
  199. * Can be used here: Length, Preg, Avail.
  200. * Make no sense to use it here: Date, DateTime, Captcha, Email.
  201. * - db_pass
  202. * Can be used here: Xss, All.
  203. * Make no sense to use it here: Int, Float, Date, DateTime, XssHtml, Boolean, Set, Preg.
  204. *
  205. * textarea - multiline input field. It can be displayed as regular textarea field or as visual HTML editor.
  206. * Parameters:
  207. * - value - default value, or empty if there is no default value.
  208. * - values - not applicable here.
  209. * - checked - not applicable here.
  210. * - collapsed - not applicable here.
  211. * - html - use visual editor or not.
  212. * - 0 - no visual editor, leave textarea field as it is.
  213. * - 1 - standard(default) visual editor, @see BxDolEditor.
  214. * - 2 - full visual editor, @see BxDolEditor.
  215. * - 3 - mini visual editor, @see BxDolEditor.
  216. * - checker_func
  217. * Can be used here: Length, Preg, Avail
  218. * Make no sense to use it here: Email, Date, DateTime, Captcha
  219. * - db_pass
  220. * Can be used here: Int, Float, Xss, XssHtml, All, Preg
  221. * Make no sense to use it here: Date, DateTime, Boolean, Set
  222. *
  223. * number - number input field. It is displayed as HTL text input, but with limited width. Also some browsers can add additional controls to this field.
  224. * Parameters:
  225. * - value - default value, or empty if there is no default value.
  226. * - values - not applicable here.
  227. * - checked - not applicable here.
  228. * - collapsed - not applicable here.
  229. * - html - not applicable here.
  230. * - checker_func
  231. * Can be used here: Length, Preg, Avail
  232. * Make no sense to use it here: Email, Date, DateTime, Captcha
  233. * - db_pass
  234. * Can be used here: Int, Float
  235. * Make no sense to use it here: Xss, XssHtml, All, Preg, Date, DateTime, Boolean, Set
  236. *
  237. * select - select one from all available values. It is displayed as HTML combo-box.
  238. * Parameters:
  239. * - value - default value (array index of selected item from values array), or empty - if there is no default value.
  240. * - values - serialized array of available values, or reference to predefined set of values.
  241. * - checked - not applicable here.
  242. * - collapsed - not applicable here.
  243. * - html - not applicable here.
  244. * - checker_func
  245. * Can be used here: Length, Preg, Avail
  246. * Make no sense to use it here: Email, Date, DateTime, Captcha
  247. * - db_pass
  248. * Can be used here: Int, Float, Xss, All, Preg
  249. * Make no sense to use it here: Date, DateTime, XssHtml, Boolean, Set
  250. *
  251. * select_multiple - select one, multiple or all items from all available values. It is displayed as HTML multiple selection input.
  252. * Parameters:
  253. * - value - default value (bit integer of array indexes of selected items from values array), or empty - if there is no default value.
  254. * - values - serialized array of available values, or reference to predefined set of values. Array index must be power of 2. Max number of values is 31 on 32bit hardware or 63 on 64bit hardware.
  255. * - checked - not applicable here.
  256. * - collapsed - not applicable here.
  257. * - html - not applicable here.
  258. * - checker_func
  259. * Can be used here: Length, Preg, Avail
  260. * Make no sense to use it here: Email, Date, DateTime, Captcha
  261. * - db_pass
  262. * Can be used here: Int
  263. * Make no sense to use it here: Float, Xss, All, Preg, Date, DateTime, XssHtml, Boolean, Set
  264. *
  265. * switcher - on/off switcher. It is displayed as custom HTML element with own styles, but on background it works as regular HTML checkbox element.
  266. * Parameters:
  267. * - value - the value which will be submitted if switcher is on, if switcher is off - nothing is submitted.
  268. * - values - not applicable here.
  269. * - checked - if set to 1 then switcher is on by default, 0 - it is off by default.
  270. * - collapsed - not applicable here.
  271. * - html - not applicable here.
  272. * - checker_func
  273. * Can be used here: Length, Preg, Avail
  274. * Make no sense to use it here: Email, Date, DateTime, Captcha
  275. * - db_pass
  276. * Can be used here: Int, Float, Xss, All, Preg, Boolean
  277. * Make no sense to use it here: Date, DateTime, XssHtml, Set
  278. *
  279. * checkbox - one checkbox. Displayed as HTML checkbox input element.
  280. * Parameters:
  281. * - value - the value which will be submitted if checkbox is checked, if checkbox isn't checked - nothing is submitted.
  282. * - values - not applicable here.
  283. * - checked - if set to 1 then checkbox is checked by default, 0 - it is unchecked by default.
  284. * - collapsed - not applicable here.
  285. * - html - not applicable here.
  286. * - checker_func
  287. * Can be used here: Length, Preg, Avail
  288. * Make no sense to use it here: Email, Date, DateTime, Captcha
  289. * - db_pass
  290. * Can be used here: Int, Float, Xss, All, Preg, Boolean
  291. * Make no sense to use it here: Date, DateTime, XssHtml, Set
  292. *
  293. * checkbox_set - set of checkboxes. It is displayed as set of checkboxes. It is displayed in one row if number of items is equal or less than 3 or every item is displayed on new line if there is more than 3 items in the set.
  294. * Parameters:
  295. * - value - default value (bit integer of array indexes of selected items from values array), or empty - if there is no default value.
  296. * - values - serialized array of available values, or reference to predefined set of values. Array index must be power of 2. Max number of values is 31 on 32bit hardware or 63 on 64bit hardware.
  297. * - checked - not applicable here.
  298. * - collapsed - not applicable here.
  299. * - html - not applicable here.
  300. * - checker_func
  301. * Can be used here: Length, Preg, Avail
  302. * Make no sense to use it here: Email, Date, DateTime, Captcha
  303. * - db_pass
  304. * Can be used here: Int
  305. * Make no sense to use it here: Float, Xss, All, Preg, Date, DateTime, XssHtml, Boolean, Set
  306. *
  307. * radio_set - set of radio buttons. It is displayed as set of radio buttons. It is displayed in one row if number of items is equal or less than 3 or every item is displayed on new line if there is more than 3 items in the set.
  308. * Parameters:
  309. * - value - default value (array index of selected radio button from values array), or empty - if there is no default value.
  310. * - values - serialized array of available values, or reference to predefined set of values.
  311. * - checked - not applicable here.
  312. * - collapsed - not applicable here.
  313. * - html - not applicable here.
  314. * - checker_func
  315. * Can be used here: Length, Preg, Avail
  316. * Make no sense to use it here: Email, Date, DateTime, Captcha
  317. * - db_pass
  318. * Can be used here: Int, Float, Xss, All, Preg
  319. * Make no sense to use it here: Date, DateTime, XssHtml, Boolean, Set
  320. *
  321. * slider - select some numeric value within the range using slider control. It is displayed as jQuery UI HTML control, but on background it works as regular HTML text input element.
  322. * Parameters:
  323. * - value - default value in the format, or empty if there is no default value.
  324. * - values - not applicable here.
  325. * - checked - not applicable here.
  326. * - collapsed - not applicable here.
  327. * - html - not applicable here.
  328. * - attrs - the following additional attributes can be used here:
  329. * - min - minimal value, default is 0.
  330. * - max - maximal value, default is 100.
  331. * - step - value can be changed by this step only, default is 1.
  332. * - checker_func
  333. * Can be used here: Length, Avail
  334. * Make no sense to use it here: Preg, Email, Date, DateTime, Captcha
  335. * - db_pass
  336. * Can be used here: Int, Float
  337. * Make no sense to use it here: Xss, XssHtml, All, Preg, Date, DateTime, Boolean, Set
  338. *
  339. * doublerange - select range values within the range using slider control.
  340. * Parameters:
  341. * - value - default value in the format [min value]-[max value], for example 16-99, or empty if there is no default value.
  342. * - values - not applicable here.
  343. * - checked - not applicable here.
  344. * - collapsed - not applicable here.
  345. * - html - not applicable here.
  346. * - attrs - the following additional attributes can be used here:
  347. * - min - minimal value, default is 0.
  348. * - max - maximal value, default is 100.
  349. * - step - value can be changed by this step only, default is 1.
  350. * - checker_func
  351. * Can be used here: Length, Avail
  352. * Make no sense to use it here: Preg, Email, Date, DateTime, Captcha
  353. * - db_pass
  354. * Can be used here: Xss, All, Preg
  355. * Make no sense to use it here: Int, Float, XssHtml, Date, DateTime, Boolean, Set
  356. *
  357. * datepicker - date selection control. It is displayed as HTML text input control, when clicking on this input then popup with date selector control is appeared.
  358. * Parameters:
  359. * - value - default value, in the format YYYY-MMM-DD, or empty if there is no default value.
  360. * - values - not applicable here.
  361. * - checked - not applicable here.
  362. * - collapsed - not applicable here.
  363. * - html - not applicable here.
  364. * - checker_func
  365. * Can be used here: Date
  366. * Make no sense to use it here: Length, Preg, Avail, Email, DateTime, Captcha
  367. * - db_pass
  368. * Can be used here: Date, DateUtc
  369. * Make no sense to use it here: Int, Float, Xss, All, Preg, DateTime, XssHtml, Boolean, Set
  370. *
  371. * datetime - date/time selection control.
  372. * Parameters:
  373. * - value - default value, in the format YYYY-MMM-DD HH:MM:SS, or empty if there is no default value.
  374. * - values - not applicable here.
  375. * - checked - not applicable here.
  376. * - collapsed - not applicable here.
  377. * - html - not applicable here.
  378. * - checker_func
  379. * Can be used here: DateTime
  380. * Make no sense to use it here: Length, Preg, Avail, Email, Date, Captcha
  381. * - db_pass
  382. * Can be used here: DateTime, DateTimeUtc
  383. * Make no sense to use it here: Int, Float, Xss, All, Preg, Date, XssHtml, Boolean, Set
  384. *
  385. * captcha - image captcha. Displayed as image with some text along with HTML text input for entering displayed on the image text.
  386. * Parameters:
  387. * - value - not applicable here.
  388. * - values - not applicable here.
  389. * - checked - not applicable here.
  390. * - collapsed - not applicable here.
  391. * - html - not applicable here.
  392. * - checker_func
  393. * Can be used here: Captcha
  394. * Make no sense to use it here: Length, Preg, Avail, Email, Date, DateTime
  395. * - db_pass
  396. * Can be used here: Xss, All, Preg
  397. * Make no sense to use it here: Int, Float, Date, DateTime, XssHtml, Boolean, Set
  398. *
  399. * hidden - hidden input field. Displayed as hidden HTML input.
  400. * Parameters:
  401. * - value - hidden input value.
  402. * - values - not applicable here.
  403. * - checked - not applicable here.
  404. * - collapsed - not applicable here.
  405. * - html - not applicable here.
  406. * - checker_func
  407. * Can be used here: Length, Preg, Avail, Email, Date, DateTime
  408. * Make no sense to use it here: Captcha
  409. * - db_pass
  410. * Can be used here: Int, Float, Xss, All, Preg, Date, DateUtc, DateTime, DateTimeUtc, XssHtml, Boolean
  411. * Make no sense to use it here: Set
  412. *
  413. * file - file upload input. Displayed as file upload HTML input.
  414. * Parameters:
  415. * - value - not applicable here.
  416. * - values - not applicable here.
  417. * - checked - not applicable here.
  418. * - collapsed - not applicable here.
  419. * - html - not applicable here.
  420. * - checker_func
  421. * File name is passed for checking.
  422. * Can be used here: Avail, Length, Preg
  423. * Make no sense to use it here: Email, Date, DateTime, Captcha
  424. * - db_pass
  425. * File can't be stored in the database, so this field isn't applicable here.
  426. *
  427. * files - files upload input. Displayed as complex uploading HTML control.
  428. * This control is too complex to describe it using default set of database fields, you need to use custom class to display this control.
  429. *
  430. * button - button control. Displayes as HTML button element.
  431. * Parameters:
  432. * - value - translatable button caption.
  433. * - values - not applicable here.
  434. * - checked - not applicable here.
  435. * - collapsed - not applicable here.
  436. * - html - not applicable here.
  437. * - checker_func - not applicable here.
  438. * - db_pass - not applicable here.
  439. *
  440. * image - form image button. It is displayed as HTML form image input element.
  441. * Parameters:
  442. * - value - not applicable here.
  443. * - values - not applicable here.
  444. * - checked - not applicable here.
  445. * - collapsed - not applicable here.
  446. * - html - not applicable here.
  447. * - attrs - the following mandatory attribute must be specified here:
  448. * - src - image URL.
  449. * - checker_func - not applicable here.
  450. * - db_pass - not applicable here.
  451. *
  452. * reset - form reset button. Displayed as HTML form reset input button. By clicking on this button the form is reset to its default state.
  453. * Parameters:
  454. * - value - translatable button caption.
  455. * - values - not applicable here.
  456. * - checked - not applicable here.
  457. * - collapsed - not applicable here.
  458. * - html - not applicable here.
  459. * - checker_func - not applicable here.
  460. * - db_pass - not applicable here.
  461. *
  462. * submit - form submit button. Displayed as HTML form submit input button. This button have the primary button style to distinguish it from other buttons. By clicking on this button the form is submitted.
  463. * Parameters:
  464. * - value - translatable button caption.
  465. * - values - not applicable here.
  466. * - checked - not applicable here.
  467. * - collapsed - not applicable here.
  468. * - html - not applicable here.
  469. * - checker_func - not applicable here.
  470. * - db_pass - not applicable here.
  471. *
  472. * value - just displaying value without any control.
  473. * Parameters:
  474. * - value - the value to display.
  475. * - values - not applicable here.
  476. * - checked - not applicable here.
  477. * - collapsed - not applicable here.
  478. * - html - not applicable here.
  479. * - checker_func - not applicable here.
  480. * - db_pass - not applicable here.
  481. *
  482. * block_header - start group of fields. Displayed as form fields divider with caption - then it can be collapsible or without caption - then it is just divider without any functionality.
  483. * Parameters:
  484. * - value - not applicable here.
  485. * - values - not applicable here.
  486. * - checked - not applicable here.
  487. * - collapsed - display group of field collapsed by default, 1 - the group is collapsed, 0 - expanded (default value).
  488. * - html - not applicable here.
  489. * - checker_func - not applicable here.
  490. * - db_pass - not applicable here.
  491. *
  492. * custom - custom control. You need custom class to display this control, so the exact used values are determined by particular realisation.
  493. *
  494. * input_set - set of other form controls.
  495. * Parameters:
  496. * - value - not applicable here.
  497. * - values - comma separated list of field names (by name field) of fields to display here.
  498. * - checked - not applicable here.
  499. * - collapsed - not applicable here.
  500. * - html - not applicable here.
  501. * - checker_func - not applicable here.
  502. * - db_pass - not applicable here.
  503. *
  504. *
  505. * @section form_using_own_class Using own class for custom behavior
  506. *
  507. * It is possible to provide own class for displaying and processing the form.
  508. * To do this you need to point it in override_class_name and override_class_file fields in sys_objects_form table.
  509. * Your custom class must be inherited from BxTemplFormView class or its descendants.
  510. *
  511. *
  512. * @section form_display_custom_control Displaying custom field control
  513. *
  514. * It is possible to leave form field with default caption and override only the form field control.
  515. * To override some field you need to define the following function:
  516. * @code
  517. * protected function genCustomInput[field name] ($aInput).
  518. * @endcode
  519. * Where [field name] is form field name.
  520. * For example:
  521. *
  522. * @code
  523. * protected function genCustomInputCustom ($aInput) {
  524. * return
  525. * 'r: <input type="text" size="2" value="'.(isset($aInput['value'][0]) ? $aInput['value'][0] : '').'" name="'.$aInput['name'].'[]" />' .
  526. * 'g: <input type="text" size="2" value="'.(isset($aInput['value'][1]) ? $aInput['value'][1] : '').'" name="'.$aInput['name'].'[]" />' .
  527. * 'b: <input type="text" size="2" value="'.(isset($aInput['value'][2]) ? $aInput['value'][2] : '').'" name="'.$aInput['name'].'[]" />';
  528. * }
  529. * @endcode
  530. *
  531. *
  532. * @section form_display_custom_row Displaying custom field row
  533. *
  534. * Form row consists of caption and control, by default it is displayed with default design and functionality.
  535. * If you need to display some field with custom header and control you need to declare the following function:
  536. * @code
  537. * protected function genCustomRow[field name] ($aInput).
  538. * @endcode
  539. * Where [field name] is form field name.
  540. *
  541. *
  542. * @section example Example of usage
  543. *
  544. * Printing the form for adding new record to the database:
  545. *
  546. * @code
  547. * $oForm = BxDolForm::getObjectInstance('sample_form_objects', 'sample_form_objects_add'); // get form instance for specified form object and display
  548. * if (!$oForm)
  549. * die('"sample_form_objects_add" form object or "sample_form_objects_add" display is not defined');
  550. * $oForm->initChecker(); // init form checker witout any data - adding new record
  551. * if ($oForm->isSubmittedAndValid())
  552. * echo 'inserted id: ' . $oForm->insert (); // add new record to the database
  553. * echo $oForm->getCode(); // display form
  554. * @endcode
  555. *
  556. * Printing the form for editing existing record in the database:
  557. *
  558. * @code
  559. * // $iEditId - ID of edited row, for example from _GET parameter
  560. * $oDb = BxDolDb::getInstance();
  561. * $sQuery = $oDb->prepare("SELECT * FROM `sample_input_types` WHERE id = ?", $iEditId);
  562. * $aRecord = $oDb->getRow();
  563. * if (!$aRecord)
  564. * die("$iEditId record wasn't found.");
  565. *
  566. * $oForm = BxDolForm::getObjectInstance('sample_form_objects', 'sample_form_objects_edit'); // get form instance for specified form object and display
  567. * if (!$oForm)
  568. * die('"sample_form_objects_edit" form object or "sample_form_objects_edit" display is not defined');
  569. * $oForm->initChecker($aRecord); // init form checker with edited data
  570. * if ($oForm->isSubmittedAndValid())
  571. * echo 'updated: ' . $oForm->update ($iEditId); // update database
  572. * echo $oForm->getCode(); // display form
  573. * @endcode
  574. *
  575. * Example of custom form class and custom checking helper class:
  576. *
  577. * @code
  578. * class BxSampleForm extends BxTemplFormView {
  579. *
  580. * public function __construct ($aInfo, $oTemplate = false) {
  581. * parent::__construct ($aInfo, $oTemplate);
  582. * }
  583. *
  584. *
  585. * // display input with 'custom' name
  586. * protected function genCustomInputCustom ($aInput) {
  587. * return
  588. * 'r: <input type="text" size="2" value="'.(isset($aInput['value'][0]) ? $aInput['value'][0] : '').'" name="'.$aInput['name'].'[]" />' .
  589. * 'g: <input type="text" size="2" value="'.(isset($aInput['value'][1]) ? $aInput['value'][1] : '').'" name="'.$aInput['name'].'[]" />' .
  590. * 'b: <input type="text" size="2" value="'.(isset($aInput['value'][2]) ? $aInput['value'][2] : '').'" name="'.$aInput['name'].'[]" />';
  591. * }
  592. *
  593. * }
  594. *
  595. * class BxSampleFormCheckerHelper extends BxDolFormCheckerHelper {
  596. *
  597. * protected $_sDiv = ',';
  598. *
  599. * // prepare RBG values to save to the DB
  600. * function passRgb ($s) {
  601. * if (!is_array($s))
  602. * return false;
  603. *
  604. * $sRet = '';
  605. * foreach ($s as $k => $v)
  606. * $sRet .= (int)trim($v) . $this->_sDiv;
  607. *
  608. * return trim($sRet, $this->_sDiv);
  609. * }
  610. *
  611. * // prepare RGB values to output to the screen
  612. * function displayRgb ($s) {
  613. * return explode($this->_sDiv, $s);
  614. * }
  615. * }
  616. * @endcode
  617. *
  618. * The recommended way is to define forms in database, if it is impossible for some reasons you can init form object from array, there is an example:
  619. *
  620. * @code
  621. * $aForm = array(
  622. * 'form_attrs' => array(
  623. * 'name' => 'form_my',
  624. * 'method' => 'post',
  625. * ),
  626. *
  627. * 'params' => array (
  628. * 'db' => array(
  629. * 'table' => 'table_name', // table name
  630. * 'key' => 'ID', // key field name
  631. * 'uri' => 'EntryUri', // uri field name
  632. * 'uri_title' => 'Title', // title field to generate uri from
  633. * 'submit_name' => 'submit_form', // some filed name with non empty value to determine if the for was submitted,
  634. * in most cases it is submit button name
  635. * ),
  636. * 'csrf' => array(
  637. * 'disable' => true, //if it wasn't set or has some other value then CSRF checking is enabled for current form, take a look at sys_security_form_token_enable to disable CSRF checking completely.
  638. * )
  639. * ),
  640. *
  641. * 'inputs' => array(
  642. *
  643. * 'Title' => array(
  644. * 'type' => 'text',
  645. * 'name' => 'Title', // the same as key and database field name
  646. * 'caption' => 'Some caption',
  647. * 'required' => true,
  648. *
  649. * // checker params
  650. * 'checker' => array (
  651. * 'func' => 'length', // see BxDolFormCheckerHelper class for all check* functions
  652. * 'params' => array(3,100),
  653. * 'error' => 'length must be from 3 to 100 characters',
  654. * ),
  655. * // database params
  656. * 'db' => array (
  657. * 'pass' => 'Xss', // do XSS clear before getting this value, see BxDolFormCheckerHelper class for all pass* functions
  658. * ),
  659. * ),
  660. *
  661. * 'Description' => array(
  662. * 'type' => 'textarea',
  663. * 'name' => 'Description', // the same as key and database field name
  664. * 'caption' => 'Some caption',
  665. * 'required' => true,
  666. *
  667. * // checker params
  668. * 'checker' => array (
  669. * 'func' => 'length',
  670. * 'error' => 'enter at least 3 characters',
  671. * 'params' => array(3,64000),
  672. * ),
  673. * 'db' => array (
  674. * 'pass' => 'XssHtml', // do XSS clear, but keep HTML before getting this value
  675. * ),
  676. * ),
  677. * );
  678. * @endcode
  679. *
  680. * Using of above array:
  681. *
  682. * @code
  683. * $oForm = new BxTemplFormView ($aForm);
  684. * $oForm->initChecker();
  685. *
  686. * if ($oForm->isSubmittedAndValid ()) {
  687. *
  688. * // add additional vars to database, in this case creation date field is added
  689. * $aValsAdd = array (
  690. * 'Date' => time(),
  691. * );
  692. *
  693. * echo 'insert last id: ' . $oForm->insert ($aValsAdd); // insert validated data to database
  694. *
  695. * } else {
  696. *
  697. * echo $oForm->getCode (); // show form
  698. *
  699. * }
  700. *
  701. * @endcode
  702. *
  703. */
  704. class BxDolForm extends BxDol implements iBxDolReplaceable
  705. {
  706. static $TYPES_SKIP = array('files' => 1, 'location' => 1);
  707. static $TYPES_CHECKBOX = array('checkbox' => 1, 'switcher' => 1);
  708. static $TYPES_TEXT = array('text' => 1, 'textarea' => 1);
  709. static $TYPES_FILE = array('file' => 1);
  710. static $FUNC_SKIP_DOMAIN_CHECK = array('email' => 1, 'emails' => 1, 'emailexist' => 1, 'emailuniq' => 1, 'emailexistorempty' => 1, 'hostdomain' => 1, 'hostdomainchat' => 1, 'emailorempty' => 1);
  711. static $FUNC_SKIP_MACROS_CHECK = array();
  712. static $LOCATION_INDEXES = array ('lat', 'lng', 'country', 'state', 'city', 'zip', 'street', 'street_number');
  713. protected $_aMarkers = array ();
  714. protected $oTemplate;
  715. protected $_isValid = true;
  716. protected $_sChecker;
  717. protected $_sCheckerHelper;
  718. protected $_aSpecificValues;
  719. public $aFormAttrs; ///< form html element attributes
  720. public $aInputs; ///< form inputs
  721. public $aParams; ///< additional form parameters
  722. public $id; ///< Form element id
  723. protected $_aFieldsCheckForSpam = array(); ///< additional fields names to check for spam(profanity filter), now only fields with 'textarea' and 'text' are checked for spam, 'textarea' fields are checked for spam and filter for profanity, while 'text' fields are filtetered for profanity only
  724. protected $_iAuthorId;
  725. protected $_sAuthorKey; ///< array key to get author ID from Values array provided in BxDolForm::initChecker.
  726. protected $_sPrivacyObjectView;
  727. protected $_sPrivacyGroupDefault;
  728. public function __construct ($aInfo, $oTemplate)
  729. {
  730. parent::__construct();
  731. if ($oTemplate)
  732. $this->oTemplate = $oTemplate;
  733. else
  734. $this->oTemplate = BxDolTemplate::getInstance();
  735. $this->aFormAttrs = isset($aInfo['form_attrs']) ? $aInfo['form_attrs'] : array();
  736. $this->aInputs = isset($aInfo['inputs']) ? $aInfo['inputs'] : array();
  737. $this->aParams = isset($aInfo['params']) ? $aInfo['params'] : array();
  738. // get form element id
  739. $this->id = $this->aFormAttrs['id'] = (!empty($this->aFormAttrs['id']) ? $this->aFormAttrs['id'] : (!empty($this->aFormAttrs['name']) ? $this->aFormAttrs['name'] : 'form_advanced'));
  740. // set default method
  741. if (!isset($this->aFormAttrs['method']))
  742. $this->aFormAttrs['method'] = BX_DOL_FORM_METHOD_DEFAULT;
  743. // set default action
  744. if (!isset($this->aFormAttrs['action']))
  745. $this->aFormAttrs['action'] = '';
  746. $this->_sChecker = isset($this->aParams['checker']) ? $this->aParams['checker'] : 'BxDolFormChecker';
  747. $this->_sCheckerHelper = isset($this->aParams['checker_helper']) ? $this->aParams['checker_helper'] : '';
  748. $this->_sAuthorKey = 'author';
  749. $this->_sPrivacyObjectView = 'sys_form_inputs_allow_view_to';
  750. $this->_sPrivacyGroupDefault = BX_DOL_PG_ALL;
  751. }
  752. /**
  753. * Get form object instance by object name
  754. * @param $sObject object name
  755. * @return object instance or false on error
  756. */
  757. static public function getObjectInstance($sObject, $sDisplayName, $oTemplate = false, $sParam = '')
  758. {
  759. $sKey = 'BxDolForm!'.$sObject.'!'.$sDisplayName.'!'.$sParam;
  760. if (isset($GLOBALS['bxDolClasses'][$sKey]))
  761. return $GLOBALS['bxDolClasses'][$sKey];
  762. $aObject = BxDolFormQuery::getFormArray($sObject, $sDisplayName);
  763. if (!$aObject || !is_array($aObject))
  764. return false;
  765. $sClass = 'BxTemplFormView';
  766. if (!empty($aObject['override_class_name'])) {
  767. $sClass = $aObject['override_class_name'];
  768. if (!empty($aObject['override_class_file']))
  769. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  770. }
  771. $o = new $sClass($aObject, $oTemplate);
  772. return ($GLOBALS['bxDolClasses'][$sKey] = $o);
  773. }
  774. /**
  775. * Get data items array
  776. * @param $sKey data items identifier
  777. * @param $isUseForSet convert data items keys to use in set fields, make it power of 2 (1,2,4,8,16,etc).
  778. * @param $sUseValues use default(BX_DATA_VALUES_DEFAULT) or additional(BX_DATA_VALUES_ADDITIONAL) value titles, if additinal value title is missing default title is used
  779. * @return data items array
  780. */
  781. public static function getDataItems($sKey, $isUseForSet = false, $sUseValues = BX_DATA_VALUES_DEFAULT)
  782. {
  783. return BxDolFormQuery::getDataItems($sKey, $isUseForSet, $sUseValues);
  784. }
  785. function initChecker ($aValues = array (), $aSpecificValues = array())
  786. {
  787. $this->_aSpecificValues = $aSpecificValues;
  788. $oChecker = new $this->_sChecker($this->_sCheckerHelper);
  789. $oChecker->setFormMethod($this->aFormAttrs['method'], $aSpecificValues);
  790. $oChecker->setFormParams($this->aParams);
  791. $oChecker->setFieldsCheckForSpam($this->_aFieldsCheckForSpam);
  792. // init form with default values
  793. $aValuesDef = array ();
  794. foreach ($this->aInputs as $k => $a) {
  795. if (!isset($a['value']) || !isset($a['db']['pass']) || isset(self::$TYPES_CHECKBOX[$a['type']]) || isset(self::$TYPES_SKIP[$a['type']]))
  796. continue;
  797. $aValuesDef[$k] = $a['value'];
  798. }
  799. $oChecker->fillWithValues($this->aInputs, $aValuesDef);
  800. // init form with provided values
  801. if ($aValues)
  802. $oChecker->fillWithValues($this->aInputs, $aValues);
  803. // init author from provided values if it's available
  804. if (isset($aValues[$this->_sAuthorKey]))
  805. $this->_iAuthorId = (int)$aValues[$this->_sAuthorKey];
  806. if ($this->isSubmitted ()) {
  807. // init form with submitted data, overwrite prevously declared values
  808. $oChecker->enableFormCsrfChecking(isset($this->aParams['csrf']['disable']) && $this->aParams['csrf']['disable'] === true ? false : true);
  809. $this->_isValid = $oChecker->check($this->aInputs, $aValues);
  810. if (!$this->_initCheckerNestedForms ())
  811. $this->_isValid = false;
  812. }
  813. }
  814. function getKeyValuesPair ()
  815. {
  816. $aRet = array ();
  817. foreach ($this->aInputs as $k => $a) {
  818. if (!isset($a['value']) || isset(self::$TYPES_CHECKBOX[$a['type']]) || isset(self::$TYPES_SKIP[$a['type']]))
  819. continue;
  820. $aRet[$k] = $a['value'];
  821. }
  822. return $aRet;
  823. }
  824. function insert ($aValsToAdd = array(), $isIgnore = false)
  825. {
  826. $oChecker = new $this->_sChecker($this->_sCheckerHelper);
  827. $oChecker->setFormMethod($this->aFormAttrs['method'], $this->_aSpecificValues);
  828. $sSql = $oChecker->dbInsert($this->aParams['db'], $this->aInputs, $aValsToAdd, $isIgnore);
  829. if (!$sSql)
  830. return false;
  831. $oDb = BxDolDb::getInstance();
  832. if ($oDb->query($sSql))
  833. return $oDb->lastId();
  834. return false;
  835. }
  836. function update ($val, $aValsToAdd = array(), &$aTrackTextFieldsChanges = null)
  837. {
  838. $oChecker = new $this->_sChecker($this->_sCheckerHelper);
  839. $oChecker->setFormMethod($this->aFormAttrs['method'], $this->_aSpecificValues);
  840. $sSql = $oChecker->dbUpdate($val, $this->aParams['db'], $this->aInputs, $aValsToAdd, $aTrackTextFieldsChanges);
  841. if (!$sSql)
  842. return false;
  843. return BxDolDb::getInstance()->query($sSql);
  844. }
  845. function delete ($val)
  846. {
  847. $oChecker = new $this->_sChecker($this->_sCheckerHelper);
  848. $oChecker->setFormMethod($this->aFormAttrs['method'], $this->_aSpecificValues);
  849. $sSql = $oChecker->dbDelete($val, $this->aParams['db'], $this->aInputs);
  850. if (!$sSql)
  851. return false;
  852. return BxDolDb::getInstance()->query($sSql);
  853. }
  854. function generateUri ()
  855. {
  856. $f = &$this->aParams['db'];
  857. $sUri = $this->getCleanValue ($f['uri_title']);
  858. return uriGenerate($sUri, $f['table'], $f['uri']);
  859. }
  860. function getCleanValue ($sName)
  861. {
  862. $oChecker = new $this->_sChecker($this->_sCheckerHelper);
  863. $oChecker->setFormMethod($this->aFormAttrs['method'], $this->_aSpecificValues);
  864. $a = isset($this->aInputs[$sName]) ? $this->aInputs[$sName] : false;
  865. if ($a && isset($a['db']['pass']))
  866. return $oChecker->get ($a['name'], $a['db']['pass'], isset($a['db']['params']) && $a['db']['params'] ? $a['db']['params'] : array());
  867. else
  868. return $oChecker->get ($sName);
  869. }
  870. function isSubmitted ()
  871. {
  872. $aSubmitName = $this->aParams['db']['submit_name'];
  873. if(!is_array($aSubmitName))
  874. $aSubmitName = array($aSubmitName);
  875. foreach($aSubmitName as $sSubmitName)
  876. if(BxDolForm::getSubmittedValue($sSubmitName, $this->aFormAttrs['method'], $this->_aSpecificValues))
  877. return true;
  878. return false;
  879. }
  880. function getId ()
  881. {
  882. return $this->id;
  883. }
  884. function setId ($sId)
  885. {
  886. $this->id = $sId;
  887. $this->aFormAttrs['id'] = $sId;
  888. }
  889. function setName($sName)
  890. {
  891. $this->aFormAttrs['name'] = $sName;
  892. }
  893. function setValid ($isValid)
  894. {
  895. $this->_isValid = $isValid;
  896. }
  897. function isValid ()
  898. {
  899. return $this->_isValid;
  900. }
  901. function isSubmittedAndValid ()
  902. {
  903. return ($this->isSubmitted() && $this->isValid());
  904. }
  905. function getSpecificValues()
  906. {
  907. return $this->_aSpecificValues;
  908. }
  909. function getAuthorId()
  910. {
  911. return $this->_iAuthorId;
  912. }
  913. function setAuthorId($iAuthorId)
  914. {
  915. $this->_iAuthorId = (int)$iAuthorId;
  916. $this->aParams['params']['author_id'] = $this->_iAuthorId;
  917. }
  918. public static function getSubmittedValue($sKey, $sMethod, &$aSpecificValues = false)
  919. {
  920. $aData = array();
  921. if($sMethod == BX_DOL_FORM_METHOD_GET) {
  922. $aData = &$_GET;
  923. } else if($sMethod == BX_DOL_FORM_METHOD_POST) {
  924. $aData = &$_POST;
  925. } else if($sMethod == BX_DOL_FORM_METHOD_SPECIFIC) {
  926. $aData = &$aSpecificValues;
  927. }
  928. return isset($aData[$sKey]) ? $aData[$sKey] : false;
  929. }
  930. public static function setSubmittedValue($sKey, $mixedValue, $sMethod, &$aSpecificValues = false)
  931. {
  932. $aData = array();
  933. if($sMethod == BX_DOL_FORM_METHOD_GET) {
  934. $aData = &$_GET;
  935. } else if($sMethod == BX_DOL_FORM_METHOD_POST) {
  936. $aData = &$_POST;
  937. } else if($sMethod == BX_DOL_FORM_METHOD_SPECIFIC) {
  938. $aData = &$aSpecificValues;
  939. }
  940. return $aData[$sKey] = $mixedValue;
  941. }
  942. /**
  943. * Check if field exists
  944. * @param $sName field name
  945. * @param $bCheckAllFields true - check all fields; false - all fields except: password, captcha, hidden, file, button, image, reset, submit, block_header, input_set
  946. * @return true if field exists or false otherwise
  947. */
  948. public function isFieldExist($sName, $bCheckAllFields = false)
  949. {
  950. if (!isset($this->aInputs[$sName]))
  951. return false;
  952. return $bCheckAllFields ? true : !in_array($this->aInputs[$sName]['type'], array('password', 'captcha', 'hidden', 'button', 'reset', 'submit', 'block_header', 'input_set', 'location'));
  953. }
  954. // Static Methods related to CSRF Tocken
  955. public static function genCsrfToken($bReturn = false)
  956. {
  957. // TODO: remove
  958. }
  959. public static function getCsrfToken()
  960. {
  961. if (getParam('sys_security_form_token_enable') != 'on')
  962. return false;
  963. if (!($oKeys = BxDolKey::getInstance()))
  964. return false;
  965. return $oKeys->getNewKey (false, (int)getParam('sys_security_form_token_lifetime'));
  966. }
  967. public static function isCsrfTokenValid($s)
  968. {
  969. if (getParam('sys_security_form_token_enable') != 'on')
  970. return true;
  971. if (!($oKeys = BxDolKey::getInstance()))
  972. return true;
  973. if ($oKeys->isKeyExists($s)) {
  974. $oKeys->removeKey($s);
  975. return true;
  976. }
  977. return false;
  978. }
  979. function _initCheckerNestedForms ()
  980. {
  981. $isValid = true;
  982. // process nested forms
  983. foreach ($this->aInputs as $sKey => $aInput) {
  984. if (!isset($aInput['ghost_template']))
  985. continue;
  986. if (!(is_array($aInput['ghost_template']) && isset($aInput['ghost_template']['inputs'])) && !(is_object($aInput['ghost_template']) && $aInput['ghost_template'] instanceof BxDolFormNested))
  987. continue;
  988. $sName = $aInput['name'];
  989. $aIds = $this->getSubmittedValue($sName, $this->aFormAttrs['method']);
  990. if (!$aIds)
  991. continue;
  992. $aNestedForms = array ();
  993. foreach ($aIds as $i => $iFileId) {
  994. // create separate form instance for each file
  995. $oFormNested = false;
  996. if (is_object($aInput['ghost_template'])) {
  997. $oFormNested = clone($aInput['ghost_template']);
  998. } else {
  999. $oFormNested = new BxDolFormNested($aInput['name'], $aInput['ghost_template'], $this->aParams['db']['submit_name'], $this->oTemplate);
  1000. }
  1001. if ($iFileId && 0 != $iFileId)
  1002. $aNestedForms[$iFileId] = $oFormNested;
  1003. else
  1004. $aNestedForms[] = $oFormNested;
  1005. // collect nested form values
  1006. $aSpecificValues = array ();
  1007. if (isset($this->aParams['db']['submit_name']))
  1008. $aSpecificValues = array ($this->aParams['db']['submit_name'] => 1);
  1009. foreach ($oFormNested->aInputs as $r) {
  1010. $sName = str_replace('[]', '', $r['name']);
  1011. $aValue = $this->getSubmittedValue($sName, $this->aFormAttrs['method']);
  1012. $aSpecificValues[$sName] = $aValue[$i];
  1013. }
  1014. $oFormNested->initChecker(array(), $aSpecificValues);
  1015. // if nested form in invalid - then the whole worm is failed
  1016. if (!$oFormNested->isValid ())
  1017. $isValid = false;
  1018. }
  1019. if ($aNestedForms)
  1020. $this->aInputs[$sKey]['ghost_template'] = $aNestedForms;
  1021. }
  1022. return $isValid;
  1023. }
  1024. /**
  1025. * Check if form field is visible.
  1026. * @param $aInput form field array
  1027. * @return boolean
  1028. */
  1029. static public function isVisible ($aInput)
  1030. {
  1031. return isset($aInput['visible_for_levels']) ? BxDolAcl::getInstance()->isMemberLevelInSet($aInput['visible_for_levels']) : true;
  1032. }
  1033. protected function _genMethodName ($s)
  1034. {
  1035. return bx_gen_method_name($s);
  1036. }
  1037. /**
  1038. * Add replace markers. Curently markers are replaced in action, form_attrs fields.
  1039. * @param $a array of markers as key => value
  1040. * @return true on success or false on error
  1041. */
  1042. public function addMarkers ($a)
  1043. {
  1044. if (empty($a) || !is_array($a))
  1045. return false;
  1046. $this->_aMarkers = array_merge ($this->_aMarkers, $a);
  1047. return true;
  1048. }
  1049. /**
  1050. * Replace provided markers in form array
  1051. * @param $a form description array
  1052. * @return array where markes are replaced with real values
  1053. */
  1054. protected function _replaceMarkers ($a)
  1055. {
  1056. return bx_replace_markers($a, $this->_aMarkers);
  1057. }
  1058. public function getFormErrors ()
  1059. {
  1060. $s = '';
  1061. foreach ($this->aInputs as $k => $a) {
  1062. if (isset($this->aInputs[$k]['error']) && $this->aInputs[$k]['error'])
  1063. $s .= $k . ': ' . $this->aInputs[$k]['error'] . " \n";
  1064. }
  1065. return $s;
  1066. }
  1067. protected function _getPrivacyIcon($mixedPrivacy)
  1068. {
  1069. switch($mixedPrivacy) {
  1070. case BX_DOL_PG_MEONLY:
  1071. $sResult = 'lock';
  1072. break;
  1073. case BX_DOL_PG_ALL:
  1074. $sResult = 'globe';
  1075. break;
  1076. default:
  1077. $sResult = 'user';
  1078. break;
  1079. }
  1080. return $sResult;
  1081. }
  1082. protected function _getPrivacyGroup($sPrivacyObject, $iInputId, $iAuthorId = false)
  1083. {
  1084. if(!$iAuthorId)
  1085. $iAuthorId = bx_get_logged_profile_id();
  1086. $mixedPrivacyGroup = BxDolFormQuery::getInputPrivacy($iInputId, $iAuthorId, BxDolPrivacy::getFieldName($sPrivacyObject));
  1087. if(empty($mixedPrivacyGroup))
  1088. $mixedPrivacyGroup = $this->_sPrivacyGroupDefault;
  1089. return $mixedPrivacyGroup;
  1090. }
  1091. }
  1092. class BxDolFormChecker
  1093. {
  1094. protected $_oChecker;
  1095. protected $_sFormMethod;
  1096. protected $_aFormParams;
  1097. protected $_bFormCsrfChecking;
  1098. protected $_aSpecificValues;
  1099. protected $_aFieldsCheckForSpam;
  1100. function __construct ($sHelper = '')
  1101. {
  1102. $this->_sFormMethod = BX_DOL_FORM_METHOD_GET;
  1103. $this->_bFormCsrfChecking = true;
  1104. $sCheckerName = !empty($sHelper) ? $sHelper : 'BxDolFormCheckerHelper';
  1105. $this->_oChecker = new $sCheckerName();
  1106. }
  1107. function setFormMethod($sMethod, $aSpecificValues = array())
  1108. {
  1109. $this->_sFormMethod = $sMethod;
  1110. $this->_aSpecificValues = $aSpecificValues;
  1111. }
  1112. function setFormParams($aParams)
  1113. {
  1114. $this->_aFormParams = $aParams;
  1115. }
  1116. function setFieldsCheckForSpam($a)
  1117. {
  1118. $this->_aFieldsCheckForSpam = $a;
  1119. }
  1120. function enableFormCsrfChecking($bFormCsrfChecking)
  1121. {
  1122. $this->_bFormCsrfChecking = $bFormCsrfChecking;
  1123. }
  1124. // check function
  1125. function check (&$aInputs, $aValues = array())
  1126. {
  1127. $oChecker = $this->_oChecker;
  1128. $iErrors = 0;
  1129. $sSubmitName = false;
  1130. foreach ($aInputs as $k => $a) {
  1131. if (isset($a['visible_for_levels']) && !BxDolForm::isVisible($a))
  1132. continue;
  1133. if (empty($a['name']) || 'submit' == $a['type'] || 'reset' == $a['type'] || 'button' == $a['type'] || 'value' == $a['type']) {
  1134. if (isset($a['type']) && 'submit' == $a['type'])
  1135. $sSubmitName = $k;
  1136. continue;
  1137. }
  1138. if ('input_set' == $a['type'])
  1139. foreach ($a as $r)
  1140. if (isset($r['type']) && 'submit' == $r['type'])
  1141. $sSubmitName = $k;
  1142. $a['name'] = str_replace('[]', '', $a['name']);
  1143. $sMethodGetSubmittedValue = 'getSubmittedValue' . bx_gen_method_name($a['name']);
  1144. if(method_exists($this, $sMethodGetSubmittedValue))
  1145. $val = $this->$sMethodGetSubmittedValue($a['name'], $this->_sFormMethod, $this->_aSpecificValues);
  1146. else
  1147. $val = BxDolForm::getSubmittedValue($a['name'], $this->_sFormMethod, $this->_aSpecificValues);
  1148. if (isset(BxDolForm::$TYPES_FILE[$a['type']]))
  1149. $val = isset($_FILES[$a['name']]['name']) ? $_FILES[$a['name']]['name'] : '';
  1150. // check for unique
  1151. if(isset($aInputs[$k]['unique']) && $aInputs[$k]['unique'] && !empty($this->_aFormParams['db']['key']) && !empty($this->_aFormParams['db']['table'])) {
  1152. $sKey = $this->_aFormParams['db']['key'];
  1153. $sTable = $this->_aFormParams['db']['table'];
  1154. $sError = _t('_sys_form_err_not_unique_value');
  1155. if(!empty($aValues[$sKey])) {
  1156. $sValDb = BxDolFormQuery::fieldGetValue($sTable, $aInputs[$k]['name'], $sKey, $aValues[$sKey]);
  1157. if($val != $sValDb && !BxDolFormQuery::fieldCheckUnique($sTable, $aInputs[$k]['name'], $val)) {
  1158. ++$iErrors;
  1159. $aInputs[$k]['error'] = $sError;
  1160. }
  1161. }
  1162. else if(!BxDolFormQuery::fieldCheckUnique($sTable, $aInputs[$k]['name'], $val)) {
  1163. ++$iErrors;
  1164. $aInputs[$k]['error'] = $sError;
  1165. }
  1166. }
  1167. // check for links in text fields
  1168. $sCheckerFunc = isset($a['checker']['func']) ? strtolower($a['checker']['func']) : '';
  1169. if (
  1170. !isset(BxDolForm::$FUNC_SKIP_DOMAIN_CHECK[$sCheckerFunc]) &&
  1171. (!isset($a['skip_domain_check']) || false == $a['skip_domain_check']) &&
  1172. isset(BxDolForm::$TYPES_TEXT[$a['type']]) &&
  1173. bx_is_url_in_content($val) &&
  1174. !isAdmin())
  1175. {
  1176. $aCheck = checkActionModule(bx_get_logged_profile_id(), 'post links', 'system');
  1177. if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED) {
  1178. ++$iErrors;
  1179. $aInputs[$k]['error'] = $aCheck[CHECK_ACTION_MESSAGE];
  1180. }
  1181. else {
  1182. checkActionModule(bx_get_logged_profile_id(), 'post links', 'system', true);
  1183. }
  1184. }
  1185. // check for macros in text fields
  1186. $sCheckerFunc = isset($a['checker']['func']) ? strtolower($a['checker']['func']) : '';
  1187. if (
  1188. !isset(BxDolForm::$FUNC_SKIP_MACROS_CHECK[$sCheckerFunc]) &&
  1189. (!isset($a['skip_macros_check']) || false == $a['skip_macros_check']) &&
  1190. isset(BxDolForm::$TYPES_TEXT[$a['type']]) &&
  1191. bx_is_macros_in_content($val) &&
  1192. !isAdmin())
  1193. {
  1194. $aCheck = checkActionModule(bx_get_logged_profile_id(), 'use macros', 'system');
  1195. if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED) {
  1196. ++$iErrors;
  1197. $aInputs[$k]['error'] = $aCheck[CHECK_ACTION_MESSAGE];
  1198. }
  1199. else {
  1200. checkActionModule(bx_get_logged_profile_id(), 'use macros', 'system', true);
  1201. }
  1202. }
  1203. if (!isset ($a['checker'])) {
  1204. if (isset(BxDolForm::$TYPES_CHECKBOX[$a['type']]))
  1205. $aInputs[$k]['checked'] = (isset($aInputs[$k]['value']) && $aInputs[$k]['value'] == $val);
  1206. elseif (!isset(BxDolForm::$TYPES_FILE[$a['type']]) && !isset(BxDolForm::$TYPES_SKIP[$a['type']]))
  1207. $aInputs[$k]['value'] = bx_process_input($val);
  1208. continue;
  1209. }
  1210. $sCheckFunction = array($oChecker, 'check' . bx_gen_method_name($a['checker']['func']));
  1211. if (is_callable($sCheckFunction))
  1212. $bool = call_user_func_array ($sCheckFunction, !empty($a['checker']['params']) ? array_merge(array($val), $a['checker']['params']) : array ($val));
  1213. else
  1214. $bool = true;
  1215. if (is_string($bool)) {
  1216. ++$iErrors;
  1217. $aInputs[$k]['error'] = $bool;
  1218. } elseif (!$bool) {
  1219. ++$iErrors;
  1220. if (isset($a['checker']['error']))
  1221. $aInputs[$k]['error'] = $a['checker']['error'];
  1222. }
  1223. if (isset(BxDolForm::$TYPES_CHECKBOX[$a['type']]))
  1224. $aInputs[$k]['checked'] = ($aInputs[$k]['value'] == $val);
  1225. elseif (!isset(BxDolForm::$TYPES_FILE[$a['type']]) && !isset(BxDolForm::$TYPES_SKIP[$a['type']]))
  1226. $aInputs[$k]['value'] = bx_process_input($val);
  1227. }
  1228. // check CSRF token if it's needed.
  1229. if (getParam('sys_security_form_token_enable') == 'on' && $this->_bFormCsrfChecking === true) {
  1230. $mixedCsrfTokenUsr = BxDolForm::getSubmittedValue('csrf_token', $this->_sFormMethod, $this->_aSpecificValues);
  1231. unset($aInputs['csrf_token']);
  1232. if ($mixedCsrfTokenUsr === false || !BxDolForm::isCsrfTokenValid($mixedCsrfTokenUsr)) {
  1233. $aInputs[$sSubmitName]['error'] = _t('_sys_txt_form_submission_error_csrf_expired');
  1234. return false;
  1235. }
  1236. }
  1237. // check for spam
  1238. if (!$iErrors) {
  1239. foreach ($aInputs as $k => $a) {
  1240. if (!isset($a['name']))
  1241. continue;
  1242. $a['name'] = str_replace('[]', '', $a['name']);
  1243. if ($a['type'] != 'textarea' && $a['type'] != 'text' && !in_array($a['name'], $this->_aFieldsCheckForSpam))
  1244. continue;
  1245. $val = BxDolForm::getSubmittedValue($a['name'], $this->_sFormMethod, $this->_aSpecificValues);
  1246. if (!$val)
  1247. continue;
  1248. if (!$oChecker->checkIsSpam($val, $a['type'])){
  1249. BxDolForm::setSubmittedValue($a['name'], $val, $this->_sFormMethod, $this->_aSpecificValues);
  1250. continue;
  1251. }
  1252. ++$iErrors;
  1253. $sErr = _t('_sys_spam_detected');
  1254. if (BxDolRequest::serviceExists('bx_contact', 'get_contact_page_url') && ($sUrl = BxDolService::call('bx_contact', 'get_contact_page_url')))
  1255. $sErr = _t('_sys_spam_detected_contact', $sUrl);
  1256. $aInputs[$k]['error'] = $sErr;
  1257. }
  1258. }
  1259. // add error message near submit button
  1260. if ($iErrors && $sSubmitName)
  1261. $aInputs[$sSubmitName]['error'] = _t('_sys_txt_form_submission_error');
  1262. return $iErrors ? false : true;
  1263. }
  1264. // get clean value from GET/POST
  1265. function get ($sName, $sPass = 'Xss', $aParams = array())
  1266. {
  1267. if (!$sPass)
  1268. $sPass = 'Xss';
  1269. $this->_oChecker;
  1270. $val = BxDolForm::getSubmittedValue($sName, $this->_sFormMethod, $this->_aSpecificValues);
  1271. return call_user_func_array (array($this->_oChecker, 'pass'.ucfirst($sPass)), $aParams ? array_merge(array($val), $aParams) : array ($val));
  1272. }
  1273. // db functions
  1274. function serializeDbValues (&$aInputs, &$aValsToAdd, &$aTrackTextFieldsChanges = null, $aUnset = null)
  1275. {
  1276. $aValsToUpdate = array();
  1277. if (null !== $aTrackTextFieldsChanges && isset($aTrackTextFieldsChanges['data']))
  1278. $aTrackTextFieldsChanges['changed_fields'] = array();
  1279. // get values from form description array
  1280. foreach ($aInputs as $k => $a) {
  1281. if (!isset ($a['db']) || !BxDolForm::isVisible($a)) continue;
  1282. $sKey = str_replace('[]', '', $a['name']);
  1283. $valClean = $this->get ($sKey, $a['db']['pass'], !empty($a['db']['params']) ? $a['db']['params'] : array());
  1284. $aValsToUpdate[$sKey] = $valClean;
  1285. $aInputs[$k]['db']['value'] = $valClean;
  1286. if (null !== $aTrackTextFieldsChanges && isset(BxDolForm::$TYPES_TEXT[$aInputs[$k]['type']]) && isset($aTrackTextFieldsChanges['data'][$a['name']]) && $aTrackTextFieldsChanges['data'][$a['name']] != $valClean)
  1287. $aTrackTextFieldsChanges['changed_fields'][] = $a['name'];
  1288. }
  1289. // get values which are provided manually
  1290. foreach ($aValsToAdd as $k => $val) {
  1291. $aValsToUpdate[$k] = $val;
  1292. }
  1293. // don't update id field for update statement
  1294. if ($aUnset) {
  1295. foreach ($aUnset as $sKey) {
  1296. if (isset($aValsToUpdate[$sKey]))
  1297. unset($aValsToUpdate[$sKey]);
  1298. }
  1299. }
  1300. // build SQL query part
  1301. return BxDolDb::getInstance()->arrayToSQL($aValsToUpdate);
  1302. }
  1303. function dbInsert (&$aDb, &$aInputs, $aValsToAdd = array(), $isIgnore = false)
  1304. {
  1305. if (!$aDb['table'])
  1306. return '';
  1307. $sFields = $this->serializeDbValues ($aInputs, $aValsToAdd);
  1308. if (!$sFields)
  1309. return '';
  1310. return "INSERT " . ($isIgnore ? 'IGNORE' : '') . " INTO `{$aDb['table']}` SET $sFields";
  1311. }
  1312. function dbUpdate ($val, &$aDb, &$aInputs, $aValsToAdd = array(), &$aTrackTextFieldsChanges = null)
  1313. {
  1314. if (!$aDb['table'] || !$aDb['key'])
  1315. return '';
  1316. $oDb = BxDolDb::getInstance();
  1317. if (null !== $aTrackTextFieldsChanges && !isset($aTrackTextFieldsChanges['data'])) {
  1318. // get row values to compare old and new values
  1319. $sQuery = $oDb->prepare("SELECT * FROM `{$aDb['table']}` WHERE `{$aDb['key']}` = ?", $val);
  1320. $aTrackTextFieldsChanges['data'] = $oDb->getRow($sQuery);
  1321. }
  1322. $sFields = $this->serializeDbValues ($aInputs, $aValsToAdd, $aTrackTextFieldsChanges, array($aDb['key']));
  1323. if (!$sFields)
  1324. return '';
  1325. return $oDb->prepare("UPDATE `{$aDb['table']}` SET $sFields WHERE `{$aDb['key']}` = ?", $val);
  1326. }
  1327. function dbDelete ($val, &$aDb, &$aInputs)
  1328. {
  1329. if (!$aDb['table'] || !$aDb['key'])
  1330. return '';
  1331. $oDb = BxDolDb::getInstance();
  1332. return $oDb->prepare("DELETE FROM `{$aDb['table']}` WHERE `{$aDb['key']}` = ?", $val);
  1333. }
  1334. function fillWithValues (&$aInputs, &$aValues)
  1335. {
  1336. foreach ($aInputs as $k => $a) {
  1337. if (!isset($aValues[$k]) || isset(BxDolForm::$TYPES_SKIP[$aInputs[$k]['type']]))
  1338. continue;
  1339. if (isset(BxDolForm::$TYPES_CHECKBOX[$aInputs[$k]['type']])) {
  1340. $aInputs[$k]['checked'] = isset($aInputs[$k]['value']) ? ($aInputs[$k]['value'] == $aValues[$k]) : false;
  1341. } else {
  1342. $sMethod = 'display' . (isset($a['db']['pass']) ? ucfirst($a['db']['pass']) : 'Undefined');
  1343. if (method_exists($this->_oChecker, $sMethod))
  1344. $aInputs[$k]['value'] = call_user_func_array (array($this->_oChecker, $sMethod), !empty($a['db']['params']) ? array_merge(array($aValues[$k]), $a['db']['params']) : array ($aValues[$k]));
  1345. else
  1346. $aInputs[$k]['value'] = $aValues[$k];
  1347. }
  1348. }
  1349. }
  1350. }
  1351. class BxDolFormCheckerHelper
  1352. {
  1353. // check functions - check values for limits or patterns
  1354. static public function checkLength ($s, $iLenMin, $iLenMax)
  1355. {
  1356. if (is_array($s)) {
  1357. foreach ($s as $k => $v) {
  1358. $iLen = get_mb_len ($v);
  1359. if ($iLen < $iLenMin || $iLen > $iLenMax)
  1360. return false;
  1361. }
  1362. return true;
  1363. }
  1364. $iLen = get_mb_len ($s);
  1365. return $iLen >= $iLenMin && $iLen <= $iLenMax ? true : false;
  1366. }
  1367. static public function checkDate ($s)
  1368. {
  1369. return self::checkPreg ($s, '#^\d+\-\d+\-\d+$#');
  1370. }
  1371. static public function checkDateRange ($s, $iMin, $iMax, $bRequired = false)
  1372. {
  1373. if (!$bRequired && (empty($s) || '0000-00-00' == $s))
  1374. return true;
  1375. if (self::checkPreg ($s, '#^\d+\-\d+\-\d+$#')){
  1376. $dDate = new DateTime($s);
  1377. $dDateMax = new DateTime("-" . $iMin . " years");
  1378. $dDateMin = new DateTime("-" . $iMax . " years");
  1379. if ($dDate > $dDateMin && $dDate < $dDateMax){
  1380. return true;
  1381. }
  1382. }
  1383. return false;
  1384. }
  1385. static public function checkDateTime ($s)
  1386. {
  1387. // remove unnecessary opera's input value;
  1388. $s = str_replace('T', ' ', $s);
  1389. $s = str_replace('Z', ':00', $s);
  1390. return self::checkPreg ($s, '#^\d+\-\d+\-\d+[\sT]{1}\d+:\d+[:\d+]$#');
  1391. }
  1392. static public function checkPreg ($s, $r)
  1393. {
  1394. if (is_array($s)) {
  1395. foreach ($s as $k => $v)
  1396. if (!preg_match($r, $v))
  1397. return false;
  1398. return true;
  1399. }
  1400. return preg_match($r, $s) ? true : false;
  1401. }
  1402. static public function checkAvail ($s)
  1403. {
  1404. if (is_array($s)) {
  1405. return !self::_isEmptyArray($s);
  1406. }
  1407. return $s ? true : false;
  1408. }
  1409. static public function checkLocation($s, $sName, $sMethod = BX_DOL_FORM_METHOD_DEFAULT, $bAll = false)
  1410. {
  1411. if(!self::checkAvail($s))
  1412. return false;
  1413. $aIndexes = BxDolForm::$LOCATION_INDEXES;
  1414. foreach($aIndexes as $sIndex) {
  1415. $sValue = BxDolForm::getSubmittedValue($sName . '_' . $sIndex, $sMethod);
  1416. $bValue = self::checkAvail($sValue);
  1417. if($bAll && !$bValue)
  1418. return false;
  1419. if(!$bAll && $bValue)
  1420. return true;
  1421. }
  1422. return $bAll ? true : false;
  1423. }
  1424. static public function checkEmailOrEmpty($s)
  1425. {
  1426. if (empty($s))
  1427. return true;
  1428. return self::checkEmail($s);
  1429. }
  1430. static public function checkEmail($s)
  1431. {
  1432. if (false === strpos($s, '@')) // simple check
  1433. return false;
  1434. if (!preg_match("/^[\pL\pNd]/u", $s)) // must start with letter or number
  1435. return false;
  1436. if (!preg_match("/@[\pL\pNd\.\-]+$/u", $s)) // validate domain
  1437. return false;
  1438. $s = str_replace(array('@', '.', '-', '+', '_'), '', $s); // allowed symbols
  1439. if (preg_match("/[^\pL^\pNd]/u", $s)) // check for undesirable chars
  1440. return false;
  1441. return true;
  1442. // return self::checkPreg ($s, "/(([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?/");
  1443. }
  1444. static public function checkCaptcha($s)
  1445. {
  1446. $oCaptcha = BxDolCaptcha::getObjectInstance();
  1447. if (!$oCaptcha)
  1448. return true;
  1449. return $oCaptcha->check ();
  1450. }
  1451. static public function checkIsSpam(&$val, $sType = 'textarea')
  1452. {
  1453. $bSpam = false;
  1454. bx_alert('system', 'check_spam', 0, getLoggedId(), array('is_spam' => &$bSpam, 'content' => &$val, 'where' => 'form', 'type' => $sType));
  1455. return $bSpam;
  1456. }
  1457. // pass functions, prepare values to insert to database
  1458. static public function passInt ($s)
  1459. {
  1460. if (is_array($s)) {
  1461. $a = array ();
  1462. foreach ($s as $k => $v) {
  1463. $a[$k] = (int)trim($v);
  1464. }
  1465. return $a;
  1466. }
  1467. return (int)$s;
  1468. }
  1469. static public function passFloat ($s)
  1470. {
  1471. if (is_array($s)) {
  1472. $a = array ();
  1473. foreach ($s as $k => $v) {
  1474. $a[$k] = (float)$v;
  1475. }
  1476. return $a;
  1477. }
  1478. return (float)$s;
  1479. }
  1480. static public function passDate ($s)
  1481. {
  1482. if (is_array($s)) {
  1483. $a = array ();
  1484. foreach ($s as $k => $v) {
  1485. $a[$k] = self::_passDate ($v, BX_DATA_DATE);
  1486. }
  1487. return $a;
  1488. }
  1489. return self::_passDate ($s, BX_DATA_DATE);
  1490. }
  1491. static public function passDateTs ($s)
  1492. {
  1493. if (is_array($s)) {
  1494. $a = array ();
  1495. foreach ($s as $k => $v) {
  1496. $a[$k] = self::_passDate ($v, BX_DATA_DATE_TS);
  1497. }
  1498. return $a;
  1499. }
  1500. return self::_passDate ($s, BX_DATA_DATE_TS);
  1501. }
  1502. static public function passDateUtc ($s)
  1503. {
  1504. if (is_array($s)) {
  1505. $a = array ();
  1506. foreach ($s as $k => $v) {
  1507. $a[$k] = self::_passDate ($v, BX_DATA_DATE_TS_UTC);
  1508. }
  1509. return $a;
  1510. }
  1511. return self::_passDate ($s, BX_DATA_DATE_TS_UTC);
  1512. }
  1513. static public function passDateTime ($s)
  1514. {
  1515. if (is_array($s)) {
  1516. $a = array ();
  1517. foreach ($s as $k => $v) {
  1518. $a[$k] = self::_passDate ($v, BX_DATA_DATETIME);
  1519. }
  1520. return $a;
  1521. }
  1522. return self::_passDate ($s, BX_DATA_DATETIME);
  1523. }
  1524. static public function passDateTimeTs ($s)
  1525. {
  1526. if (is_array($s)) {
  1527. $a = array ();
  1528. foreach ($s as $k => $v) {
  1529. $a[$k] = self::_passDate ($v, BX_DATA_DATETIME_TS);
  1530. }
  1531. return $a;
  1532. }
  1533. return self::_passDate ($s, BX_DATA_DATETIME_TS);
  1534. }
  1535. static public function passDateTimeUtc ($s)
  1536. {
  1537. if (is_array($s)) {
  1538. $a = array ();
  1539. foreach ($s as $k => $v) {
  1540. $a[$k] = self::_passDate ($v, BX_DATA_DATETIME_TS_UTC);
  1541. }
  1542. return $a;
  1543. }
  1544. return self::_passDate ($s, BX_DATA_DATETIME_TS_UTC);
  1545. }
  1546. static public function _passDate ($s, $iFormat)
  1547. {
  1548. $iRet = bx_process_input ($s, $iFormat);
  1549. if (false === $iRet)
  1550. return 0;
  1551. return $iRet;
  1552. }
  1553. static public function passXss ($s)
  1554. {
  1555. if (is_array($s)) {
  1556. $a = array ();
  1557. foreach ($s as $k => $v) {
  1558. $a[$k] = bx_process_input ($v, BX_DATA_TEXT); // "strip tags" option was here in 7.0
  1559. }
  1560. return $a;
  1561. }
  1562. return bx_process_input ($s, BX_DATA_TEXT); // "strip tags" option was here in 7.0
  1563. }
  1564. static public function passXssMultiline ($s)
  1565. {
  1566. if (is_array($s)) {
  1567. $a = array ();
  1568. foreach ($s as $k => $v) {
  1569. $a[$k] = bx_process_input ($v, BX_DATA_TEXT_MULTILINE);
  1570. }
  1571. return $a;
  1572. }
  1573. return bx_process_input ($s, BX_DATA_TEXT_MULTILINE);
  1574. }
  1575. static public function passXssHtml ($s)
  1576. {
  1577. if (is_array($s)) {
  1578. $a = array ();
  1579. foreach ($s as $k => $v) {
  1580. $a[$k] = bx_process_input ($v, BX_DATA_HTML);
  1581. }
  1582. return $a;
  1583. }
  1584. return bx_process_input ($s, BX_DATA_HTML);
  1585. }
  1586. static public function passAll ($s)
  1587. {
  1588. if (is_array($s)) {
  1589. $a = array ();
  1590. foreach ($s as $k => $v) {
  1591. $a[$k] = bx_process_input ($v);
  1592. }
  1593. return $a;
  1594. }
  1595. return bx_process_input ($s);
  1596. }
  1597. static public function passPreg ($s, $r)
  1598. {
  1599. if (is_array($s)) {
  1600. $a = array ();
  1601. foreach ($s as $k => $v) {
  1602. $a[$k] = self::_passPreg ($v, $r);
  1603. }
  1604. return $a;
  1605. }
  1606. return self::_passPreg($s, $r);
  1607. }
  1608. static public function _passPreg ($s, $r)
  1609. {
  1610. if (preg_match ($r, $s, $m)) {
  1611. return $m[1];
  1612. }
  1613. return '';
  1614. }
  1615. static public function passBoolean ($s)
  1616. {
  1617. if (is_array($s)) {
  1618. $a = array ();
  1619. foreach ($s as $k => $v) {
  1620. $a[$k] = $v == 'on' ? true : false;
  1621. }
  1622. return $a;
  1623. }
  1624. return $s == 'on' ? true : false;
  1625. }
  1626. static public function passSet ($s)
  1627. {
  1628. if (is_array($s)) {
  1629. $i = 0;
  1630. foreach ($s as $v)
  1631. $i |= pow (2, $v - 1);
  1632. return $i;
  1633. }
  1634. return (int)$s;
  1635. }
  1636. // display functions, prepare values to output to the screen
  1637. static public function displayDate ($i)
  1638. {
  1639. return bx_process_output ($i, BX_DATA_DATE);
  1640. }
  1641. static public function displayDateTs ($i)
  1642. {
  1643. return bx_process_output ($i, BX_DATA_DATE_TS);
  1644. }
  1645. static public function displayDateUtc ($i)
  1646. {
  1647. return bx_process_output ($i, BX_DATA_DATE_TS_UTC);
  1648. }
  1649. static public function displayDateTime ($i)
  1650. {
  1651. return bx_process_output ($i, BX_DATA_DATETIME);
  1652. }
  1653. static public function displayDateTimeTs ($i)
  1654. {
  1655. return bx_process_output ($i, BX_DATA_DATETIME_TS);
  1656. }
  1657. static public function displayDateTimeUtc ($i)
  1658. {
  1659. return bx_process_output ($i, BX_DATA_DATETIME_TS_UTC);
  1660. }
  1661. static public function displaySet ($i)
  1662. {
  1663. $i = (int)$i;
  1664. $bit = 1;
  1665. $bitpos = 1;
  1666. $a = array();
  1667. while ($bit < BX_DOL_INT_MAX && $bit > 0) {
  1668. if ($bit & $i)
  1669. $a[] = $bitpos;
  1670. $bit <<= 1;
  1671. $bitpos++;
  1672. }
  1673. return $a;
  1674. }
  1675. // for internal usage only
  1676. static public function _isEmptyArray ($a)
  1677. {
  1678. return bx_is_empty_array($a);
  1679. }
  1680. static public function _isFullArray ($a)
  1681. {
  1682. return bx_is_full_array($a);
  1683. }
  1684. }
  1685. /** @} */