Zum Inhalt springen

Modul:URLutil

aus Wikipedia, der freien Enzyklopädie
Dies ist eine alte Version dieser Seite, zuletzt bearbeitet am 12. April 2013 um 22:01 Uhr durch PerfektesChaos (Diskussion | Beiträge) (Anpassung). Sie kann sich erheblich von der aktuellen Version unterscheiden.
Vorlagen-
programmierung
Diskussionen Lua Test Unterseiten
Modul Deutsch English

Esperanto Dolnoserbski Hornjoserbsce Modul: WP:Lua

Diese Seite enthält Code in der Programmiersprache Lua. Einbindungszahl Cirrus

Dies ist die (produktive) Mutterversion eines global benutzten Lua-Moduls.
Wenn die serial-Information nicht übereinstimmt, müsste eine Kopie hiervon in das lokale Wiki geschrieben werden.
Versionsbezeichnung auf WikiData: 2024-10-29

--[=[
URLutil: Utilities for URL etc.
* getScheme()
* getDomain()
* isIP()
* isIPv4()
* isIPv6()
Only [[dotted decimal]] notation for IPv4 supported.
Does not support dotted hexadecimal, dotted octal, or single-number formats.

Functions are not "local", so other modules can require this module and call them directly.
We return an object with small stub functions to call the real ones so that the functions
can be called from templates also.
----
Based upon   w:en:Special:Permalink/542839577?title=Module:IPAddress   2013-03-01
Unit tests at :en:Module:IPAddress/tests
]=]

function _isIPv6( s )
    local dcolon, groups
    if type( s ) ~= "string"
        or s:len() == 0
        or s:find( "[^:%x]" ) -- only colon and hex digits are legal chars
        or s:find( "^:[^:]" ) -- can begin or end with :: but not with single :
        or s:find( "[^:]:$" )
        or s:find( ":::" )
    then
        return false
    end 
    s, dcolon = s:gsub( "::", ":" )
    if dcolon > 1 then return false end -- at most one ::
    s = s:gsub( "^:?", ":" ) -- prepend : if needed, upper
    s, groups = s:gsub( ":%x%x?%x?%x?", "" ) -- remove valid groups, and count them
    return ( ( dcolon == 1 and groups < 8 ) or ( dcolon == 0 and groups == 8 ) )
        and ( s:len() == 0 or ( dcolon == 1 and s == ":" ) ) -- might be one dangling : if original ended with ::
end

function _isIPv4( s )
    local function legal( n ) return ( tonumber( n ) or 256 ) < 256  and not n:match("^0%d") end-- in lua 0 is true!
    
    if type( s ) ~= "string" then return false end
    local p1, p2, p3, p4 = s:match( "^(%d+)%.(%d+)%.(%d+)%.(%d+)$" ) 
    return legal( p1 ) and legal( p2 ) and legal( p3 ) and legal( p4 )
end

function _isIP( s )
    return _isIPv4( s ) and "4" or _isIPv6( s ) and "6"
end

local p = {}

function p.isIPv6(frame) return _isIPv6( frame.args[ 1 ] ) and "1" or "0" end
function p.isIPv4(frame) return _isIPv4( frame.args[ 1 ] ) and "1" or "0" end
function p.isIP(frame) return _isIP( frame.args[ 1 ] ) or "" end

return p