הבדלים בין גרסאות בדף "יחידה:String"

מתוך ויקיסוגיה
קפיצה לניווט קפיצה לחיפוש
מ (גרסה אחת יובאה: ייבוא מויקיפדיה. ראה ברשימת התורמים בגרסאות קודמות שם. משוחרר ברישיון זהה לרישיון שם)
תגית: שוחזרה
שורה 1: שורה 1:
--[[
--[=[


This module is intended to provide access to basic string functions.
This module is based on idea and original code of [[User:IKhitron]].


Most of the functions provided here can be invoked with named parameters,
the source of this module is in //he.wikipedia.org/wiki/Module:ParamValidator
unnamed parameters, or a mixture. If named parameters are used, Mediawiki will
automatically remove any leading or trailing whitespace from the parameter. 
Depending on the intended use, it may be advantageous to either preserve or
remove such whitespace.


Global options
main purpose: use "templatedata" to verify the parameters passed to a template
    ignore_errors: If set to 'true' or 1, any error condition will result in
        an empty string being returned rather than an error message. 
       
    error_category: If an error occurs, specifies the name of a category to
        include with the error message.  The default category is 
        [Category:Errors reported by Module String].
       
    no_category: If set to 'true' or 1, no category will be added if an error
        is generated.
       
Unit tests for this module are available at Module:String/tests.
]]


local str = {}
Terminology: "numeric parameter" means order-based parameter. e.g. if the template is transcluded like so {{x  | k |  | a = m | b = }}
"a" and "b" are "named" parameters, and there are 2 "numeric", or order based parameters, 1 and 2.
we say that the value of a is "m", the value of 1 is "k", and "b" and 2 are "empty".


--[[
This module exports two functions: calculateViolations( frame, subpages ), and validateParams( frame ).
len


This function returns the length of the target string.
calculateViolations( frame, subpages ) finds templatedata, in template page or in one of its subpages in the list, if provided.
it returns a table with the violations. if there are none, the table is empty. otherwise it has the structure
{
violation1 = { param1 = value1, param2 = value2 },
violation2 = { ... },
...
}


Usage:
violation1, violation2 etc. are one of the names of specific violations, as described below.
{{#invoke:String|len|target_string|}}
param1, param2 etc. are either the names of parameter passed to the template, or defined in templatedata.
OR
value1, value2 etc. are the values passed to the template, or an empty string if no such parameter was passed.
{{#invoke:String|len|s=target_string}}


Parameters
the different violations are as follow:
    s: The string whose length to report
* "no-templatedata": no valid tempaltedata was found in tempalte page, or documentation subpage
* "undeclared": named parameters with non-empty value, does not exist in templatedata
* "empty-undeclared": named parameters with empty value, does not exist in templatedata
* "undeclared-numeric": numeric parameters with non-empty value, does not exist in templatedata
* "empty-undeclared-numeric": numeric parameters with empty value, does not exist in templatedata
* "deprecated":  parameters with non-empty value, marked as "deprecated" in tempaltedata
* "empty-deprecated":  parameters with empty value, marked as "deprecated" in tempaltedata
* "empty-required": missing or empty parameter marked as "required" in tempaltedata
* "incompatible": a non-empty parameter passed to the template, incompatible with the parameter type defined in templatedata
* "duplicate": a value is passed for the same parameter (or any of its aliases) more than once


If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string. 
]]
function str.len( frame )
    local new_args = str._getParameters( frame.args, {'s'} );
    local s = new_args['s'] or '';
    return mw.ustring.len( s )
end


--[[
The second function, validateParams( frame ), can be called from the tempalte' using #invoke.
sub
it expects a parameter named "options", which contains the definition of the output. typically, it's used by placing something like so:


This function returns a substring of the target string at specified indices.
<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} }}</includeonly>


Usage:
at the top of the template (be mindful not to add extra spaces and newlines to the template).
{{#invoke:String|sub|target_string|start_index|end_index}}
to bypass some mediawiki limitation, it is also possible to pass the options as "module", like so (use one of the two, but not both):
OR
<includeonly>{{#invoke:ParamValidator | validateParams | module_options = Module:PV default options}} }}</includeonly>
{{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}


Parameters
the first form expects a template named "Template:PV default options" which contains the options, and the 2nd form expects a module,  
    s: The string to return a subset of
suitable for mw.loadData(), which returns a map of namespace => options (i.e. { [0] = <options>, [2] => <options> } .... )
    i: The fist index of the substring to return, defaults to 1.
    j: The last index of the string to return, defaults to the last character.
   
The first character of the string is assigned an index of 1. If either i or j
is a negative value, it is interpreted the same as selecting a character by
counting from the end of the string. Hence, a value of -1 is the same as
selecting the last character of the string.


If the requested indices are out of range for the given string, an error is
the options parameter should be a JSON-encoded string, defining the output, and some special behaviors.  
reported.
the example above assumes that a wiki page named [[Template:PV default options]] exists, and contains valid JSON string.  
]]
for each of the violations defined above, "options" may define an output string, so basically, "options" looks like so:
function str.sub( frame )
{
    local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );
violation1: outputstring1,
    local s = new_args['s'] or '';
violation2: outputstring2,
    local i = tonumber( new_args['i'] ) or 1;
.... ,
    local j = tonumber( new_args['j'] ) or -1;
behavior1: some value,
   
....
    local len = mw.ustring.len( s );
}


    -- Convert negatives for range checking
not all violations have to be defined. a violation not defined in "options" will be ignored.
    if i < 0 then
        i = len + i + 1;
    end
    if j < 0 then
        j = len + j + 1;
    end
   
    if i > len or j > len or i < 1 or j < 1 then
        return str._error( 'String subset index out of range' );
    end
    if j < i then
        return str._error( 'String subset indices out of order' );
    end
   
    return mw.ustring.sub( s, i, j )
end


--[[
when invoked, it extract "subpages" from the options parameter, and calls:
This function implements that features of {{str sub old}} and is kept in order
calculateViolations( frame, subpages )
to maintain these older templates.
if the returned table is empty, no violation were found, and an empty string is returned and nothing else happens.
]]
function str.sublength( frame )
    local i = tonumber( frame.args.i ) or 0
    local len = tonumber( frame.args.len )
    return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
end


--[[
otherwise, for each of the violations, i.e., the keys of the returned table, when "options" contains this key,
match
the corresonding value is appended to the output.


This function returns a substring from the source string that matches a  
some further processing is done:
specified pattern.
1) several tokens are replaced with calculated values. these are described below.
2) some "meta" violations are calculated: when any none-ignored violation occured,
the "any" meta-violation is added to the output in the same way,
i.e. the string keyed by "any" in the options is appended to output with appropriate substitutions.
similarly, "multiple" meta-violation is created when more than one type of non-ignored violations occured.
3) if the output is not empty, a prefix and suffix strings are prepended and appended to it.  


Usage:
these are the tokens and the replacement.
{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
* "templatename": full template name, including namespace.
OR
* "tname_naked": template name without namespace.
{{#invoke:String|pos|s=source_string|pattern=pattern_string|start=start_index
* "paramname":  comma-separated list of parameters
    |match=match_number|plain=plain_flag|nomatch=nomatch_output}}
* "paramandvalue": is replaced by comma-separated list of "name: value" pairs of parameters and values
the first two are applied to the whole output, including the suffux and prefix,
and the rest are applied to the individual violations, each with its own list of offending parameters and values.


Parameters
    s: The string to search
    pattern: The pattern or string to find within the string
    start: The index within the source string to start the search.  The first
        character of the string has index 1.  Defaults to 1.
    match: In some cases it may be possible to make multiple matches on a single
        string.  This specifies which match to return, where the first match is
        match= 1.  If a negative number is specified then a match is returned
        counting from the last match.  Hence match = -1 is the same as requesting
        the last match.  Defaults to 1.
    plain: A flag indicating that the pattern should be understood as plain
        text.  Defaults to false.
    nomatch: If no match is found, output the "nomatch" value rather than an error.


If invoked using named parameters, Mediawiki will automatically remove any leading or
the rest of the if the value of some keys is null, this error condition will be ignored, and not counted when calculating "any" and "multiple" conditions.
trailing whitespace from each string.  In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.


If the match_number or start_index are out of range for the string being queried, then
some other optional fields can be passed via options:
this function generates an error. An error is also generated if no match is found.
* "doc-subpage": can be either a string, or a list (in square bracktes) of strings, indicating subpages of the template
If one adds the parameter ignore_errors=true, then the error will be suppressed and
that may contain templatedata.  
an empty string will be returned on any failure.
* "ignore": list of patterns. any parameter whose name matches any pattern, will not considered in violation of any of the rules.
* "skip-empty-numeric": if a quoted number, the module will ignore non-declared empty numeric parameters up to this number
* "wrapper-prefix": openning wrapper element of outpot (defaults to "<div class = 'paramvalidator-wrapper'>")
* "wrapper-suffix": closing wrapper element of output (defaults to "</div>")


For information on constructing Lua patterns, a form of [regular expression], see:
additional option parameters, named options1, options2, etc. can be passed. any entry defined in these options will
override the previous value. a typical use may be like so:


* http://www.lua.org/manual/5.1/manual.html#5.4.1
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
typically, this JSON structure will be placed in a separate template, and retrieved for the module-use as shown above.
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} | options1 = {"key":"value"} }}</includeonly>
"key" can override any of the options fields described above.


]]
function str.match( frame )
    local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
    local s = new_args['s'] or '';
    local start = tonumber( new_args['start'] ) or 1;
    local plain_flag = str._getBoolean( new_args['plain'] or false );
    local pattern = new_args['pattern'] or '';
    local match_index = math.floor( tonumber(new_args['match']) or 1 );
    local nomatch = new_args['nomatch'];
   
    if s == '' then
        return str._error( 'Target string is empty' );
    end
    if pattern == '' then
        return str._error( 'Pattern string is empty' );
    end
    if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
        return str._error( 'Requested start is out of range' );
    end
    if match_index == 0 then
        return str._error( 'Match index is out of range' );
    end
    if plain_flag then
        pattern = str._escapePattern( pattern );
    end
   
    local result
    if match_index == 1 then
        -- Find first match is simple case
        result = mw.ustring.match( s, pattern, start )
    else
        if start > 1 then
            s = mw.ustring.sub( s, start );
        end
       
        local iterator = mw.ustring.gmatch(s, pattern);
        if match_index > 0 then
            -- Forward search
            for w in iterator do
                match_index = match_index - 1;
                if match_index == 0 then
                    result = w;
                    break;
                end
            end   
        else
            -- Reverse search
            local result_table = {};
            local count = 1;
            for w in iterator do
                result_table[count] = w;
                count = count + 1;
            end
           
            result = result_table[ count + match_index ];           
        end
    end       
   
    if result == nil then
        if nomatch == nil then
            return str._error( 'Match not found' );
        else
            return nomatch;
        end
    else
        return result;
    end
end


--[[
]=]
pos


This function returns a single character from the target string at position pos.
local util = {
empty = function( s )
return s == nil  or type( s ) == 'string' and mw.text.trim( s ) == '' 
end
,
extract_options = function( frame, optionsPrefix )
optionsPrefix = optionsPrefix or 'options'


Usage:
local options, n, more = {}
{{#invoke:String|pos|target_string|index_value}}
if frame.args['module_options'] then
OR
local module_options = mw.loadData( frame.args['module_options'] )
{{#invoke:String|pos|target=target_string|pos=index_value}}
if type( module_options ) ~= 'table' then return {} end
local title = mw.title.getCurrentTitle()
local local_ptions = module_options[ title.namespace ] or module_options[ title.nsText ] or {}  
for k, v in pairs( local_ptions ) do options[k] = v end
end
repeat
ok, more = pcall( mw.text.jsonDecode, frame.args[optionsPrefix .. ( n or '' )] )
if ok and type( more ) == 'table' then
for k, v in pairs( more ) do options[k] = v end
end
n = ( n or 0 ) + 1
until not ok


Parameters
return options
    target: The string to search
end
    pos: The index for the character to return
,
 
build_namelist = function ( template_name, sp )
If invoked using named parameters, Mediawiki will automatically remove any leading or
local res = { template_name }
trailing whitespace from the target string. In some circumstances this is desirable, in
if sp then
other cases one may want to preserve the whitespace.
if type( sp ) == 'string' then sp = { sp } end
 
for _, p in ipairs( sp ) do table.insert( res, template_name .. '/' .. p ) end
The first character has an index value of 1.
end
 
return res
If one requests a negative value, this function will select a character by counting backwards
end
from the end of the string.  In other words pos = -1 is the same as asking for the last character.
,
 
table_empty = function( t ) -- normally, test if next(t) is nil, but for some perverse reason, non-empty tables returned by loadData return nil...
A requested value of zero, or a value greater than the length of the string returns an error.
if type( t ) ~= 'table' then return true end
]]
for a, b in pairs( t ) do return false end
function str.pos( frame )
return true
    local new_args = str._getParameters( frame.args, {'target', 'pos'} );
end
    local target_str = new_args['target'] or '';
,
    local pos = tonumber( new_args['pos'] ) or 0;
}


    if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
local function _readTemplateData( templateName )
        return str._error( 'String index out of range' );
local title = mw.title.makeTitle( 0, templateName ) 
    end   
local templateContent = title and title.exists and title:getContent() -- template's raw content
   
local capture =  templateContent and mw.ustring.match( templateContent, '<templatedata%s*>(.*)</templatedata%s*>' ) -- templatedata as text
    return mw.ustring.sub( target_str, pos, pos );
-- capture = capture and mw.ustring.gsub( capture, '"(%d+)"', tonumber ) -- convert "1": {} to 1: {}. frame.args uses numerical indexes for order-based params.
local trailingComma = capture and mw.ustring.find( capture, ',%s*[%]%}]' ) -- look for ,] or ,} : jsonDecode allows it, but it's verbotten in json
if capture and not trailingComma then return pcall( mw.text.jsonDecode, capture ) end
return false
end
end


--[[
local function readTemplateData( templateName )
str_find
if type( templateName ) == 'string' then
 
templateName = { templateName, templateName .. '/' .. docSubPage }
This function duplicates the behavior of {{str_find}}, including all of its quirks.
end
This is provided in order to support existing templates, but is NOT RECOMMENDED for
if type( templateName ) == "table" then
new code and templates.  New code is recommended to use the "find" function instead.
for _, name in ipairs( templateName ) do
 
local td, result = _readTemplateData( name )  
Returns the first index in "source" that is a match to "target".  Indexing is 1-based,
if td then return result end
and the function returns -1 if the "target" string is not present in "source".
end
 
end
Important Note: If the "target" string is empty / missing, this function returns a
return nil
value of "1", which is generally unexpected behavior, and must be accounted for
separatetly.
]]
function str.str_find( frame )
    local new_args = str._getParameters( frame.args, {'source', 'target'} );
    local source_str = new_args['source'] or '';
    local target_str = new_args['target'] or '';
 
    if target_str == '' then
        return 1;
    end   
   
    local start = mw.ustring.find( source_str, target_str, 1, true )
    if start == nil then
        start = -1
    end
   
    return start
end
end


--[[
find


This function allows one to search for a target string or pattern within another
-- this is the function to be called by other modules. it expects the frame, and then an optional list of subpages, e.g. { "Documentation" }.
string.
-- if second parameter is nil, only tempalte page will be searched for templatedata.
local function calculateViolations( frame, subpages )
-- used for parameter type validy test. keyed by TD 'type' string. values are function(val) returning bool.
local type_validators = {
['number'] = function( s ) return mw.language.getContentLanguage():parseFormattedNumber( s ) end
}
local function compatible( typ, val )
local func = type_validators[typ]
return type( func ) ~= 'function' or util.empty( val ) or func( val )
end
local function list_empty_or_contains(ar, searched)
if not ar or #ar == 0 then return true end
for _, val in ipairs(ar) do if val == searched then return true end end
return false
end
local t_frame = frame:getParent()
local t_args, template_name = t_frame.args, t_frame:getTitle()
local td_source = util.build_namelist( template_name, subpages )
local templatedata = readTemplateData( td_source )
local td_params = templatedata and templatedata.params
local all_aliases, all_series = {}, {}
if not td_params then return { ['no-templatedata'] = { [''] = '' } } end
-- from this point on, we know templatedata is valid.


Usage:
local res = {} -- before returning to caller, we'll prune empty tables
{{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
OR
{{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}


Parameters
-- allow for aliases
    source: The string to search
for _, p in pairs( td_params ) do for _, alias in ipairs( p.aliases or {} ) do
    target: The string or pattern to find within source
all_aliases[alias] = p
    start: The index within the source string to start the search, defaults to 1
if tonumber(alias) then all_aliases[tonumber(alias)] = p end
    plain: Boolean flag indicating that target should be understood as plain
end end
        text and not as a Lua style regular expression, defaults to true


If invoked using named parameters, Mediawiki will automatically remove any leading or
-- handle undeclared and deprecated
trailing whitespace from the parameter. In some circumstances this is desirable, in  
local already_seen = {}
other cases one may want to preserve the whitespace.
local series = frame.args['series']
for p_name, value in pairs( t_args ) do
local tp_param, noval, numeric, table_name = td_params[p_name] or all_aliases[p_name], util.empty( value ), tonumber( p_name )
local hasval = not noval


This function returns the first index >= "start" where "target" can be found
if not tp_param and series then -- 2nd chance. check to see if series
within "source". Indices are 1-basedIf "target" is not found, then this  
for s_name, p in pairs(td_params) do
function returns 0. If either "source" or "target" are missing / empty, this
if mw.ustring.match( p_name, '^' .. s_name .. '%d+' .. '$') then
function also returns 0.
-- mw.log('found p_name '.. p_name .. ' s_name:' .. s_name, ' p is:', p) debugging series support
tp_param = p
end -- don't bother breaking. td always correct.
end
end
if not tp_param then -- not in TD: this is called undeclared
-- calculate the relevant table for this undeclared parameter, based on parameter and value types
table_name =
noval and numeric and 'empty-undeclared-numeric' or
noval and not numeric and 'empty-undeclared' or
hasval and numeric and 'undeclared-numeric' or
'undeclared' -- tzvototi nishar.
else -- in td: test for deprecation and mistype. if deprecated, no further tests
table_name = tp_param.deprecated and hasval and 'deprecated'
or tp_param.deprecated and noval and 'empty-deprecated'
or not compatible( tp_param.type, value ) and 'incompatible'
or not series and already_seen[tp_param] and hasval and 'duplicate'
or hasval and not list_empty_or_contains(tp_param.suggestedvalues , value) and 'unsuggested-value'


This function should be safe for UTF-8 strings.
]]
already_seen[tp_param] = hasval
function str.find( frame )
end
    local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } );
-- report it.
    local source_str = new_args['source'] or '';
if table_name then
    local pattern = new_args['target'] or '';
res[table_name] = res[table_name] or {}
    local start_pos = tonumber(new_args['start']) or 1;
res[table_name][p_name] = value
    local plain = new_args['plain'] or true;
end
       
end
    if source_str == '' or pattern == '' then
        return 0;
-- test for empty/missing paraeters declared "required"
    end  
for p_name, param in pairs( td_params ) do
   
if param.required and util.empty( t_args[p_name] ) then
    plain = str._getBoolean( plain );
local is_alias
 
for _, alias in ipairs( param.aliases or {} ) do is_alias = is_alias or not util.empty( t_args[alias] ) end
    local start = mw.ustring.find( source_str, pattern, start_pos, plain )
if not is_alias then
    if start == nil then
res['empty-required'] = res['empty-required'] or {}
        start = 0
res['empty-required'][p_name] = ''  
    end
end
   
end
    return start
end
return res
end
end


--[[
-- wraps report in hidden frame
replace
local function wrapReport(report, template_name, options)
 
if util.empty( report ) then return '' end
This function allows one to replace a target string or pattern within another
local naked = mw.title.new( template_name )['text']  
string.
 
mw.log(report)
Usage:
report = ( options['wrapper-prefix'] or "<div class = 'paramvalidator-wrapper'><span class='paramvalidator-error'>" )
{{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
.. report
OR
.. ( options['wrapper-suffix'] or "</span></div>" )
{{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
  count=replacement_count|plain=plain_flag}}
report = mw.ustring.gsub( report, 'tname_naked', naked )
 
report = mw.ustring.gsub( report, 'templatename', template_name )
Parameters
return report
    source: The string to search
    pattern: The string or pattern to find within source
    replace: The replacement text
    count: The number of occurences to replace, defaults to all.
    plain: Boolean flag indicating that pattern should be understood as plain
        text and not as a Lua style regular expression, defaults to true
]]
function str.replace( frame )
    local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } );
    local source_str = new_args['source'] or '';
    local pattern = new_args['pattern'] or '';
    local replace = new_args['replace'] or '';
    local count = tonumber( new_args['count'] );
    local plain = new_args['plain'] or true;
       
    if source_str == '' or pattern == '' then
        return source_str;
    end   
    plain = str._getBoolean( plain );
 
    if plain then
        pattern = str._escapePattern( pattern );
        replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Only need to escape replacement sequences.
    end
   
    local result;
 
    if count ~= nil then
        result = mw.ustring.gsub( source_str, pattern, replace, count );
    else
        result = mw.ustring.gsub( source_str, pattern, replace );
    end       
 
    return result;
end
end


--[[
-- this is the "user" version, called with {{#invoke:}} returns a string, as defined by the options parameter
"Reverse" reverses a string, a'la string.reverse()
local function validateParams( frame )
]]
str.reverse = function( frame )
-- for purple pages:
    local tab = mw.text.split( frame.args[1] or '', '' )
if frame:getParent().args['skip parameters validation'] then return '[[ קטגוריה:דפים עם שגיאות פרמטריות שקיבלו חנינה]]' end
    local restab = {}
local options, report, template_name = util.extract_options( frame ), '', frame:getParent():getTitle()
    for i = #tab, 1, -1 do table.insert( restab, tab[i] ) end
    return table.concat( restab )
end


str['היפוך'] = str.reverse
local ignore = function( p_name )
for _, pattern in ipairs( options['ignore'] or {} ) do
if mw.ustring.match( p_name, '^' .. pattern .. '$' ) then return true end
end
return false
end


--[[
local replace_macros = function( s, param_names )
Helper function that populates the argument list given that user may need to use a mix of
local function concat_and_escape( t )
named and unnamed parameters. This is relevant because named parameters are not
local s = table.concat( t, ', ' )
identical to unnamed parameters due to string trimming, and when dealing with strings
return ( mw.ustring.gsub( s, '%%', '%%%%' ) )
we sometimes want to either preserve or remove that whitespace depending on the application.
end
]]
function str._getParameters( frame_args, arg_list )
if s and ( type( param_names ) == 'table' ) then
    local new_args = {};
local k_ar, kv_ar = {}, {}
    local index = 1;
for k, v in pairs( param_names ) do
    local value;
table.insert( k_ar, k )
   
table.insert( kv_ar, k .. ': ' .. v)
    for i,arg in ipairs( arg_list ) do
end
        value = frame_args[arg]
s = mw.ustring.gsub( s, 'paramname', concat_and_escape( k_ar ) )
        if value == nil then
s = mw.ustring.gsub( s, 'paramandvalue', concat_and_escape( kv_ar ) )
            value = frame_args[index];
end
            index = index + 1;
return s
        end
end
        new_args[arg] = value;
    end
   
    return new_args;
end      


--[[
local report_params = function( key, param_names )
Helper function to handle error messages.
local res = replace_macros( options[key], param_names )
]]
report = report .. ( res or '' )
function str._error( error_str )
return res
    local frame = mw.getCurrentFrame();
end
    local error_category = frame.args.error_category or 'שגיאות טיפול במחרוזת';
    local ignore_errors = frame.args.ignore_errors or false;
    local no_category = frame.args.no_category or false;
   
    if str._getBoolean(ignore_errors) then
        return '';
    end
   
    local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>';
    if error_category ~= '' and not str._getBoolean( no_category ) then
    if mw.title.getCurrentTitle().namespace ~= 10 then
        error_str = '[[Category:' .. error_category .. ']]' .. error_str;
        end
    end       
   
    return error_str;
end
 
--[[
Helper Function to interpret boolean strings
]]
function str._getBoolean( boolean_str )
    local boolean_value;
   
    if type( boolean_str ) == 'string' then
        boolean_str = boolean_str:lower();
        if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'
                or boolean_str == '' then
            boolean_value = false;
        else
            boolean_value = true;
        end   
    elseif type( boolean_str ) == 'boolean' then
        boolean_value = boolean_str;
    else
        error( 'No boolean value found' );
    end   
    return boolean_value
end


--[[
-- no option no work.
Helper function that escapes all pattern characters so that they will be treated
if util.table_empty( options ) then return '' end
as plain text.
]]
function str._escapePattern( pattern_str )
    return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
end


--[[
-- get the errors.
contains_any
local violations = calculateViolations( frame, options['doc-subpage'] )
-- special request of bora: use skip_empty_numeric
This function returns the first matched element or empty string
if violations['empty-undeclared-numeric'] then
for i = 1, tonumber( options['skip-empty-numeric'] ) or 0 do  
Usage:
violations['empty-undeclared-numeric'][i] = nil
{{#invoke:String|contains_any|string|search1|search2|search3...}}
Parameters
    1: string
    2...: strings to search within the first string
]]
function str.contains_any( frame )
for i,v in pairs(frame.args) do
if i>1 then
local m=mw.ustring.find( frame.args[1], v, 0, true)
if m then
    return v
    end
end
    end
    return
end
--[[
contains_any_csv
This function returns the first matched element or empty string.
Usage:
{{#invoke:String|contains_any_csv|string|search1,search2,search3}}
Parameters
    1: string
    2: comma seperated list of strings to search within the first string
]]
function str.contains_any_csv( frame )
for word in mw.ustring.gmatch(frame.args[2], '([^,]+)') do
local m=mw.ustring.find( frame.args[1], word, 0, true)
if m then
    return word
  end
    end
    return
end
 
str.rep = function( frame )
local strval, repval = frame.args[1] or '', tonumber( frame.args[2] )
if not repval then return '' end
return string.rep( strval, repval )
end
 
str.join = function(frame)
local res = {}
local sep = ', '
for k,v in pairs(frame.args) do
if k=='sep' then
sep = v
else
if #v>0 then -- avoid empty string
table.insert(res, v)
end
end
end
end
end
return table.concat( res, sep)
end
-- handle ignore list, and prune empty violations - in that order!
local offenders = 0
for name, tab in pairs( violations ) do
-- remove ignored parameters from all violations
for pname in pairs( tab ) do if ignore( pname ) then tab[pname] = nil end end
-- prune empty violations
if util.table_empty( tab ) then violations[name] = nil end
-- WORK IS DONE. report the errors.
-- if report then count it.
if violations[name] and report_params( name, tab ) then offenders = offenders + 1 end
end


str.encode = function(frame)
if offenders > 1 then report_params( 'multiple' ) end
return mw.text.encode( frame.args[1] or "" )
if offenders ~= 0 then report_params( 'any' ) end -- could have tested for empty( report ), but since we count them anyway...
return wrapReport(report, template_name, options)
end
end


str["קידוד"] = str.encode
return {
 
['validateparams'] = validateParams,
return str
['calculateViolations'] = calculateViolations,
['wrapReport'] = wrapReport
}

גרסה מ־20:53, 21 בדצמבר 2021

ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:String/תיעוד

--[=[

This module is based on idea and original code of [[User:IKhitron]].

the source of this module is in //he.wikipedia.org/wiki/Module:ParamValidator

main purpose: use "templatedata" to verify the parameters passed to a template

Terminology: "numeric parameter" means order-based parameter. e.g. if the template is transcluded like so {{x  | k |  | a = m | b = }}
"a" and "b" are "named" parameters, and there are 2 "numeric", or order based parameters, 1 and 2. 
we say that the value of a is "m", the value of 1 is "k", and "b" and 2 are "empty".

This module exports two functions: calculateViolations( frame, subpages ), and validateParams( frame ). 

calculateViolations( frame, subpages ) finds templatedata, in template page or in one of its subpages in the list, if provided.
it returns a table with the violations. if there are none, the table is empty. otherwise it has the structure
{
	violation1 = { param1 = value1, param2 = value2 },
	violation2 = { ... },
	...
}

violation1, violation2 etc. are one of the names of specific violations, as described below. 
param1, param2 etc. are either the names of parameter passed to the template, or defined in templatedata.
value1, value2 etc. are the values passed to the template, or an empty string if no such parameter was passed.

the different violations are as follow:
	* "no-templatedata": 			no valid tempaltedata was found in tempalte page, or documentation subpage
	* "undeclared": 				named parameters with non-empty value, does not exist in templatedata
	* "empty-undeclared": 			named parameters with empty value, does not exist in templatedata
	* "undeclared-numeric": 		numeric parameters with non-empty value, does not exist in templatedata
	* "empty-undeclared-numeric": 	numeric parameters with empty value, does not exist in templatedata
	* "deprecated":  				parameters with non-empty value, marked as "deprecated" in tempaltedata
	* "empty-deprecated":  			parameters with empty value, marked as "deprecated" in tempaltedata
	* "empty-required": 			missing or empty parameter marked as "required" in tempaltedata
	* "incompatible":				a non-empty parameter passed to the template, incompatible with the parameter type defined in templatedata 
	* "duplicate":					a value is passed for the same parameter (or any of its aliases) more than once


The second function, validateParams( frame ), can be called from the tempalte' using #invoke.
it expects a parameter named "options", which contains the definition of the output. typically, it's used by placing something like so:

<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} }}</includeonly>

at the top of the template (be mindful not to add extra spaces and newlines to the template).
to bypass some mediawiki limitation, it is also possible to pass the options as "module", like so (use one of the two, but not both):
<includeonly>{{#invoke:ParamValidator | validateParams | module_options = Module:PV default options}} }}</includeonly>

the first form expects a template named "Template:PV default options" which contains the options, and the 2nd form expects a module, 
suitable for mw.loadData(), which returns a map of namespace => options (i.e. { [0] = <options>, [2] => <options> } .... )

the options parameter should be a JSON-encoded string, defining the output, and some special behaviors. 
the example above assumes that a wiki page named [[Template:PV default options]] exists, and contains valid JSON string. 
for each of the violations defined above, "options" may define an output string, so basically, "options" looks like so:
{
	violation1: outputstring1,
	violation2: outputstring2,
	.... ,
	behavior1: some value,
	....
}

not all violations have to be defined. a violation not defined in "options" will be ignored.

when invoked, it extract "subpages" from the options parameter, and calls:
 calculateViolations( frame, subpages )
if the returned table is empty, no violation were found, and an empty string is returned and nothing else happens.

otherwise, for each of the violations, i.e., the keys of the returned table, when "options" contains this key,
the corresonding value is appended to the output.

some further processing is done:
1) several tokens are replaced with calculated values. these are described below.
2) some "meta" violations are calculated: when any none-ignored violation occured, 
	the "any" meta-violation is added to the output in the same way, 
	i.e. the string keyed by "any" in the options is appended to output with appropriate substitutions.
	similarly, "multiple" meta-violation is created when more than one type of non-ignored violations occured.
3) if the output is not empty, a prefix and suffix strings are prepended and appended to it. 

these are the tokens and the replacement. 
	* "templatename":	full template name, including namespace.
	* "tname_naked":	template name without namespace.
	* "paramname":  	comma-separated list of parameters
	* "paramandvalue": is replaced by comma-separated list of "name: value" pairs of parameters and values
the first two are applied to the whole output, including the suffux and prefix,
and the rest are applied to the individual violations, each with its own list of offending parameters and values.


the rest of the if the value of some keys is null, this error condition will be ignored, and not counted when calculating "any" and "multiple" conditions.

some other optional fields can be passed via options:
	* "doc-subpage": can be either a string, or a list (in square bracktes) of strings, indicating subpages of the template 
			that may contain templatedata. 
	* "ignore": list of patterns. any parameter whose name matches any pattern, will not considered in violation of any of the rules.
	* "skip-empty-numeric": if a quoted number, the module will ignore non-declared empty numeric parameters up to this number
	* "wrapper-prefix": openning wrapper element of outpot (defaults to "<div class = 'paramvalidator-wrapper'>") 
	* "wrapper-suffix": closing wrapper element of output (defaults to "</div>") 

additional option parameters, named options1, options2, etc. can be passed. any entry defined in these options will 
override the previous value. a typical use may be like so:

	
typically, this JSON structure will be placed in a separate template, and retrieved for the module-use as shown above.
<includeonly>{{#invoke:ParamValidator | validateParams | options = {{PV default options}} | options1 = {"key":"value"} }}</includeonly>
"key" can override any of the options fields described above.


]=]

local util = {
	empty = function( s ) 
		return s == nil  or type( s ) == 'string' and mw.text.trim( s ) == ''   
	end
	, 
	extract_options = function( frame, optionsPrefix )
		optionsPrefix = optionsPrefix or 'options' 
		

		local options, n, more = {}
		if frame.args['module_options'] then
			local module_options = mw.loadData( frame.args['module_options'] ) 
			if type( module_options ) ~= 'table' then return {} end
			local title = mw.title.getCurrentTitle()
			local local_ptions = module_options[ title.namespace ] or module_options[ title.nsText ] or {} 
			for k, v in pairs( local_ptions ) do options[k] = v end
		end
		
		repeat
			ok, more = pcall( mw.text.jsonDecode, frame.args[optionsPrefix .. ( n or '' )] )
			if ok and type( more ) == 'table' then
				for k, v in pairs( more ) do options[k] = v end
			end
			n = ( n or 0 ) + 1
		until not ok

		return options
	end
	, 
	build_namelist = function ( template_name, sp )
		local res = { template_name }
		if sp then
			if type( sp ) == 'string' then sp = { sp } end
			for _, p in ipairs( sp ) do table.insert( res, template_name .. '/' .. p ) end
		end
		return res
	end
	,
	table_empty = function( t ) -- normally, test if next(t) is nil, but for some perverse reason, non-empty tables returned by loadData return nil...
		if type( t ) ~= 'table' then return true end
		for a, b in pairs( t ) do return false end
		return true
	end
	,
}

local function _readTemplateData( templateName ) 
	local title = mw.title.makeTitle( 0, templateName )  
	local templateContent = title and title.exists and title:getContent() -- template's raw content
	local capture =  templateContent and mw.ustring.match( templateContent, '<templatedata%s*>(.*)</templatedata%s*>' ) -- templatedata as text
--	capture = capture and mw.ustring.gsub( capture, '"(%d+)"', tonumber ) -- convert "1": {} to 1: {}. frame.args uses numerical indexes for order-based params.
	local trailingComma = capture and mw.ustring.find( capture, ',%s*[%]%}]' ) -- look for ,] or ,} : jsonDecode allows it, but it's verbotten in json
	if capture and not trailingComma then return pcall( mw.text.jsonDecode, capture ) end
	return false
end

local function readTemplateData( templateName )
	if type( templateName ) == 'string' then 
		templateName = { templateName, templateName .. '/' .. docSubPage }
	end
	if type( templateName ) == "table" then
		for _, name in ipairs( templateName ) do
			local td, result = _readTemplateData( name ) 
			if td then return result end
		end
	end
	return nil
end


-- this is the function to be called by other modules. it expects the frame, and then an optional list of subpages, e.g. { "Documentation" }.
-- if second parameter is nil, only tempalte page will be searched for templatedata.
local function calculateViolations( frame, subpages )
-- used for parameter type validy test. keyed by TD 'type' string. values are function(val) returning bool.
	local type_validators = { 
		['number'] = function( s ) return mw.language.getContentLanguage():parseFormattedNumber( s ) end
	}
	
	local function compatible( typ, val )
		local func = type_validators[typ]
		return type( func ) ~= 'function' or util.empty( val ) or func( val )
	end
	
	local function list_empty_or_contains(ar, searched) 
		if not ar or #ar == 0 then return true end 
		for _, val in ipairs(ar) do if val == searched then return true end end
		return false
	end
	
	local t_frame = frame:getParent()
	local t_args, template_name = t_frame.args, t_frame:getTitle()
	local td_source = util.build_namelist( template_name, subpages )
	local templatedata = readTemplateData( td_source )
	local td_params = templatedata and templatedata.params
	local all_aliases, all_series = {}, {}
	
	
	if not td_params then return { ['no-templatedata'] = { [''] = '' } } end
	-- from this point on, we know templatedata is valid.

	local res = {} -- before returning to caller, we'll prune empty tables

	-- allow for aliases
	for _, p in pairs( td_params ) do for _, alias in ipairs( p.aliases or {} ) do 
		all_aliases[alias] = p
		if tonumber(alias) then all_aliases[tonumber(alias)] = p end
	end end

	-- handle undeclared and deprecated
	local already_seen = {}
	local series = frame.args['series']
	for p_name, value in pairs( t_args ) do
		local tp_param, noval, numeric, table_name = td_params[p_name] or all_aliases[p_name], util.empty( value ), tonumber( p_name )
		local hasval = not noval

		if not tp_param and series then -- 2nd chance. check to see if series
			for s_name, p in pairs(td_params) do 
				if mw.ustring.match( p_name, '^' .. s_name .. '%d+' .. '$') then 
					-- mw.log('found p_name '.. p_name .. '  s_name:' .. s_name, ' p is:', p) debugging series support
					tp_param = p 
				end -- don't bother breaking. td always correct.
			end 				
		end
		
		if not tp_param then -- not in TD: this is called undeclared
			-- calculate the relevant table for this undeclared parameter, based on parameter and value types
			table_name = 
				noval and numeric and 'empty-undeclared-numeric' or
				noval and not numeric and 'empty-undeclared' or
				hasval and numeric and 'undeclared-numeric' or
				'undeclared' -- tzvototi nishar.
		else -- in td: test for deprecation and mistype. if deprecated, no further tests
			table_name = tp_param.deprecated and hasval and 'deprecated' 
				or tp_param.deprecated and noval and 'empty-deprecated' 
				or not compatible( tp_param.type, value ) and 'incompatible' 
				or not series and already_seen[tp_param] and hasval and 'duplicate'
				or hasval and not list_empty_or_contains(tp_param.suggestedvalues , value) and 'unsuggested-value'

				
			already_seen[tp_param] = hasval
		end
		-- report it.
		if table_name then 
			res[table_name] = res[table_name] or {}
			res[table_name][p_name] = value 
		end
	end
	
	-- test for empty/missing paraeters declared "required" 
	for p_name, param in pairs( td_params ) do 
		if param.required and util.empty( t_args[p_name] ) then
			local is_alias
			for _, alias in ipairs( param.aliases or {} ) do is_alias = is_alias or not util.empty( t_args[alias] ) end
			if not is_alias then
				res['empty-required'] = res['empty-required'] or {} 
				res['empty-required'][p_name] = '' 
			end
		end
	end
	
	return res
end

-- wraps report in hidden frame
local function wrapReport(report, template_name, options)
	if util.empty( report ) then return '' end
	local naked = mw.title.new( template_name )['text'] 
	
	mw.log(report)
	report = ( options['wrapper-prefix'] or "<div class = 'paramvalidator-wrapper'><span class='paramvalidator-error'>" )
			.. report
			.. ( options['wrapper-suffix'] or "</span></div>" )
	
	report = mw.ustring.gsub( report, 'tname_naked', naked )
	report = mw.ustring.gsub( report, 'templatename', template_name )
	return report
end

-- this is the "user" version, called with {{#invoke:}} returns a string, as defined by the options parameter
local function validateParams( frame )
	
	-- for purple pages:
	if frame:getParent().args['skip parameters validation'] then return '[[ קטגוריה:דפים עם שגיאות פרמטריות שקיבלו חנינה]]' end
	local options, report, template_name = util.extract_options( frame ), '', frame:getParent():getTitle()

	local ignore = function( p_name )
		for _, pattern in ipairs( options['ignore'] or {} ) do
			if mw.ustring.match( p_name, '^' .. pattern .. '$' ) then return true end
		end
		return false
	end

	local replace_macros = function( s, param_names )
		local function concat_and_escape( t ) 
			local s = table.concat( t, ', ' )
			return ( mw.ustring.gsub( s, '%%', '%%%%' ) )
		end
		
		if s and ( type( param_names ) == 'table' ) then
			local k_ar, kv_ar = {}, {}
			for k, v in pairs( param_names ) do
				table.insert( k_ar, k )
				table.insert( kv_ar, k .. ': ' .. v)
			end
			s = mw.ustring.gsub( s, 'paramname', concat_and_escape( k_ar ) ) 
			s = mw.ustring.gsub( s, 'paramandvalue', concat_and_escape( kv_ar ) )
		end
		return s
	end

	local report_params = function( key, param_names )
		local res = replace_macros( options[key], param_names )
		report = report ..  ( res or '' )
		return res
	end

	-- no option no work.
	if util.table_empty( options ) then return '' end

	-- get the errors.
	local violations = calculateViolations( frame, options['doc-subpage'] )
	-- special request of bora: use skip_empty_numeric
	if violations['empty-undeclared-numeric'] then 
		for i = 1, tonumber( options['skip-empty-numeric'] ) or 0 do 
			violations['empty-undeclared-numeric'][i] = nil 
		end
	end
	
	-- handle ignore list, and prune empty violations - in that order!
	local offenders = 0
	for name, tab in pairs( violations ) do 
		-- remove ignored parameters from all violations
		for pname in pairs( tab ) do if ignore( pname ) then tab[pname] = nil end end
		-- prune empty violations
		if util.table_empty( tab ) then violations[name] = nil end
	-- WORK IS DONE. report the errors.
	-- if report then count it.
		if violations[name] and report_params( name, tab ) then offenders = offenders + 1 end 
	end

	if offenders > 1 then report_params( 'multiple' ) end
	if offenders ~= 0 then report_params( 'any' ) end -- could have tested for empty( report ), but since we count them anyway...
	return wrapReport(report, template_name, options)
end

return {
	['validateparams'] = validateParams,
	['calculateViolations'] = calculateViolations,
	['wrapReport'] = wrapReport
}