BxDolForm.php 75 KB

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