ASP Classic blog framework - BrainOrdure
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

854 řádky
27KB

  1. <%
  2. Function QuoteValue(val)
  3. if IsWrappedInSingleQuotes(val) then
  4. QuoteValue = val
  5. Exit Function
  6. end if
  7. Select Case VarType(val)
  8. Case vbString
  9. QuoteValue = "'" & Replace(val, "'", "''") & "'"
  10. Case vbDate
  11. if conn.Provider = "Microsoft.Jet.OLEDB.4.0" or conn.Provider = "Microsoft.ACE.OLEDB.12.0" then
  12. QuoteValue = "#" & FormatDateTime(val, 0) & "#"
  13. else
  14. ' SQL Server
  15. QuoteValue = "'" & FormatDateTime(val, 0) & "'"
  16. end if
  17. Case vbNull, vbEmpty
  18. QuoteValue = "Null"
  19. Case vbBoolean
  20. ' Return boolean values without quotes
  21. QuoteValue = "'" & CStr(val) & "'"
  22. Case Else
  23. If IsNumeric(val) Then
  24. QuoteValue = CLng(val)
  25. Else
  26. QuoteValue = CStr(val)
  27. End If
  28. End Select
  29. End Function
  30. Public Function GetAppSetting(key)
  31. Dim cacheKey, xml, nodes, node, i
  32. cacheKey = "AppSetting_" & key
  33. ' Check Application cache first for performance
  34. If Not IsEmpty(Application(cacheKey)) Then
  35. GetAppSetting = Application(cacheKey)
  36. Exit Function
  37. End If
  38. ' Load from web.config only if not cached
  39. Set xml = Server.CreateObject("Microsoft.XMLDOM")
  40. xml.Load(Server.MapPath("web.config"))
  41. Set nodes = xml.selectNodes("//appSettings/add")
  42. For i = 0 To nodes.Length - 1
  43. Set node = nodes.Item(i)
  44. If node.getAttribute("key") = key Then
  45. GetAppSetting = node.getAttribute("value")
  46. ' Cache the value for subsequent requests
  47. Application.Lock
  48. Application(cacheKey) = GetAppSetting
  49. Application.Unlock
  50. Exit Function
  51. End If
  52. Next
  53. GetAppSetting = "nothing"
  54. End Function
  55. Public Function GetEnvironmentValue(name)
  56. Dim shell, env, value, scopes, scope
  57. value = ""
  58. On Error Resume Next
  59. Set shell = Server.CreateObject("WScript.Shell")
  60. If Err.Number = 0 Then
  61. scopes = Array("PROCESS", "SYSTEM", "USER")
  62. For Each scope In scopes
  63. Set env = shell.Environment(scope)
  64. If Err.Number = 0 Then
  65. value = env(name)
  66. If Len(Trim(CStr(value))) > 0 Then Exit For
  67. End If
  68. Err.Clear
  69. Next
  70. Else
  71. Err.Clear
  72. End If
  73. On Error GoTo 0
  74. GetEnvironmentValue = Trim(CStr(value))
  75. End Function
  76. Public Function GetSecureSetting(key, envName)
  77. Dim value, envValue
  78. value = Trim(CStr(GetAppSetting(key)))
  79. If Len(value) > 0 And LCase(value) <> "nothing" Then
  80. GetSecureSetting = value
  81. Exit Function
  82. End If
  83. envValue = Trim(CStr(GetEnvironmentValue(envName)))
  84. If Len(envValue) > 0 Then
  85. On Error Resume Next
  86. UpdateAppSetting key, envValue
  87. Err.Clear
  88. On Error GoTo 0
  89. GetSecureSetting = envValue
  90. Exit Function
  91. End If
  92. GetSecureSetting = ""
  93. End Function
  94. Public Function GetGenerationPromptTemplate()
  95. Dim prompt
  96. prompt = Trim(CStr(GetAppSetting("AbacusGenerationPrompt")))
  97. If Len(prompt) = 0 Or LCase(prompt) = "nothing" Then
  98. prompt = "You write clear, engaging blog post content for a classic ASP blog. Return only valid JSON with two keys: summary and body. Summary must be 1 to 2 sentences. Body must be 3 to 5 short paragraphs separated by blank lines. Do not use markdown fences, bullets, or code blocks." & vbCrLf & vbCrLf & _
  99. "Create blog content for this post title: {TITLE}" & vbCrLf & _
  100. "Existing summary: {SUMMARY}" & vbCrLf & _
  101. "Existing body: {BODY}" & vbCrLf & _
  102. "Keep the title unchanged. Make the content readable and helpful for a general audience." & vbCrLf & _
  103. "Also include an image_prompt field in the generated JSON output that describes a magazine-style feature image."
  104. End If
  105. GetGenerationPromptTemplate = prompt
  106. End Function
  107. Public Function BuildGenerationPrompt(ByRef post)
  108. Dim template
  109. template = GetGenerationPromptTemplate()
  110. template = Replace(template, "{TITLE}", SafePromptText(post.Title))
  111. template = Replace(template, "{SUMMARY}", SafePromptText(post.Summary))
  112. template = Replace(template, "{BODY}", SafePromptText(post.Body))
  113. BuildGenerationPrompt = template
  114. End Function
  115. Public Function SafePromptText(ByVal value)
  116. If IsNull(value) Or IsEmpty(value) Then
  117. SafePromptText = ""
  118. Else
  119. SafePromptText = CStr(value)
  120. End If
  121. End Function
  122. Public Function UpdateAppSetting(key, value)
  123. Dim xml, nodes, node, appSettings, found
  124. Set xml = Server.CreateObject("Microsoft.XMLDOM")
  125. xml.async = False
  126. xml.preserveWhiteSpace = True
  127. xml.Load Server.MapPath("web.config")
  128. If xml.parseError.errorCode <> 0 Then
  129. Err.Raise 1, "UpdateAppSetting", "Unable to load web.config: " & xml.parseError.reason
  130. End If
  131. Set nodes = xml.selectNodes("//appSettings/add[@key='" & key & "']")
  132. found = False
  133. If Not (nodes Is Nothing) Then
  134. If nodes.Length > 0 Then
  135. Set node = nodes.Item(0)
  136. node.setAttribute "value", value
  137. found = True
  138. End If
  139. End If
  140. If Not found Then
  141. Set appSettings = xml.selectSingleNode("//appSettings")
  142. If appSettings Is Nothing Then
  143. Err.Raise 1, "UpdateAppSetting", "<appSettings> section not found in web.config."
  144. End If
  145. Set node = xml.createElement("add")
  146. node.setAttribute "key", key
  147. node.setAttribute "value", value
  148. appSettings.appendChild node
  149. End If
  150. xml.Save Server.MapPath("web.config")
  151. Application.Contents.Remove("AppSetting_" & key)
  152. UpdateAppSetting = True
  153. End Function
  154. Public Sub ShowServerVariables
  155. Dim varName, htmlTable
  156. htmlTable = "<table border='1' cellspacing='0' cellpadding='5'>"
  157. htmlTable = htmlTable & "<thead><tr><th>Variable Name</th><th>Value</th></tr></thead><tbody>"
  158. ' Loop through all server variables
  159. For Each varName In Request.ServerVariables
  160. htmlTable = htmlTable & "<tr>"
  161. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(varName) & "</td>"
  162. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(Request.ServerVariables(varName)) & "</td>"
  163. htmlTable = htmlTable & "</tr>"
  164. Next
  165. htmlTable = htmlTable & "</tbody></table>"
  166. ' Output the HTML table
  167. Response.Write(htmlTable)
  168. End Sub
  169. '------------------------------------------------------------------------------
  170. ' Utility: IIf Function for VBScript
  171. ' Usage: result = IIf(condition, trueValue, falseValue)
  172. '------------------------------------------------------------------------------
  173. Function IIf(condition, trueValue, falseValue)
  174. On Error Resume Next
  175. If CBool(condition) Then
  176. IIf = trueValue
  177. Else
  178. IIf = falseValue
  179. End If
  180. If Err.Number <> 0 Then
  181. ' Optional: handle or log error in conversion/evaluation
  182. Err.Clear
  183. End If
  184. On Error GoTo 0
  185. End Function
  186. '-----------------------------
  187. ' Utility: Generic Error Reporter
  188. '-----------------------------
  189. Public Sub ErrorCheck(context)
  190. If Err.Number <> 0 Then
  191. Dim errHtml
  192. errHtml = "<div style='padding:10px; border:2px solid red; background:#fdd; font-family:Verdana; font-size:12px;'>"
  193. errHtml = errHtml & "<strong>Error occurred" & IIf(Not IsEmpty(context) And context <> "", ": " & context, "") & "</strong><br />"
  194. errHtml = errHtml & "<em>Time:</em> " & Now() & "<br />"
  195. errHtml = errHtml & "<em>Number:</em> " & Err.Number & "<br />"
  196. errHtml = errHtml & "<em>Description:</em> " & Server.HTMLEncode(Err.Description) & "<br />"
  197. If Len(Err.Source) > 0 Then
  198. errHtml = errHtml & "<em>Source:</em> " & Server.HTMLEncode(Err.Source) & "<br />"
  199. End If
  200. errHtml = errHtml & "</div>"
  201. Response.Write errHtml
  202. Err.Clear
  203. End If
  204. End Sub
  205. '------------------------------------------------------------------------------
  206. ' Utility: TrimQueryParams
  207. ' Removes everything from the first "?" or "&" onward.
  208. ' Usage:
  209. ' CleanPath = TrimQueryParams(rawPath)
  210. '------------------------------------------------------------------------------
  211. Function TrimQueryParams(rawPath)
  212. Dim posQ, posA, cutPos
  213. ' find the first occurrences of "?" and "&"
  214. posQ = InStr(rawPath, "?")
  215. posA = InStr(rawPath, "&")
  216. ' determine the earliest cut position (>0)
  217. If posQ > 0 And posA > 0 Then
  218. cutPos = IIf(posQ < posA, posQ, posA)
  219. ElseIf posQ > 0 Then
  220. cutPos = posQ
  221. ElseIf posA > 0 Then
  222. cutPos = posA
  223. Else
  224. cutPos = 0
  225. End If
  226. ' if found, return up to just before that char
  227. If cutPos > 0 Then
  228. TrimQueryParams = Left(rawPath, cutPos - 1)
  229. Else
  230. TrimQueryParams = rawPath
  231. End If
  232. End Function
  233. Function DecodeUrlPath(ByVal rawPath)
  234. Dim current, previous
  235. current = Trim(CStr(rawPath))
  236. On Error Resume Next
  237. Do
  238. previous = current
  239. current = Server.URLDecode(current)
  240. If Err.Number <> 0 Then
  241. Err.Clear
  242. current = previous
  243. Exit Do
  244. End If
  245. Loop While current <> previous
  246. On Error GoTo 0
  247. current = Replace(current, "%252D", "-")
  248. current = Replace(current, "%252d", "-")
  249. current = Replace(current, "%2D", "-")
  250. current = Replace(current, "%2d", "-")
  251. current = Replace(current, "%25", "%")
  252. DecodeUrlPath = current
  253. End Function
  254. Sub Destroy(o)
  255. if isobject(o) then
  256. if not o is nothing then
  257. on error resume next
  258. o.close
  259. on error goto 0
  260. set o = nothing
  261. end if
  262. end if
  263. End Sub
  264. 'prepends indents
  265. Private Sub puti(v)
  266. put Spaces(m_indent) & v
  267. End Sub
  268. Sub put(v)
  269. Select Case typename(v)
  270. Case "LinkedList_Class" : response.write join(v.TO_Array, ", ")
  271. Case "DynamicArray_Class" : response.write JoinList(v)
  272. Case "Variant()" : response.write join(v, ", ")
  273. Case else : response.write v
  274. End Select
  275. End Sub
  276. Sub put_
  277. put "<br>"
  278. End Sub
  279. Sub putl(v)
  280. put v
  281. put_
  282. End Sub
  283. '---------------------------------------------------------------------------------------------------------------------
  284. 'Wrapper for Server.HTMLEncode() -- makes it easier on the eyes when reading the HTML code
  285. Function H(s)
  286. If Not IsEmpty(s) and Not IsNull(s) then
  287. H = Server.HTMLEncode(s)
  288. Else
  289. H = ""
  290. End If
  291. End Function
  292. Function RenderPostBody(ByVal body)
  293. Dim raw
  294. If IsNull(body) Or IsEmpty(body) Then
  295. RenderPostBody = ""
  296. Exit Function
  297. End If
  298. raw = CStr(body)
  299. If IsHtmlPostBody(raw) Then
  300. RenderPostBody = raw
  301. Else
  302. raw = Server.HTMLEncode(raw)
  303. raw = Replace(raw, vbCrLf, "<br>")
  304. raw = Replace(raw, vbCr, "<br>")
  305. raw = Replace(raw, vbLf, "<br>")
  306. RenderPostBody = raw
  307. End If
  308. End Function
  309. Function IsHtmlPostBody(ByVal text)
  310. Dim lowerText
  311. lowerText = LCase(CStr(text))
  312. IsHtmlPostBody = _
  313. (InStr(lowerText, "<p") > 0) Or _
  314. (InStr(lowerText, "<div") > 0) Or _
  315. (InStr(lowerText, "<br") > 0) Or _
  316. (InStr(lowerText, "<strong") > 0) Or _
  317. (InStr(lowerText, "<em") > 0) Or _
  318. (InStr(lowerText, "<ul") > 0) Or _
  319. (InStr(lowerText, "<ol") > 0) Or _
  320. (InStr(lowerText, "<li") > 0) Or _
  321. (InStr(lowerText, "<a ") > 0) Or _
  322. (InStr(lowerText, "<img") > 0) Or _
  323. (InStr(lowerText, "<blockquote") > 0) Or _
  324. (InStr(lowerText, "<h1") > 0) Or _
  325. (InStr(lowerText, "<h2") > 0) Or _
  326. (InStr(lowerText, "<h3") > 0) Or _
  327. (InStr(lowerText, "<h4") > 0) Or _
  328. (InStr(lowerText, "<h5") > 0) Or _
  329. (InStr(lowerText, "<h6") > 0) Or _
  330. (InStr(lowerText, "<code") > 0) Or _
  331. (InStr(lowerText, "<pre") > 0)
  332. End Function
  333. Function AiImageUrl(ByVal prompt)
  334. AiImageUrl = "https://pollinations.ai/p/" & Server.URLEncode(Trim(CStr(prompt)))
  335. End Function
  336. '------------------------------------------------------------------------------
  337. ' Canonical application URL helpers
  338. ' - Categories use numeric IDs
  339. ' - Posts use slug permalinks for public links and numeric IDs for admin actions
  340. '------------------------------------------------------------------------------
  341. Function CategoryUrl(ByVal categoryId)
  342. CategoryUrl = "/categories/" & Server.URLEncode(CStr(categoryId))
  343. End Function
  344. Function CategoriesUrl()
  345. CategoriesUrl = "/categories"
  346. End Function
  347. Function CategoryNewUrl()
  348. CategoryNewUrl = "/categories/new"
  349. End Function
  350. Function CategoryEditUrl(ByVal categoryId)
  351. CategoryEditUrl = CategoryUrl(categoryId) & "/edit"
  352. End Function
  353. Function CategoryDeleteUrl(ByVal categoryId)
  354. CategoryDeleteUrl = CategoryUrl(categoryId) & "/delete"
  355. End Function
  356. Function PostUrl(ByVal slug)
  357. PostUrl = "/posts/" & Server.URLEncode(NormalizeSlug(slug))
  358. End Function
  359. Function PostPath(ByVal slug)
  360. PostPath = "/posts/" & NormalizeSlug(slug)
  361. End Function
  362. Function PostsUrl()
  363. PostsUrl = "/posts"
  364. End Function
  365. Function PostNewUrl()
  366. PostNewUrl = "/posts/new"
  367. End Function
  368. Function PostEditUrl(ByVal postId)
  369. PostEditUrl = "/posts/" & Server.URLEncode(CStr(postId)) & "/edit"
  370. End Function
  371. Function PostUpdateUrl(ByVal postId)
  372. PostUpdateUrl = "/posts/" & Server.URLEncode(CStr(postId))
  373. End Function
  374. Function PostDeleteUrl(ByVal postId)
  375. PostDeleteUrl = "/posts/" & Server.URLEncode(CStr(postId)) & "/delete"
  376. End Function
  377. Function AdminPostPublishUrl(ByVal postId)
  378. AdminPostPublishUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/publish"
  379. End Function
  380. Function AdminPostUnpublishUrl(ByVal postId)
  381. AdminPostUnpublishUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/unpublish"
  382. End Function
  383. Function AdminPostAIUrl(ByVal postId)
  384. AdminPostAIUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/ai"
  385. End Function
  386. Function AdminCommentsUrl()
  387. AdminCommentsUrl = "/admin/comments"
  388. End Function
  389. Function AdminCommentApproveUrl(ByVal commentId)
  390. AdminCommentApproveUrl = "/admin/comments/" & Server.URLEncode(CStr(commentId)) & "/approve"
  391. End Function
  392. Function AdminCommentUnapproveUrl(ByVal commentId)
  393. AdminCommentUnapproveUrl = "/admin/comments/" & Server.URLEncode(CStr(commentId)) & "/unapprove"
  394. End Function
  395. Function AdminCommentDeleteUrl(ByVal commentId)
  396. AdminCommentDeleteUrl = "/admin/comments/" & Server.URLEncode(CStr(commentId)) & "/delete"
  397. End Function
  398. Function AdminAIPromptUrl()
  399. AdminAIPromptUrl = "/admin/ai-prompt"
  400. End Function
  401. Function AdminAIPromptUpdateUrl()
  402. AdminAIPromptUpdateUrl = "/admin/ai-prompt"
  403. End Function
  404. Function AdminUrl()
  405. AdminUrl = "/admin"
  406. End Function
  407. Function CommentsUrl()
  408. CommentsUrl = "/comments"
  409. End Function
  410. Function NormalizeSlug(ByVal slug)
  411. Dim current, previous
  412. current = Trim(CStr(slug))
  413. If Len(current) = 0 Then
  414. NormalizeSlug = ""
  415. Exit Function
  416. End If
  417. On Error Resume Next
  418. Do
  419. previous = current
  420. current = Server.URLDecode(current)
  421. If Err.Number <> 0 Then
  422. Err.Clear
  423. current = previous
  424. Exit Do
  425. End If
  426. Loop While current <> previous
  427. On Error GoTo 0
  428. current = Replace(current, "%252D", "-")
  429. current = Replace(current, "%252d", "-")
  430. current = Replace(current, "%2D", "-")
  431. current = Replace(current, "%2d", "-")
  432. current = Replace(current, "%25", "%")
  433. NormalizeSlug = current
  434. End Function
  435. '=======================================================================================================================
  436. ' Adapted from Tolerable library
  437. '=======================================================================================================================
  438. ' This subroutine allows us to ignore the difference
  439. ' between object and primitive assignments. This is
  440. ' essential for many parts of the engine.
  441. Public Sub Assign(ByRef var, ByVal val)
  442. If IsObject(val) Then
  443. Set var = val
  444. Else
  445. var = val
  446. End If
  447. End Sub
  448. ' This is similar to the ? : operator of other languages.
  449. ' Unfortunately, both the if_true and if_false "branches"
  450. ' will be evalauted before the condition is even checked. So,
  451. ' you'll only want to use this for simple expressions.
  452. Public Function Choice(ByVal cond, ByVal if_true, ByVal if_false)
  453. If cond Then
  454. Assign Choice, if_true
  455. Else
  456. Assign Choice, if_false
  457. End If
  458. End Function
  459. ' Allows single-quotes to be used in place of double-quotes.
  460. ' Basically, this is a cheap trick that can make it easier
  461. ' to specify Lambdas.
  462. Public Function Q(ByVal input)
  463. Q = Replace(input, "'", """")
  464. End Function
  465. Function SurroundString(inputVar)
  466. If VarType(inputVar) = vbString Then
  467. SurroundString = """" & inputVar & """"
  468. Else
  469. SurroundString = inputVar
  470. End If
  471. End Function
  472. Function SurroundStringInArray(arr)
  473. Dim i
  474. For i = LBound(arr) To UBound(arr)
  475. If IsString(arr(i)) Then
  476. arr(i) = """" & arr(i) & """"
  477. End If
  478. Next
  479. SurroundStringInArray = arr
  480. End Function
  481. '-----------------------------------------------------------------------------------------------------------------------
  482. 'Boolean type checkers
  483. 'Don't forget IsArray is built-in!
  484. Function IsString(value)
  485. IsString = Choice(typename(value) = "String", true, false)
  486. End Function
  487. Function IsDict(value)
  488. IsDict = Choice(typename(value) = "Dictionary", true, false)
  489. End Function
  490. Function IsRecordset(value)
  491. IsRecordset = Choice(typename(value) = "Recordset", true, false)
  492. End Function
  493. Function IsLinkedList(value)
  494. IsLinkedList = Choice(typename(value) = "LinkedList_Class", true, false)
  495. End Function
  496. Function IsArray(value)
  497. IsArray = Choice(typename(value) = "Variant()", true, false)
  498. End Function
  499. '--------------------------------------------------------------------
  500. ' Returns True when the named key is present in Session.Contents
  501. ' • Handles scalars (String, Integer, etc.), objects, Empty, and Null
  502. '--------------------------------------------------------------------
  503. Function SessionHasKey(keyName)
  504. 'Loop over the existing keys—Session.Contents is like a dictionary
  505. Dim k
  506. For Each k In Session.Contents
  507. If StrComp(k, keyName, vbTextCompare) = 0 Then
  508. SessionHasKey = True
  509. Exit Function
  510. End If
  511. Next
  512. SessionHasKey = False 'not found
  513. End Function
  514. Function RenderObjectsAsTable(arr,boolUseTabulator)
  515. Dim html, propNames, i, j, obj, val, pkName, isPk
  516. If IsEmpty(arr) Or Not IsArray(arr) Then
  517. RenderObjectsAsTable = "<!-- no data -->"
  518. Exit Function
  519. End If
  520. Set obj = arr(0)
  521. On Error Resume Next
  522. propNames = obj.Properties
  523. pkName = obj.PrimaryKey
  524. On Error GoTo 0
  525. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  526. RenderObjectsAsTable = "<!-- missing properties or primary key -->"
  527. Exit Function
  528. End If
  529. html = "<div class='table-wrapper'>" & vbCrLf
  530. html = html & "<table class='pobo-table' id='pobo-table'>" & vbCrLf
  531. html = html & " <thead><tr>" & vbCrLf
  532. For i = 0 To UBound(propNames)
  533. html = html & " <th>" & Server.HTMLEncode(propNames(i)) & "</th>" & vbCrLf
  534. Next
  535. html = html & " </tr></thead>" & vbCrLf
  536. html = html & " <tbody>" & vbCrLf
  537. For j = 0 To UBound(arr)
  538. Set obj = arr(j)
  539. html = html & " <tr>" & vbCrLf
  540. For i = 0 To UBound(propNames)
  541. val = GetDynamicProperty(obj, propNames(i))
  542. isPk = (StrComp(propNames(i), pkName, vbTextCompare) = 0)
  543. If IsNull(val) Or IsEmpty(val) Then
  544. val = "&nbsp;"
  545. ElseIf IsDate(val) Then
  546. val = FormatDateTime(val, vbShortDate)
  547. ElseIf VarType(val) = vbBoolean Then
  548. val = IIf(val, "True", "False")
  549. Else
  550. val = CStr(val)
  551. Dim maxLen : maxLen = CInt(GetAppSetting("TableCellMaxLength"))
  552. If maxLen <= 0 Then maxLen = 90
  553. If Len(val) > maxLen Then
  554. val = Left(val, maxLen - 3) & "..."
  555. End If
  556. val = Server.HTMLEncode(val)
  557. End If
  558. If isPk and boolUseTabulator = False Then
  559. val = "<a href=""" & obj.Tablename & "/edit/" & GetDynamicProperty(obj, pkName) & """ class=""table-link"">" & val & "</a>"
  560. End If
  561. html = html & " <td>" & val & "</td>" & vbCrLf
  562. Next
  563. html = html & " </tr>" & vbCrLf
  564. Next
  565. html = html & " </tbody>" & vbCrLf & "</table>" & vbCrLf & "</div>"
  566. RenderObjectsAsTable = html
  567. End Function
  568. Function RenderFormFromObject(obj)
  569. Dim html, propNames, i, name, val, inputType
  570. Dim pkName, tableName, checkedAttr
  571. On Error Resume Next
  572. propNames = obj.Properties
  573. pkName = obj.PrimaryKey
  574. tableName = obj.TableName
  575. On Error GoTo 0
  576. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  577. RenderFormFromObject = "<!-- Invalid object -->"
  578. Exit Function
  579. End If
  580. html = "<form method='post' action='/" & tableName & "/save' class='article-content'>" & vbCrLf
  581. For i = 0 To UBound(propNames)
  582. name = propNames(i)
  583. val = GetDynamicProperty(obj, name)
  584. ' Handle nulls
  585. If IsNull(val) Then val = ""
  586. ' Primary key → hidden input
  587. If StrComp(name, pkName, vbTextCompare) = 0 Then
  588. html = html & " <input type='hidden' name='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  589. 'Continue For
  590. End If
  591. html = html & " <div class='form-group'>" & vbCrLf
  592. html = html & " <label for='" & name & "'>" & name & "</label>" & vbCrLf
  593. Select Case True
  594. Case VarType(val) = vbBoolean
  595. checkedAttr = ""
  596. If val = True Then checkedAttr = " checked"
  597. html = html & " <input type='checkbox' class='form-check-input' name='" & name & "' id='" & name & "' value='true'" & checkedAttr & " />" & vbCrLf
  598. Case IsDate(val)
  599. html = html & " <input type='date' class='form-control' name='" & name & "' id='" & name & "' value='" & FormatDateForInput(val) & "' />" & vbCrLf
  600. Case IsNumeric(val)
  601. html = html & " <input type='number' class='form-control' name='" & name & "' id='" & name & "' value='" & val & "' />" & vbCrLf
  602. Case Len(val) > CInt(GetAppSetting("FormTextareaThreshold"))
  603. html = html & " <textarea class='form-control' name='" & name & "' id='" & name & "' rows='6'>" & Server.HTMLEncode(val) & "</textarea>" & vbCrLf
  604. Case Else
  605. html = html & " <input type='text' class='form-control' name='" & name & "' id='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  606. End Select
  607. html = html & " </div>" & vbCrLf
  608. Next
  609. html = html & " <button type='submit' class='btn btn-primary btn-lg'>Save</button>" & vbCrLf
  610. html = html & "</form>" & vbCrLf
  611. RenderFormFromObject = html
  612. End Function
  613. Function GetDynamicProperty(obj, propName)
  614. On Error Resume Next
  615. Dim result
  616. Execute "result = obj." & propName
  617. If Err.Number <> 0 Then
  618. result = ""
  619. Err.Clear
  620. End If
  621. GetDynamicProperty = result
  622. On Error GoTo 0
  623. End Function
  624. Function FormatDateForInput(val)
  625. If IsDate(val) Then
  626. Dim yyyy, mm, dd
  627. yyyy = Year(val)
  628. mm = Right("0" & Month(val), 2)
  629. dd = Right("0" & Day(val), 2)
  630. FormatDateForInput = yyyy & "-" & mm & "-" & dd
  631. Else
  632. FormatDateForInput = ""
  633. End If
  634. End Function
  635. '-------------------------------------------------------------
  636. ' Returns obj.<propName> for any public VBScript class property
  637. '-------------------------------------------------------------
  638. Function GetObjProp(o, pName)
  639. Dim tmp
  640. ' Build a tiny statement like: tmp = o.UserID
  641. Execute "tmp = o." & pName
  642. GetObjProp = tmp
  643. End Function
  644. Function GenerateSlug(title)
  645. Dim slug
  646. slug = LCase(title) ' Convert to lowercase
  647. slug = Replace(slug, "&", "and") ' Replace ampersands
  648. slug = Replace(slug, "'", "") ' Remove apostrophes
  649. slug = Replace(slug, """", "") ' Remove quotes
  650. slug = Replace(slug, "–", "-") ' Replace en dash
  651. slug = Replace(slug, "—", "-") ' Replace em dash
  652. slug = Replace(slug, "/", "-") ' Replace slashes
  653. slug = Replace(slug, "\", "-") ' Replace backslashes
  654. ' Remove all non-alphanumeric and non-hyphen/space characters
  655. Dim i, ch, clean
  656. clean = ""
  657. For i = 1 To Len(slug)
  658. ch = Mid(slug, i, 1)
  659. If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Or ch = " " Or ch = "-" Then
  660. clean = clean & ch
  661. End If
  662. Next
  663. ' Replace multiple spaces or hyphens with single hyphen
  664. Do While InStr(clean, " ") > 0
  665. clean = Replace(clean, " ", " ")
  666. Loop
  667. clean = Replace(clean, " ", "-")
  668. Do While InStr(clean, "--") > 0
  669. clean = Replace(clean, "--", "-")
  670. Loop
  671. ' Trim leading/trailing hyphens
  672. Do While Left(clean, 1) = "-"
  673. clean = Mid(clean, 2)
  674. Loop
  675. Do While Right(clean, 1) = "-"
  676. clean = Left(clean, Len(clean) - 1)
  677. Loop
  678. GenerateSlug = clean
  679. End Function
  680. Function GetRawJsonFromRequest()
  681. Dim stream, rawJson
  682. Set stream = Server.CreateObject("ADODB.Stream")
  683. stream.Type = 1 ' adTypeBinary
  684. stream.Open
  685. stream.Write Request.BinaryRead(Request.TotalBytes)
  686. stream.Position = 0
  687. stream.Type = 2 ' adTypeText
  688. stream.Charset = "utf-8"
  689. rawJson = stream.ReadText
  690. stream.Close
  691. Set stream = Nothing
  692. GetRawJsonFromRequest = rawJson
  693. End Function
  694. Function Active(controllerName)
  695. On Error Resume Next
  696. If Replace(Lcase(router.Resolve(Request.ServerVariables("REQUEST_METHOD"), TrimQueryParams(Request.ServerVariables("HTTP_X_ORIGINAL_URL")))(0)),"controller","") = LCase(controllerName) Then
  697. Active = "active"
  698. Else
  699. Active = ""
  700. End If
  701. On Error GoTo 0
  702. End Function
  703. '====================================================================
  704. ' FormatDateForSql
  705. ' Converts a VBScript Date to a SQL Server-compatible string
  706. ' Output: 'YYYY-MM-DD HH:MM:SS'
  707. '====================================================================
  708. Function FormatDateForSql(vbDate)
  709. If IsNull(vbDate) Or vbDate = "" Then
  710. FormatDateForSql = "NULL"
  711. Exit Function
  712. End If
  713. ' Ensure vbDate is a valid date
  714. If Not IsDate(vbDate) Then
  715. Err.Raise vbObjectError + 1000, "FormatDateForSql", "Invalid date: " & vbDate
  716. End If
  717. Dim yyyy, mm, dd, hh, nn, ss
  718. yyyy = Year(vbDate)
  719. mm = Right("0" & Month(vbDate), 2)
  720. dd = Right("0" & Day(vbDate), 2)
  721. hh = Right("0" & Hour(vbDate), 2)
  722. nn = Right("0" & Minute(vbDate), 2)
  723. ss = Right("0" & Second(vbDate), 2)
  724. ' Construct SQL Server datetime literal
  725. FormatDateForSql = "'" & yyyy & "-" & mm & "-" & dd & " " & hh & ":" & nn & ":" & ss & "'"
  726. End Function
  727. %>

Powered by TurnKey Linux.