ASP Classic blog framework - BrainOrdure
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

846 lignes
26KB

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

Powered by TurnKey Linux.