ASP Classic blog framework - BrainOrdure
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

641 строка
20KB

  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 Sub ShowServerVariables
  88. Dim varName, htmlTable
  89. htmlTable = "<table border='1' cellspacing='0' cellpadding='5'>"
  90. htmlTable = htmlTable & "<thead><tr><th>Variable Name</th><th>Value</th></tr></thead><tbody>"
  91. ' Loop through all server variables
  92. For Each varName In Request.ServerVariables
  93. htmlTable = htmlTable & "<tr>"
  94. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(varName) & "</td>"
  95. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(Request.ServerVariables(varName)) & "</td>"
  96. htmlTable = htmlTable & "</tr>"
  97. Next
  98. htmlTable = htmlTable & "</tbody></table>"
  99. ' Output the HTML table
  100. Response.Write(htmlTable)
  101. End Sub
  102. '------------------------------------------------------------------------------
  103. ' Utility: IIf Function for VBScript
  104. ' Usage: result = IIf(condition, trueValue, falseValue)
  105. '------------------------------------------------------------------------------
  106. Function IIf(condition, trueValue, falseValue)
  107. On Error Resume Next
  108. If CBool(condition) Then
  109. IIf = trueValue
  110. Else
  111. IIf = falseValue
  112. End If
  113. If Err.Number <> 0 Then
  114. ' Optional: handle or log error in conversion/evaluation
  115. Err.Clear
  116. End If
  117. On Error GoTo 0
  118. End Function
  119. '-----------------------------
  120. ' Utility: Generic Error Reporter
  121. '-----------------------------
  122. Public Sub ErrorCheck(context)
  123. If Err.Number <> 0 Then
  124. Dim errHtml
  125. errHtml = "<div style='padding:10px; border:2px solid red; background:#fdd; font-family:Verdana; font-size:12px;'>"
  126. errHtml = errHtml & "<strong>Error occurred" & IIf(Not IsEmpty(context) And context <> "", ": " & context, "") & "</strong><br />"
  127. errHtml = errHtml & "<em>Time:</em> " & Now() & "<br />"
  128. errHtml = errHtml & "<em>Number:</em> " & Err.Number & "<br />"
  129. errHtml = errHtml & "<em>Description:</em> " & Server.HTMLEncode(Err.Description) & "<br />"
  130. If Len(Err.Source) > 0 Then
  131. errHtml = errHtml & "<em>Source:</em> " & Server.HTMLEncode(Err.Source) & "<br />"
  132. End If
  133. errHtml = errHtml & "</div>"
  134. Response.Write errHtml
  135. Err.Clear
  136. End If
  137. End Sub
  138. '------------------------------------------------------------------------------
  139. ' Utility: TrimQueryParams
  140. ' Removes everything from the first "?" or "&" onward.
  141. ' Usage:
  142. ' CleanPath = TrimQueryParams(rawPath)
  143. '------------------------------------------------------------------------------
  144. Function TrimQueryParams(rawPath)
  145. Dim posQ, posA, cutPos
  146. ' find the first occurrences of "?" and "&"
  147. posQ = InStr(rawPath, "?")
  148. posA = InStr(rawPath, "&")
  149. ' determine the earliest cut position (>0)
  150. If posQ > 0 And posA > 0 Then
  151. cutPos = IIf(posQ < posA, posQ, posA)
  152. ElseIf posQ > 0 Then
  153. cutPos = posQ
  154. ElseIf posA > 0 Then
  155. cutPos = posA
  156. Else
  157. cutPos = 0
  158. End If
  159. ' if found, return up to just before that char
  160. If cutPos > 0 Then
  161. TrimQueryParams = Left(rawPath, cutPos - 1)
  162. Else
  163. TrimQueryParams = rawPath
  164. End If
  165. End Function
  166. Sub Destroy(o)
  167. if isobject(o) then
  168. if not o is nothing then
  169. on error resume next
  170. o.close
  171. on error goto 0
  172. set o = nothing
  173. end if
  174. end if
  175. End Sub
  176. 'prepends indents
  177. Private Sub puti(v)
  178. put Spaces(m_indent) & v
  179. End Sub
  180. Sub put(v)
  181. Select Case typename(v)
  182. Case "LinkedList_Class" : response.write join(v.TO_Array, ", ")
  183. Case "DynamicArray_Class" : response.write JoinList(v)
  184. Case "Variant()" : response.write join(v, ", ")
  185. Case else : response.write v
  186. End Select
  187. End Sub
  188. Sub put_
  189. put "<br>"
  190. End Sub
  191. Sub putl(v)
  192. put v
  193. put_
  194. End Sub
  195. '---------------------------------------------------------------------------------------------------------------------
  196. 'Wrapper for Server.HTMLEncode() -- makes it easier on the eyes when reading the HTML code
  197. Function H(s)
  198. If Not IsEmpty(s) and Not IsNull(s) then
  199. H = Server.HTMLEncode(s)
  200. Else
  201. H = ""
  202. End If
  203. End Function
  204. '------------------------------------------------------------------------------
  205. ' Canonical application URL helpers
  206. ' - Categories use numeric IDs
  207. ' - Posts use slug permalinks for public links and numeric IDs for admin actions
  208. '------------------------------------------------------------------------------
  209. Function CategoryUrl(ByVal categoryId)
  210. CategoryUrl = "/categories/" & Server.URLEncode(CStr(categoryId))
  211. End Function
  212. Function CategoriesUrl()
  213. CategoriesUrl = "/categories"
  214. End Function
  215. Function CategoryNewUrl()
  216. CategoryNewUrl = "/categories/new"
  217. End Function
  218. Function CategoryEditUrl(ByVal categoryId)
  219. CategoryEditUrl = CategoryUrl(categoryId) & "/edit"
  220. End Function
  221. Function CategoryDeleteUrl(ByVal categoryId)
  222. CategoryDeleteUrl = CategoryUrl(categoryId) & "/delete"
  223. End Function
  224. Function PostUrl(ByVal slug)
  225. PostUrl = "/posts/" & Server.URLEncode(CStr(slug))
  226. End Function
  227. Function PostsUrl()
  228. PostsUrl = "/posts"
  229. End Function
  230. Function PostNewUrl()
  231. PostNewUrl = "/posts/new"
  232. End Function
  233. Function PostEditUrl(ByVal postId)
  234. PostEditUrl = "/posts/" & Server.URLEncode(CStr(postId)) & "/edit"
  235. End Function
  236. Function PostDeleteUrl(ByVal postId)
  237. PostDeleteUrl = "/posts/" & Server.URLEncode(CStr(postId)) & "/delete"
  238. End Function
  239. Function AdminPostPublishUrl(ByVal postId)
  240. AdminPostPublishUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/publish"
  241. End Function
  242. Function AdminPostUnpublishUrl(ByVal postId)
  243. AdminPostUnpublishUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/unpublish"
  244. End Function
  245. Function AdminPostAIUrl(ByVal postId)
  246. AdminPostAIUrl = "/admin/posts/" & Server.URLEncode(CStr(postId)) & "/ai"
  247. End Function
  248. Function AdminUrl()
  249. AdminUrl = "/admin"
  250. End Function
  251. Function CommentsUrl()
  252. CommentsUrl = "/comments"
  253. End Function
  254. '=======================================================================================================================
  255. ' Adapted from Tolerable library
  256. '=======================================================================================================================
  257. ' This subroutine allows us to ignore the difference
  258. ' between object and primitive assignments. This is
  259. ' essential for many parts of the engine.
  260. Public Sub Assign(ByRef var, ByVal val)
  261. If IsObject(val) Then
  262. Set var = val
  263. Else
  264. var = val
  265. End If
  266. End Sub
  267. ' This is similar to the ? : operator of other languages.
  268. ' Unfortunately, both the if_true and if_false "branches"
  269. ' will be evalauted before the condition is even checked. So,
  270. ' you'll only want to use this for simple expressions.
  271. Public Function Choice(ByVal cond, ByVal if_true, ByVal if_false)
  272. If cond Then
  273. Assign Choice, if_true
  274. Else
  275. Assign Choice, if_false
  276. End If
  277. End Function
  278. ' Allows single-quotes to be used in place of double-quotes.
  279. ' Basically, this is a cheap trick that can make it easier
  280. ' to specify Lambdas.
  281. Public Function Q(ByVal input)
  282. Q = Replace(input, "'", """")
  283. End Function
  284. Function SurroundString(inputVar)
  285. If VarType(inputVar) = vbString Then
  286. SurroundString = """" & inputVar & """"
  287. Else
  288. SurroundString = inputVar
  289. End If
  290. End Function
  291. Function SurroundStringInArray(arr)
  292. Dim i
  293. For i = LBound(arr) To UBound(arr)
  294. If IsString(arr(i)) Then
  295. arr(i) = """" & arr(i) & """"
  296. End If
  297. Next
  298. SurroundStringInArray = arr
  299. End Function
  300. '-----------------------------------------------------------------------------------------------------------------------
  301. 'Boolean type checkers
  302. 'Don't forget IsArray is built-in!
  303. Function IsString(value)
  304. IsString = Choice(typename(value) = "String", true, false)
  305. End Function
  306. Function IsDict(value)
  307. IsDict = Choice(typename(value) = "Dictionary", true, false)
  308. End Function
  309. Function IsRecordset(value)
  310. IsRecordset = Choice(typename(value) = "Recordset", true, false)
  311. End Function
  312. Function IsLinkedList(value)
  313. IsLinkedList = Choice(typename(value) = "LinkedList_Class", true, false)
  314. End Function
  315. Function IsArray(value)
  316. IsArray = Choice(typename(value) = "Variant()", true, false)
  317. End Function
  318. '--------------------------------------------------------------------
  319. ' Returns True when the named key is present in Session.Contents
  320. ' • Handles scalars (String, Integer, etc.), objects, Empty, and Null
  321. '--------------------------------------------------------------------
  322. Function SessionHasKey(keyName)
  323. 'Loop over the existing keys—Session.Contents is like a dictionary
  324. Dim k
  325. For Each k In Session.Contents
  326. If StrComp(k, keyName, vbTextCompare) = 0 Then
  327. SessionHasKey = True
  328. Exit Function
  329. End If
  330. Next
  331. SessionHasKey = False 'not found
  332. End Function
  333. Function RenderObjectsAsTable(arr,boolUseTabulator)
  334. Dim html, propNames, i, j, obj, val, pkName, isPk
  335. If IsEmpty(arr) Or Not IsArray(arr) Then
  336. RenderObjectsAsTable = "<!-- no data -->"
  337. Exit Function
  338. End If
  339. Set obj = arr(0)
  340. On Error Resume Next
  341. propNames = obj.Properties
  342. pkName = obj.PrimaryKey
  343. On Error GoTo 0
  344. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  345. RenderObjectsAsTable = "<!-- missing properties or primary key -->"
  346. Exit Function
  347. End If
  348. html = "<div class='table-wrapper'>" & vbCrLf
  349. html = html & "<table class='pobo-table' id='pobo-table'>" & vbCrLf
  350. html = html & " <thead><tr>" & vbCrLf
  351. For i = 0 To UBound(propNames)
  352. html = html & " <th>" & Server.HTMLEncode(propNames(i)) & "</th>" & vbCrLf
  353. Next
  354. html = html & " </tr></thead>" & vbCrLf
  355. html = html & " <tbody>" & vbCrLf
  356. For j = 0 To UBound(arr)
  357. Set obj = arr(j)
  358. html = html & " <tr>" & vbCrLf
  359. For i = 0 To UBound(propNames)
  360. val = GetDynamicProperty(obj, propNames(i))
  361. isPk = (StrComp(propNames(i), pkName, vbTextCompare) = 0)
  362. If IsNull(val) Or IsEmpty(val) Then
  363. val = "&nbsp;"
  364. ElseIf IsDate(val) Then
  365. val = FormatDateTime(val, vbShortDate)
  366. ElseIf VarType(val) = vbBoolean Then
  367. val = IIf(val, "True", "False")
  368. Else
  369. val = CStr(val)
  370. Dim maxLen : maxLen = CInt(GetAppSetting("TableCellMaxLength"))
  371. If maxLen <= 0 Then maxLen = 90
  372. If Len(val) > maxLen Then
  373. val = Left(val, maxLen - 3) & "..."
  374. End If
  375. val = Server.HTMLEncode(val)
  376. End If
  377. If isPk and boolUseTabulator = False Then
  378. val = "<a href=""" & obj.Tablename & "/edit/" & GetDynamicProperty(obj, pkName) & """ class=""table-link"">" & val & "</a>"
  379. End If
  380. html = html & " <td>" & val & "</td>" & vbCrLf
  381. Next
  382. html = html & " </tr>" & vbCrLf
  383. Next
  384. html = html & " </tbody>" & vbCrLf & "</table>" & vbCrLf & "</div>"
  385. RenderObjectsAsTable = html
  386. End Function
  387. Function RenderFormFromObject(obj)
  388. Dim html, propNames, i, name, val, inputType
  389. Dim pkName, tableName, checkedAttr
  390. On Error Resume Next
  391. propNames = obj.Properties
  392. pkName = obj.PrimaryKey
  393. tableName = obj.TableName
  394. On Error GoTo 0
  395. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  396. RenderFormFromObject = "<!-- Invalid object -->"
  397. Exit Function
  398. End If
  399. html = "<form method='post' action='/" & tableName & "/save' class='article-content'>" & vbCrLf
  400. For i = 0 To UBound(propNames)
  401. name = propNames(i)
  402. val = GetDynamicProperty(obj, name)
  403. ' Handle nulls
  404. If IsNull(val) Then val = ""
  405. ' Primary key → hidden input
  406. If StrComp(name, pkName, vbTextCompare) = 0 Then
  407. html = html & " <input type='hidden' name='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  408. 'Continue For
  409. End If
  410. html = html & " <div class='form-group'>" & vbCrLf
  411. html = html & " <label for='" & name & "'>" & name & "</label>" & vbCrLf
  412. Select Case True
  413. Case VarType(val) = vbBoolean
  414. checkedAttr = ""
  415. If val = True Then checkedAttr = " checked"
  416. html = html & " <input type='checkbox' class='form-check-input' name='" & name & "' id='" & name & "' value='true'" & checkedAttr & " />" & vbCrLf
  417. Case IsDate(val)
  418. html = html & " <input type='date' class='form-control' name='" & name & "' id='" & name & "' value='" & FormatDateForInput(val) & "' />" & vbCrLf
  419. Case IsNumeric(val)
  420. html = html & " <input type='number' class='form-control' name='" & name & "' id='" & name & "' value='" & val & "' />" & vbCrLf
  421. Case Len(val) > CInt(GetAppSetting("FormTextareaThreshold"))
  422. html = html & " <textarea class='form-control' name='" & name & "' id='" & name & "' rows='6'>" & Server.HTMLEncode(val) & "</textarea>" & vbCrLf
  423. Case Else
  424. html = html & " <input type='text' class='form-control' name='" & name & "' id='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  425. End Select
  426. html = html & " </div>" & vbCrLf
  427. Next
  428. html = html & " <button type='submit' class='btn btn-primary btn-lg'>Save</button>" & vbCrLf
  429. html = html & "</form>" & vbCrLf
  430. RenderFormFromObject = html
  431. End Function
  432. Function GetDynamicProperty(obj, propName)
  433. On Error Resume Next
  434. Dim result
  435. Execute "result = obj." & propName
  436. If Err.Number <> 0 Then
  437. result = ""
  438. Err.Clear
  439. End If
  440. GetDynamicProperty = result
  441. On Error GoTo 0
  442. End Function
  443. Function FormatDateForInput(val)
  444. If IsDate(val) Then
  445. Dim yyyy, mm, dd
  446. yyyy = Year(val)
  447. mm = Right("0" & Month(val), 2)
  448. dd = Right("0" & Day(val), 2)
  449. FormatDateForInput = yyyy & "-" & mm & "-" & dd
  450. Else
  451. FormatDateForInput = ""
  452. End If
  453. End Function
  454. '-------------------------------------------------------------
  455. ' Returns obj.<propName> for any public VBScript class property
  456. '-------------------------------------------------------------
  457. Function GetObjProp(o, pName)
  458. Dim tmp
  459. ' Build a tiny statement like: tmp = o.UserID
  460. Execute "tmp = o." & pName
  461. GetObjProp = tmp
  462. End Function
  463. Function GenerateSlug(title)
  464. Dim slug
  465. slug = LCase(title) ' Convert to lowercase
  466. slug = Replace(slug, "&", "and") ' Replace ampersands
  467. slug = Replace(slug, "'", "") ' Remove apostrophes
  468. slug = Replace(slug, """", "") ' Remove quotes
  469. slug = Replace(slug, "–", "-") ' Replace en dash
  470. slug = Replace(slug, "—", "-") ' Replace em dash
  471. slug = Replace(slug, "/", "-") ' Replace slashes
  472. slug = Replace(slug, "\", "-") ' Replace backslashes
  473. ' Remove all non-alphanumeric and non-hyphen/space characters
  474. Dim i, ch, clean
  475. clean = ""
  476. For i = 1 To Len(slug)
  477. ch = Mid(slug, i, 1)
  478. If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Or ch = " " Or ch = "-" Then
  479. clean = clean & ch
  480. End If
  481. Next
  482. ' Replace multiple spaces or hyphens with single hyphen
  483. Do While InStr(clean, " ") > 0
  484. clean = Replace(clean, " ", " ")
  485. Loop
  486. clean = Replace(clean, " ", "-")
  487. Do While InStr(clean, "--") > 0
  488. clean = Replace(clean, "--", "-")
  489. Loop
  490. ' Trim leading/trailing hyphens
  491. Do While Left(clean, 1) = "-"
  492. clean = Mid(clean, 2)
  493. Loop
  494. Do While Right(clean, 1) = "-"
  495. clean = Left(clean, Len(clean) - 1)
  496. Loop
  497. GenerateSlug = clean
  498. End Function
  499. Function GetRawJsonFromRequest()
  500. Dim stream, rawJson
  501. Set stream = Server.CreateObject("ADODB.Stream")
  502. stream.Type = 1 ' adTypeBinary
  503. stream.Open
  504. stream.Write Request.BinaryRead(Request.TotalBytes)
  505. stream.Position = 0
  506. stream.Type = 2 ' adTypeText
  507. stream.Charset = "utf-8"
  508. rawJson = stream.ReadText
  509. stream.Close
  510. Set stream = Nothing
  511. GetRawJsonFromRequest = rawJson
  512. End Function
  513. Function Active(controllerName)
  514. On Error Resume Next
  515. If Replace(Lcase(router.Resolve(Request.ServerVariables("REQUEST_METHOD"), TrimQueryParams(Request.ServerVariables("HTTP_X_ORIGINAL_URL")))(0)),"controller","") = LCase(controllerName) Then
  516. Active = "active"
  517. Else
  518. Active = ""
  519. End If
  520. On Error GoTo 0
  521. End Function
  522. '====================================================================
  523. ' FormatDateForSql
  524. ' Converts a VBScript Date to a SQL Server-compatible string
  525. ' Output: 'YYYY-MM-DD HH:MM:SS'
  526. '====================================================================
  527. Function FormatDateForSql(vbDate)
  528. If IsNull(vbDate) Or vbDate = "" Then
  529. FormatDateForSql = "NULL"
  530. Exit Function
  531. End If
  532. ' Ensure vbDate is a valid date
  533. If Not IsDate(vbDate) Then
  534. Err.Raise vbObjectError + 1000, "FormatDateForSql", "Invalid date: " & vbDate
  535. End If
  536. Dim yyyy, mm, dd, hh, nn, ss
  537. yyyy = Year(vbDate)
  538. mm = Right("0" & Month(vbDate), 2)
  539. dd = Right("0" & Day(vbDate), 2)
  540. hh = Right("0" & Hour(vbDate), 2)
  541. nn = Right("0" & Minute(vbDate), 2)
  542. ss = Right("0" & Second(vbDate), 2)
  543. ' Construct SQL Server datetime literal
  544. FormatDateForSql = "'" & yyyy & "-" & mm & "-" & dd & " " & hh & ":" & nn & ":" & ss & "'"
  545. End Function
  546. %>

Powered by TurnKey Linux.