Consolidated ASP Classic MVC framework from best components
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.

552 lignes
19KB

  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. ' SQLite stores dates as ISO-8601 text; other providers get a quoted date string
  12. QuoteValue = "'" & Year(val) & "-" & Right("0" & Month(val), 2) & "-" & Right("0" & Day(val), 2) & _
  13. " " & Right("0" & Hour(val), 2) & ":" & Right("0" & Minute(val), 2) & ":" & Right("0" & Second(val), 2) & "'"
  14. Case vbNull, vbEmpty
  15. QuoteValue = "Null"
  16. Case vbBoolean
  17. ' Return boolean values without quotes
  18. QuoteValue = "'" & CStr(val) & "'"
  19. Case Else
  20. If IsNumeric(val) Then
  21. QuoteValue = CLng(val)
  22. Else
  23. QuoteValue = CStr(val)
  24. End If
  25. End Select
  26. End Function
  27. Public Function GetAppSetting(key)
  28. Dim cacheKey, xml, nodes, node, i
  29. cacheKey = "AppSetting_" & key
  30. ' Check Application cache first for performance
  31. If Not IsEmpty(Application(cacheKey)) Then
  32. GetAppSetting = Application(cacheKey)
  33. Exit Function
  34. End If
  35. ' Load from web.config only if not cached
  36. Set xml = Server.CreateObject("Microsoft.XMLDOM")
  37. ' web.config is in the web root (public/); the CLI migration runner uses the framework folder as root
  38. Dim cfgPath : cfgPath = Server.MapPath("/web.config")
  39. If Not CreateObject("Scripting.FileSystemObject").FileExists(cfgPath) Then cfgPath = Server.MapPath("/public/web.config")
  40. xml.Load(cfgPath)
  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 Sub ShowServerVariables
  56. Dim varName, htmlTable
  57. htmlTable = "<table border='1' cellspacing='0' cellpadding='5'>"
  58. htmlTable = htmlTable & "<thead><tr><th>Variable Name</th><th>Value</th></tr></thead><tbody>"
  59. ' Loop through all server variables
  60. For Each varName In Request.ServerVariables
  61. htmlTable = htmlTable & "<tr>"
  62. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(varName) & "</td>"
  63. htmlTable = htmlTable & "<td>" & Server.HTMLEncode(Request.ServerVariables(varName)) & "</td>"
  64. htmlTable = htmlTable & "</tr>"
  65. Next
  66. htmlTable = htmlTable & "</tbody></table>"
  67. ' Output the HTML table
  68. Response.Write(htmlTable)
  69. End Sub
  70. '------------------------------------------------------------------------------
  71. ' Utility: IIf Function for VBScript
  72. ' Usage: result = IIf(condition, trueValue, falseValue)
  73. '------------------------------------------------------------------------------
  74. Function IIf(condition, trueValue, falseValue)
  75. On Error Resume Next
  76. If CBool(condition) Then
  77. IIf = trueValue
  78. Else
  79. IIf = falseValue
  80. End If
  81. If Err.Number <> 0 Then
  82. ' Optional: handle or log error in conversion/evaluation
  83. Err.Clear
  84. End If
  85. On Error GoTo 0
  86. End Function
  87. '-----------------------------
  88. ' Utility: Generic Error Reporter
  89. '-----------------------------
  90. Public Sub ErrorCheck(context)
  91. If Err.Number <> 0 Then
  92. Dim errHtml
  93. errHtml = "<div style='padding:10px; border:2px solid red; background:#fdd; font-family:Verdana; font-size:12px;'>"
  94. errHtml = errHtml & "<strong>Error occurred" & IIf(Not IsEmpty(context) And context <> "", ": " & context, "") & "</strong><br />"
  95. errHtml = errHtml & "<em>Time:</em> " & Now() & "<br />"
  96. errHtml = errHtml & "<em>Number:</em> " & Err.Number & "<br />"
  97. errHtml = errHtml & "<em>Description:</em> " & Server.HTMLEncode(Err.Description) & "<br />"
  98. If Len(Err.Source) > 0 Then
  99. errHtml = errHtml & "<em>Source:</em> " & Server.HTMLEncode(Err.Source) & "<br />"
  100. End If
  101. errHtml = errHtml & "</div>"
  102. Response.Write errHtml
  103. Err.Clear
  104. End If
  105. End Sub
  106. '------------------------------------------------------------------------------
  107. ' Utility: TrimQueryParams
  108. ' Removes everything from the first "?" or "&" onward.
  109. ' Usage:
  110. ' CleanPath = TrimQueryParams(rawPath)
  111. '------------------------------------------------------------------------------
  112. Function TrimQueryParams(rawPath)
  113. Dim posQ, posA, cutPos
  114. rawPath = "" & rawPath
  115. ' find the first occurrences of "?" and "&"
  116. posQ = InStr(rawPath, "?")
  117. posA = InStr(rawPath, "&")
  118. ' determine the earliest cut position (>0)
  119. If posQ > 0 And posA > 0 Then
  120. If posQ < posA Then
  121. cutPos = posQ
  122. Else
  123. cutPos = posA
  124. End If
  125. ElseIf posQ > 0 Then
  126. cutPos = posQ
  127. ElseIf posA > 0 Then
  128. cutPos = posA
  129. Else
  130. cutPos = 0
  131. End If
  132. ' if found, return up to just before that char
  133. If cutPos > 0 Then
  134. TrimQueryParams = Left(rawPath, cutPos - 1)
  135. Else
  136. TrimQueryParams = rawPath
  137. End If
  138. End Function
  139. ' Returns the original request path. IIS URL Rewrite supplies HTTP_X_ORIGINAL_URL;
  140. ' on other hosts (AxonASP/Linux) fall back to the request URL.
  141. Function GetRequestPath()
  142. Dim p
  143. p = "" & Request.QueryString("__route") ' set by the web.config rewrite rule (AxonASP)
  144. If Len(p) = 0 Then p = "" & Request.ServerVariables("HTTP_X_ORIGINAL_URL")
  145. If Len(p) = 0 Then p = "" & Request.ServerVariables("HTTP_X_REWRITE_URL")
  146. If Len(p) = 0 Then p = "" & Request.ServerVariables("URL")
  147. If Len(p) = 0 Then p = "" & Request.ServerVariables("PATH_INFO")
  148. If Len(p) = 0 Then p = "" & Request.ServerVariables("SCRIPT_NAME")
  149. p = TrimQueryParams(p)
  150. If LCase(p) = "/default.asp" Then p = "/"
  151. GetRequestPath = p
  152. End Function
  153. Sub Destroy(o)
  154. if isobject(o) then
  155. if not o is nothing then
  156. on error resume next
  157. o.close
  158. on error goto 0
  159. set o = nothing
  160. end if
  161. end if
  162. End Sub
  163. Sub puts(v)
  164. Select Case typename(v)
  165. Case "LinkedList_Class" : response.write join(v.TO_Array, ", ")
  166. Case "DynamicArray_Class" : response.write JoinList(v)
  167. Case "Variant()" : response.write join(v, ", ")
  168. Case else : response.write v
  169. End Select
  170. End Sub
  171. Sub puts_
  172. puts "<br>"
  173. End Sub
  174. Sub putl(v)
  175. puts v
  176. puts_
  177. End Sub
  178. '---------------------------------------------------------------------------------------------------------------------
  179. 'Wrapper for Server.HTMLEncode() -- makes it easier on the eyes when reading the HTML code
  180. Function H(s)
  181. If Not IsEmpty(s) and Not IsNull(s) then
  182. H = Server.HTMLEncode(s)
  183. Else
  184. H = ""
  185. End If
  186. End Function
  187. '=======================================================================================================================
  188. ' Adapted from Tolerable library
  189. '=======================================================================================================================
  190. ' This subroutine allows us to ignore the difference
  191. ' between object and primitive assignments. This is
  192. ' essential for many parts of the engine.
  193. Public Sub Assign(ByRef var, ByVal val)
  194. If IsObject(val) Then
  195. Set var = val
  196. Else
  197. var = val
  198. End If
  199. End Sub
  200. ' This is similar to the ? : operator of other languages.
  201. ' Unfortunately, both the if_true and if_false "branches"
  202. ' will be evalauted before the condition is even checked. So,
  203. ' you'll only want to use this for simple expressions.
  204. Public Function Choice(ByVal cond, ByVal if_true, ByVal if_false)
  205. If cond Then
  206. Assign Choice, if_true
  207. Else
  208. Assign Choice, if_false
  209. End If
  210. End Function
  211. ' Allows single-quotes to be used in place of double-quotes.
  212. ' Basically, this is a cheap trick that can make it easier
  213. ' to specify Lambdas.
  214. Public Function Q(ByVal input)
  215. Q = Replace(input, "'", """")
  216. End Function
  217. Function SurroundString(inputVar)
  218. If VarType(inputVar) = vbString Then
  219. SurroundString = """" & inputVar & """"
  220. Else
  221. SurroundString = inputVar
  222. End If
  223. End Function
  224. Function SurroundStringInArray(arr)
  225. Dim i
  226. For i = LBound(arr) To UBound(arr)
  227. If IsString(arr(i)) Then
  228. ' double any embedded quote: the value is spliced into an Execute string, so this prevents code injection
  229. arr(i) = """" & Replace(arr(i), """", """""") & """"
  230. End If
  231. Next
  232. SurroundStringInArray = arr
  233. End Function
  234. '-----------------------------------------------------------------------------------------------------------------------
  235. 'Boolean type checkers
  236. 'Don't forget IsArray is built-in!
  237. Function IsString(value)
  238. IsString = Choice(typename(value) = "String", true, false)
  239. End Function
  240. Function IsDict(value)
  241. IsDict = Choice(typename(value) = "Dictionary", true, false)
  242. End Function
  243. Function IsRecordset(value)
  244. IsRecordset = Choice(typename(value) = "Recordset", true, false)
  245. End Function
  246. Function IsLinkedList(value)
  247. IsLinkedList = Choice(typename(value) = "LinkedList_Class", true, false)
  248. End Function
  249. Function IsArray(value)
  250. IsArray = Choice(typename(value) = "Variant()", true, false)
  251. End Function
  252. '--------------------------------------------------------------------
  253. ' Returns True when the named key is present in Session.Contents
  254. ' • Handles scalars (String, Integer, etc.), objects, Empty, and Null
  255. '--------------------------------------------------------------------
  256. Function SessionHasKey(keyName)
  257. 'Loop over the existing keys—Session.Contents is like a dictionary
  258. Dim k
  259. For Each k In Session.Contents
  260. If StrComp(k, keyName, vbTextCompare) = 0 Then
  261. SessionHasKey = True
  262. Exit Function
  263. End If
  264. Next
  265. SessionHasKey = False 'not found
  266. End Function
  267. Function RenderObjectsAsTable(arr,boolUseTabulator)
  268. Dim html, propNames, i, j, obj, val, pkName, isPk
  269. If IsEmpty(arr) Or Not IsArray(arr) Then
  270. RenderObjectsAsTable = "<!-- no data -->"
  271. Exit Function
  272. End If
  273. Set obj = arr(0)
  274. On Error Resume Next
  275. propNames = obj.Properties
  276. pkName = obj.PrimaryKey
  277. On Error GoTo 0
  278. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  279. RenderObjectsAsTable = "<!-- missing properties or primary key -->"
  280. Exit Function
  281. End If
  282. html = "<div class='table-wrapper'>" & vbCrLf
  283. html = html & "<table class='pobo-table' id='pobo-table'>" & vbCrLf
  284. html = html & " <thead><tr>" & vbCrLf
  285. For i = 0 To UBound(propNames)
  286. html = html & " <th>" & Server.HTMLEncode(propNames(i)) & "</th>" & vbCrLf
  287. Next
  288. html = html & " </tr></thead>" & vbCrLf
  289. html = html & " <tbody>" & vbCrLf
  290. For j = 0 To UBound(arr)
  291. Set obj = arr(j)
  292. html = html & " <tr>" & vbCrLf
  293. For i = 0 To UBound(propNames)
  294. val = GetDynamicProperty(obj, propNames(i))
  295. isPk = (StrComp(propNames(i), pkName, vbTextCompare) = 0)
  296. If IsNull(val) Or IsEmpty(val) Then
  297. val = "&nbsp;"
  298. ElseIf IsDate(val) Then
  299. val = FormatDateTime(val, vbShortDate)
  300. ElseIf VarType(val) = vbBoolean Then
  301. val = IIf(val, "True", "False")
  302. Else
  303. val = CStr(val)
  304. Dim maxLen : maxLen = CInt(GetAppSetting("TableCellMaxLength"))
  305. If maxLen <= 0 Then maxLen = 90
  306. If Len(val) > maxLen Then
  307. val = Left(val, maxLen - 3) & "..."
  308. End If
  309. val = Server.HTMLEncode(val)
  310. End If
  311. If isPk and boolUseTabulator = False Then
  312. val = "<a href=""" & obj.Tablename & "/edit/" & GetDynamicProperty(obj, pkName) & """ class=""table-link"">" & val & "</a>"
  313. End If
  314. html = html & " <td>" & val & "</td>" & vbCrLf
  315. Next
  316. html = html & " </tr>" & vbCrLf
  317. Next
  318. html = html & " </tbody>" & vbCrLf & "</table>" & vbCrLf & "</div>"
  319. RenderObjectsAsTable = html
  320. End Function
  321. Function RenderFormFromObject(obj)
  322. Dim html, propNames, i, name, val, inputType
  323. Dim pkName, tableName, checkedAttr
  324. On Error Resume Next
  325. propNames = obj.Properties
  326. pkName = obj.PrimaryKey
  327. tableName = obj.TableName
  328. On Error GoTo 0
  329. If IsEmpty(propNames) Or Len(pkName) = 0 Then
  330. RenderFormFromObject = "<!-- Invalid object -->"
  331. Exit Function
  332. End If
  333. html = "<form method='post' action='/" & tableName & "/save' class='article-content'>" & vbCrLf
  334. For i = 0 To UBound(propNames)
  335. name = propNames(i)
  336. val = GetDynamicProperty(obj, name)
  337. ' Handle nulls
  338. If IsNull(val) Then val = ""
  339. ' Primary key → hidden input
  340. If StrComp(name, pkName, vbTextCompare) = 0 Then
  341. html = html & " <input type='hidden' name='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  342. 'Continue For
  343. End If
  344. html = html & " <div class='form-group'>" & vbCrLf
  345. html = html & " <label for='" & name & "'>" & name & "</label>" & vbCrLf
  346. Select Case True
  347. Case VarType(val) = vbBoolean
  348. checkedAttr = ""
  349. If val = True Then checkedAttr = " checked"
  350. html = html & " <input type='checkbox' class='form-check-input' name='" & name & "' id='" & name & "' value='true'" & checkedAttr & " />" & vbCrLf
  351. Case IsDate(val)
  352. html = html & " <input type='date' class='form-control' name='" & name & "' id='" & name & "' value='" & FormatDateForInput(val) & "' />" & vbCrLf
  353. Case IsNumeric(val)
  354. html = html & " <input type='number' class='form-control' name='" & name & "' id='" & name & "' value='" & val & "' />" & vbCrLf
  355. Case Len(val) > CInt(GetAppSetting("FormTextareaThreshold"))
  356. html = html & " <textarea class='form-control' name='" & name & "' id='" & name & "' rows='6'>" & Server.HTMLEncode(val) & "</textarea>" & vbCrLf
  357. Case Else
  358. html = html & " <input type='text' class='form-control' name='" & name & "' id='" & name & "' value='" & Server.HTMLEncode(val) & "' />" & vbCrLf
  359. End Select
  360. html = html & " </div>" & vbCrLf
  361. Next
  362. html = html & " <button type='submit' class='btn btn-primary btn-lg'>Save</button>" & vbCrLf
  363. html = html & "</form>" & vbCrLf
  364. RenderFormFromObject = html
  365. End Function
  366. Function GetDynamicProperty(obj, propName)
  367. On Error Resume Next
  368. Dim result
  369. Execute "result = obj." & propName
  370. If Err.Number <> 0 Then
  371. result = ""
  372. Err.Clear
  373. End If
  374. GetDynamicProperty = result
  375. On Error GoTo 0
  376. End Function
  377. Function FormatDateForInput(val)
  378. If IsDate(val) Then
  379. Dim yyyy, mm, dd
  380. yyyy = Year(val)
  381. mm = Right("0" & Month(val), 2)
  382. dd = Right("0" & Day(val), 2)
  383. FormatDateForInput = yyyy & "-" & mm & "-" & dd
  384. Else
  385. FormatDateForInput = ""
  386. End If
  387. End Function
  388. '-------------------------------------------------------------
  389. ' Returns obj.<propName> for any public VBScript class property
  390. '-------------------------------------------------------------
  391. Function GetObjProp(o, pName)
  392. Dim tmp
  393. ' Build a tiny statement like: tmp = o.UserID
  394. Execute "tmp = o." & pName
  395. GetObjProp = tmp
  396. End Function
  397. Function GenerateSlug(title)
  398. Dim slug
  399. slug = LCase(title) ' Convert to lowercase
  400. slug = Replace(slug, "&", "and") ' Replace ampersands
  401. slug = Replace(slug, "'", "") ' Remove apostrophes
  402. slug = Replace(slug, """", "") ' Remove quotes
  403. slug = Replace(slug, "–", "-") ' Replace en dash
  404. slug = Replace(slug, "—", "-") ' Replace em dash
  405. slug = Replace(slug, "/", "-") ' Replace slashes
  406. slug = Replace(slug, "\", "-") ' Replace backslashes
  407. ' Remove all non-alphanumeric and non-hyphen/space characters
  408. Dim i, ch, clean
  409. clean = ""
  410. For i = 1 To Len(slug)
  411. ch = Mid(slug, i, 1)
  412. If (ch >= "a" And ch <= "z") Or (ch >= "0" And ch <= "9") Or ch = " " Or ch = "-" Then
  413. clean = clean & ch
  414. End If
  415. Next
  416. ' Replace multiple spaces or hyphens with single hyphen
  417. Do While InStr(clean, " ") > 0
  418. clean = Replace(clean, " ", " ")
  419. Loop
  420. clean = Replace(clean, " ", "-")
  421. Do While InStr(clean, "--") > 0
  422. clean = Replace(clean, "--", "-")
  423. Loop
  424. ' Trim leading/trailing hyphens
  425. Do While Left(clean, 1) = "-"
  426. clean = Mid(clean, 2)
  427. Loop
  428. Do While Right(clean, 1) = "-"
  429. clean = Left(clean, Len(clean) - 1)
  430. Loop
  431. GenerateSlug = clean
  432. End Function
  433. Function GetRawJsonFromRequest()
  434. Dim stream, rawJson
  435. Set stream = Server.CreateObject("ADODB.Stream")
  436. stream.Type = 1 ' adTypeBinary
  437. stream.Open
  438. stream.Write Request.BinaryRead(Request.TotalBytes)
  439. stream.Position = 0
  440. stream.Type = 2 ' adTypeText
  441. stream.Charset = "utf-8"
  442. rawJson = stream.ReadText
  443. stream.Close
  444. Set stream = Nothing
  445. GetRawJsonFromRequest = rawJson
  446. End Function
  447. Function Active(controllerName)
  448. On Error Resume Next
  449. If Replace(Lcase(GetRouter().Resolve(Request.ServerVariables("REQUEST_METHOD"), GetRequestPath())(0)),"controller","") = LCase(controllerName) Then
  450. Active = "active"
  451. Else
  452. Active = ""
  453. End If
  454. On Error GoTo 0
  455. End Function
  456. '====================================================================
  457. ' FormatDateForSql
  458. ' Converts a VBScript Date to a SQL Server-compatible string
  459. ' Output: 'YYYY-MM-DD HH:MM:SS'
  460. '====================================================================
  461. Function FormatDateForSql(vbDate)
  462. If IsNull(vbDate) Or vbDate = "" Then
  463. FormatDateForSql = "NULL"
  464. Exit Function
  465. End If
  466. ' Ensure vbDate is a valid date
  467. If Not IsDate(vbDate) Then
  468. Err.Raise vbObjectError + 1000, "FormatDateForSql", "Invalid date: " & vbDate
  469. End If
  470. Dim yyyy, mm, dd, hh, nn, ss
  471. yyyy = Year(vbDate)
  472. mm = Right("0" & Month(vbDate), 2)
  473. dd = Right("0" & Day(vbDate), 2)
  474. hh = Right("0" & Hour(vbDate), 2)
  475. nn = Right("0" & Minute(vbDate), 2)
  476. ss = Right("0" & Second(vbDate), 2)
  477. ' Construct SQL Server datetime literal
  478. FormatDateForSql = "'" & yyyy & "-" & mm & "-" & dd & " " & hh & ":" & nn & ":" & ss & "'"
  479. End Function
  480. %>

Powered by TurnKey Linux.