모듈:위키데이터IB
Module![]() | 이 모듈은 페이지 보호 대상입니다.매우 많은 페이지에서 사용하는 눈에 잘 띄는 모듈이거나 매우 자주 교체됩니다.파손이나 실수는 많은 페이지에 영향을 미치며 사소한 편집에도 서버에 상당한 부하가 걸릴 수 있기 때문에 편집으로부터 보호됩니다. |
![]() | 이 루아 모듈은 전체 페이지의 약 3%인 약 150만 페이지에 사용됩니다. 중대한 중단과 서버 부하를 방지하기 위해 모듈의 /샌드박스 또는 /테스트 케이스 하위 페이지 또는 자체 모듈 샌드박스에서 변경 사항을 테스트해야 합니다.테스트된 변경 내용을 한 번의 편집으로 이 페이지에 추가할 수 있습니다.실행하기 전에 토크 페이지에서 변경 사항에 대해 논의하는 것을 고려합니다. |
![]() | 이 모듈의 보다 사용자 친화적인 래퍼는 {{wdib}}을(를) 참조하십시오. |
이 모듈은 {{infobox}}(Wikidata 문자) 내부에서 사용하도록 설계되었습니다.IB는 인포박스(Info Box) 또는 기타 템플릿을 의미하며 (기사가 사용하는 인포박스의 편집자와는 달리) 기사의 편집자가 위키데이터 값을 표시하는지 여부를 제어할 수 있도록 특별히 설계되었습니다.
두 샌드박스 중 하나는 사소한 수정 사항 외에 테스트에 사용해야 합니다.
메인 모듈과 두 샌드박스에 대한 테스트 예제를 이용할 수 있습니다.
모듈 | 시험사례 | |
---|---|---|
주된 | 모듈: WikidataIB | 모듈 대화:위키데이터IB/테스트 |
샌드박스 | 모듈: WikidataIB/샌드박스(디프) | 모듈 대화:위키데이터IB/샌드박스/테스트(diff) |
샌드박스1 | 모듈: WikidataIB/샌드박스1(디프) | 모듈 대화:위키데이터IB/샌드박스1/테스트(디프) |
개요
모듈은 현재 정보 상자에서 사용할 수 있도록 다음 호출을 제공합니다.
getValue
- main call, 주어진 속성의 값을 가져오는 데 사용getQualifierValue
- 주어진: (1) 속성; (2) 해당 값; (3) 한정자의 속성ID, 일치하는 값을 반환합니다.getValueByQual
지정된 엔터티 값을 가진 한정자가 있는 속성의 값을 가져옵니다.getValueByLang
값이 지정된 언어 코드를 가진 P407("일의 언어 또는 이름") 한정자를 가진 속성의 값을 가져옵니다.getValueByRefSource
값이 지정된 엔티티 ID를 가진 참조 "stated in"(P248)을 가진 속성의 값을 가져옵니다.getPropOfProp
prop1의 값이 "wikibase-item" 유형일 경우 각 wikbase의 prop2 값을 반환합니다.getAwardCat
항목에 P166(수령)의 값이 있는 경우 P2517(이 상을 받는 사람의 범주)의 각 상을 검사하고 해당 범주를 반환합니다. 항목의 P734(가족 이름)를 정렬 키로 하거나 가족 이름이 없는 경우 정렬 키가 없습니다.getIntersectCat
prop1의 각 값에 대해 값의 주 범주를 가져온 다음 prop2의 각 값을 가져온 다음 해당 속성의 교집합을 나타내는 모든 범주를 반환합니다.getSumOfParts
는 속성 'has part'(P527)에서 목록과 일치하는 값을 검색합니다.일치하는 값에 한정자 '수량'이 있는 경우(P1114), 해당 수량은 합산되어 반환됩니다(단, 0은 0을 반환함).getCoords
좌표를 가져와 {{Coord}}을(를) 통과합니다.getPreferredValue
- 이전 버전과의 호환성을 위해 더 이상 사용하지 않습니다.사용.getValue rank=best
매개 변수 대신
를 사용하여 동일한 작업을 수행할 수 있는 getValue에 중복되므로 이제 오래된 호출 getSourcedValue가 제거되었습니다. onlysourced=true
parameter(기본 설정).
유틸리티 기능
getLink
로컬 Wiki에 기사에 대한 사이트 링크가 있으면 Wikidata 레이블이 표시된 텍스트로 기사에 대한 링크를 반환합니다.사이트 링크가 없는 경우 레이블을 일반 텍스트로 반환합니다.로컬 언어에 레이블이 없는 경우 entity-ID를 반환합니다.getAT
(기사 제목) 로컬 위키에 기사에 대한 사이트 링크가 있으면 사이트 링크를 일반 텍스트로 반환하고, 그렇지 않으면 아무것도 반환하지 않습니다.getSiteLink
지정된 위키의 기사에 대한 일반 텍스트 링크를 가져옵니다.getLabel
로컬 언어에 대한 Wikidata 레이블을 일반 텍스트로 반환합니다.로컬 언어에 레이블이 없는 경우 entity-ID를 반환합니다.getAllLabels
레이블 집합을 가져와 Wikitext로 표시할 수 있도록 형식을 지정합니다.labelorid
모든 wikitext가 제거된 레이블을 반환하거나 레이블이 없는 경우 entity-ID를 반환합니다.getDescription
로컬 매개 변수가 "Wikidata"인 경우 Wikidata 엔티티에 대한 아티클 설명을 반환합니다.getAllDescriptions
설명 집합을 가져와 위키텍스트로 표시할 수 있도록 형식을 지정합니다.getAliases
현재 또는 지정된 언어로 엔티티에 대한 별칭을 반환합니다.getAllAliases
별칭 집합을 가져와 Wikitext로 표시할 형식을 지정합니다.pageId
현재 페이지의 연결된 Wikidata 페이지 ID(entity-ID, Q-number)를 반환합니다.formatDate
mw에서 일반 형식의 날짜 시간을 가져옵니다.wikibase.entity:formatPropertyValues와 df(날짜 형식) 및 bc 매개 변수에 따라 포맷합니다.formatNumber
제공된 언어 코드에 따라 숫자를 포맷합니다.checkBlacklist
필드가 블랙리스트에 없는 경우 true를 반환합니다(즉, 허용됨).emptyor
매개 변수가 구두점, 공백 또는 html 태그일 경우 nil을 반환하고, 그렇지 않으면 변경되지 않은 인수를 반환합니다.getLang
MediaWiki 언어 코드 또는 현재 콘텐츠의 전체 언어 이름을 반환합니다.getItemLangCode
국가를 찾습니다(P17). 그 다음 해당 국가의 공용어를 찾습니다(P37). 언어 코드를 반환합니다(P424).findLanguage
유효한 경우 (1) 제공 언어를 반환하거나, (2) 사용자의 설정 언어를 반환하거나, (3) 현재 위키의 언어를 반환합니다.getQid
(1) 제공된 경우 entity-ID를 반환하거나, (2) "카테고리의 주 주제(P301)"의 entity ID를 반환하거나, (3) 현재 페이지와 연관된 entity ID를 반환하거나, (4) 아무것도 반환하지 않습니다.followQid
속성 목록이 주어지면, 각 속성을 차례로 찾아 일치하는 첫 번째 값의 entity-ID를 반환합니다(선택적으로 일치하는 모든 entity-ID를 반환합니다).getGlobe
P625(좌표 위치)에서 사용되는 지구의 entity-ID를 반환하거나, 없는 경우 0을 반환합니다.getCommonsLink
연결된 위키데이터 항목의 커먼즈 사이트 링크; 연결된 위키데이터 항목의 주제의 주 카테고리의 커먼즈 사이트 링크siteID
globalSite의 루트를 반환합니다.예를 들어 enwiki, enwiki 소스, en-gb 등의 ID.projID
siteID와 같음location
현재 위치에서 상위 위치의 체인을 따라 위쪽으로 스캔하여 국가에 도달할 때까지 각 위치를 반환합니다.examine
지정된 속성의 형식화된 덤프를 반환합니다.url2
적절한 URL인 매개 변수를 사용하여 인포박스에서 사용할 수 있도록 포맷합니다. 이 매개 변수는 자신의 출력을 입력으로 받아들입니다.getWebsite
공식 웹 사이트(P856)를 가져와 인포박스에서 사용할 수 있도록 포맷합니다.checkvalue
지정된 entity-ID에 대한 속성을 값으로 검색하고 발견된 경우 해당 entity-ID를 반환합니다. 그렇지 않은 경우 0checkValidity
이름 없는 첫 번째 매개 변수가 유효한 엔티티-id를 나타내는지 여부를 반환합니다.showNoLinks
링크해서는 안 되는 기사 제목을 표시합니다.
호출 예제
{{#invoke:위키데이터IB get 값 < 속성ID> name=<fieldname> suppress fields=<표시되지 않을 필드 목록> fetchwikidata=<Wikidata에서 값을 가져올 필드 목록> onlysourced=<yes/no> noicon=<yes/no> df=<dmy/mdy/y> bc=<BC/BCE> qual=<ALL/DATES/P999> list=<ubl/hlist/ prose> linked=<yes/no><local parameter>}
{{#invoke:위키데이터IB getCoords name=<fieldname> suppress fields=<표시되지 않을 필드 목록> fetchwikidata=<Wikidata에서 값을 가져올 필드 목록><local parameter>}
{{#invoke:위키데이터IBgetQualifier 값 <속성ID> pval=<속성에 대한 대상 값 ID > qual=<대상 값에 대한 qualifier ID > name=<fieldname> suppress fields=<표시되지 않을 필드 목록> fetchwikidata=<Wikidata에서 값을 가져올 필드 목록> onlysourced=<yes/no>}
{{#invoke:위키데이터IB get Value ByQual <속성ID> 자격ID=<일치할 한정자 속성 ID> qvalue=<Q한정자 속성> name=<fieldname> suppress fields=<표시되지 않을 필드 목록> fetchwikidata=<Wikidata에서 값을 가져올 필드 목록> onlysourced=<yes/no>}
{{#invoke:위키데이터IB get Value by Lang <속성ID> lang=<matching language code> name=<fieldname> suppress fields=<표시되지 않을 필드 목록> fetchwikidata=<Wikidata에서 값을 가져올 필드 목록> only sourced=<yes/no>}
함수 getValue
값을 가져올 모수
이름. | 별칭 | 기능. | 체납 |
---|---|---|---|
(처음 이름 미정) | 1 | 값이 반환되는 property-ID.필수의. | |
(두번째 이름 없음) | 2 | 로컬에서 제공한 값으로, 비어 있지 않은 경우 Wikidata의 값보다 우선하여 반환됩니다. | 빈 |
qid | 속성이 속한 엔티티의 Q-number(entity-ID)입니다.제공되지 않거나 비어 있으면 현재 페이지의 관련 Wikidata 항목이 기본값으로 설정됩니다. 이 항목은 mw를 사용합니다.wikibase.getEntityIdForCurrentPage(). | 현재페이지의항목ID | |
이드 | qid의 대안.제외하고는eid , 값을 얻기 위한 모든 매개 변수는 nil과 빈 문자열을 동일하게 처리합니다.그래서 세팅을 x= 매개 변수를 생략한 것과 동일한 결과를 제공합니다.그러나 다른 모듈과의 호환성을 제공하기 위해서는 eid= 생략하는 동안 항상 빈 문자열을 반환합니다.eid 허용한다qid 정상적으로 일하기 위해서입니다. | 현재페이지의항목ID | |
순위 | [대소문자 구분 안 함]으로 설정하면best , 기본값이 있으면 기본값을 반환하고, 없으면 일반값을 반환합니다.로 설정할 경우preferred 기본 설정 값을 반환합니다.로 설정할 경우normal , 정규 값을 반환합니다.로 설정할 경우deprecated 감가 상각된 값을 반환합니다."b"로 시작하는 모든 매개 변수 값은 "best", "p"로 시작하는 "preferred", "n"으로 시작하는 "normal", "d"로 시작하는 모든 매개 변수 값은 "best"입니다.여러 개의 값이 허용됩니다. "pnd"는 모든 순위를 반환합니다."Best"는 다른 플래그보다 우선합니다.다른 값은 무시되며 순위가 요청되지 않으면 선호 및 정상이 반환됩니다. | 선호하는 정상적인 | |
자질이 있는 | 속성 뒤에 괄호로 반환되는 한정자의 속성 ID를 구두점으로 구분한 목록입니다.세팅qual=ALL 모든 한정자를 반환합니다.세팅qual=DATES 날짜 구분 기호가 있는 시작 시간(P580) 및 종료 시간(P582)을 반환합니다. | 없음. | |
quals만 | qo | 속성 값이나 괄호 없이 한정자만 표시할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
위키데이터를 가져오다 | fwd | 값을 가져올 필드 목록입니다.ALL 모든 필드를 가져옵니다.의 가치.NONE 또는 공백이거나 매개 변수를 생략하면 필드가 나타나지 않습니다. | 없음. |
밭을 막다 | spf | 표시되지 않는 필드 목록입니다.이렇게 하면 필드의 로컬 값이 표시되지 않을 수도 있습니다. | 없음. |
이름. | 필드 이름입니다.인포박스를 인코딩할 때, 이 이름은 fetchwikidata 및 suppress 필드가 인식할 이름입니다.fetchwikidata(페치위키 데이터) 또는 suppress 필드(suppress fields)가 지정된 경우 필요합니다.fetchwikidata=ALL ). | 0의 | |
소스만 있는 | osd | 출처가 없거나 위키백과에만 출처가 있는 위키데이터 값을 걸러내는 부울입니다.이 2018 RFC에서는 기사 정보 상자에 표시된 Wikidata 값을 출처로 표시해야 합니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 진실의 |
df | 날짜 형식: 일 수 있습니다.dmy (달의 하루 전) 또는mdy (월전일) 또는y (1년 동안만). | dmy | |
qdf | 한정자의 날짜 형식입니다.생략할 경우 매개변수로 기본 설정됩니다.df , 또는 "y"인 경우df 또한 생략합니다. | "y"에 대한 df 값 | |
bc | 날짜에 대한 BC/BCE 접미사의 형식입니다. | BCE | |
평범한 날짜 | pd | 날짜 형식을 수정할 문자열입니다."true"/"yes"/"1"을 설정하면 "sourcing circumners"(P1480) 및 링크 추가가 비활성화됩니다."adj"를 설정하는 것은 동일하지만 날짜의 형용사 형식을 사용합니다. | 거짓의 |
연결된 | Wikidata의 사이트 링크를 통해 로컬 페이지에 대한 링크를 활성화하는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 진실의 | |
표시 텍스트 | dt | 링크된 항목이 비어 있지 않은 경우 표시된 텍스트를 재정의하는 문자열입니다. | 빈 |
단명 | sn | 연결된 항목에 레이블 대신 짧은 이름(P1813)을 사용할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
라벨을 사용합니다 | 쓸모없는 | 연결된 항목에 대해 명확하지 않은 사이트 링크 대신 레이블을 강제로 표시하는 부울입니다.라벨은 사이트 링크를 연결하는 공공 기물 파손의 가능성이 훨씬 높습니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
wdlinks | wdl | 로컬 문서가 없을 때 Wikidata 링크를 표시할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
단위 abbr | uabbr | 공통 단위에 대한 단위 약어를 활성화하는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
개종시키다 | 회심의 | 템플릿에 수량 전달을 가능하게 하는 부울:Cvt. 값no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
부대를 나타내다 | su | 수량 단위를 표시할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 진실의 |
규모. | 수량 형식의 스케일링을 설정하는 문자열입니다.값은 "a"=자동, "0"=스케일링 없음, "3"=천, "6"=백만, "9"=억, "12"=trillion입니다. | 0 | |
최대치 | 여러 값을 사용할 수 있을 때 반환할 최대 값 수를 설정합니다.1로 설정하면 반환된 문자열이 다른 통화(예: 이미지) 내에서 사용되는 경우에 유용합니다.가치0 그리고 empty는 모든 값으로 반환합니다. | 0(전부) | |
무너지다 | 콘텐츠가 자동으로 축소되기 전에 반환할 최대 값 수를 설정합니다.가치0 모든 콘텐츠를 축소되지 않고 표시할 수 있도록 허용합니다. | 0(전부) | |
연결 접두사 | lp | 링크될 때 링크 값 앞에 붙는 링크 접두사.기사 및 문자열(예: url)이 있는 항목에만 적용됩니다.문자열의 연결을 트리거합니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다. | 빈 |
링크 포스트픽스 | 링크된 경우 링크된 값에 추가되는 링크 포스트픽스입니다.기사 및 문자열(예: url)이 있는 항목에만 적용됩니다.문자열의 연결을 트리거합니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다. | 빈 | |
접두어 | 표시된 문자열 값 앞에 붙는 접두사(예: url)입니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다. | 빈 | |
사후 수정 | 표시된 문자열 값(예: url)에 추가되는 포스트픽스입니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다. | 빈 | |
qlink 접두사 | qlp | 한정자 링크 접두사(링크 접두사 참조). | 빈 |
qlink 포스트픽스 | 한정자 링크 포스트픽스(링크 포스트픽스 참조). | 빈 | |
qprefix | 한정자 접두사(접두사 참조). | 빈 | |
qpostfix | 한정자 후 수정(후 수정 참조). | 빈 | |
분류된 | 반환된 값을 정렬할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 | |
qsorted의 | 반환되는 각 항목 내에서 한정자 값을 정렬할 수 있는 부울입니다.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 | |
노아이콘 | 후행 "edit at Wikidata" 펜 아이콘을 억제하는 부울입니다.반환된 값을 추가로 처리할 때 유용합니다.가치no ,false 그리고.0 모두 거짓입니다(즉, 아이콘을 표시함). 그 밖의 모든 것은 참입니다(즉, 아이콘을 억제함). | 거짓의 | |
목록. | 그런 다음 여러 값의 목록이 전달되는 템플릿의 이름입니다.예를 들어 "cslist", "hlist", "ubl", "blist", "olist", "p-1" 등이 있습니다.특별한 가치,prose , "1, 2, 3, 4"를 생산합니다. | 없음. | |
셉 | 반환된 여러 값을 구분하는 데 사용되는 문자열을 사용자 지정합니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다.아무것도 전달하지 않거나 빈 문자열이 전달되지 않으면 기본 목록 구분자(", "영어로")로 설정됩니다. | ", " | |
qsep | 반환된 여러 한정자 값을 구분하는 데 사용되는 문자열을 사용자 지정합니다.큰따옴표 "는 공백을 통과할 수 있도록 제거됩니다.아무것도 전달하지 않거나 빈 문자열이 전달되지 않으면 기본 목록 구분자(", "영어로")로 설정됩니다. | ", " | |
체재를 갖추다 | 전역 좌표를 도/분/초 또는 십진도로 렌더링할지 결정합니다."dec"(대소문자 구분 없음)로 시작하는 값은 모두 10진수로 표시됩니다.다른 것은 DMS로 렌더링됩니다. | dms | |
선보이다 | 전역 좌표를 반환할 방법을 결정합니다."long lat" 값이 반환됩니다.longitude, latitude . "lon"(대소문자 구분 없음)으로 시작하는 다른 값은 경도만 반환됩니다."lat"(대소문자 구분 없음)로 시작하는 값은 위도만 반환됩니다.와 함께 사용할 경우 noicon=true , 이 모든 숫자는 10진수(서명: N과 E가 양으로 표시됨)로, 매핑 템플릿 등에 사용하기 위한 것입니다.다른 값(또는 아무것도)은 "NSEW" 한정자 등을 사용하여 일반 좌표 값을 DMS 또는 10진수로 렌더링합니다. | 빈 | |
랭 | 선택한 언어로 연결되지 않은 값을 반환할 수 있습니다.MediaWiki에서 인식하는 표준 ISO 언어 코드를 사용합니다.제공되지 않거나 공백인 경우 로컬 언어(또는 다중 언어 위키의 설정 언어)가 정상적으로 사용됩니다. | 현지어 | |
매개변수 집합 | ps | 일반적으로 사용되는 매개변수 집합을 단일 매개변수로 지정할 수 있는 편의 매개변수: ps=1은 가능한 한 간단한 연결값을 얻고 ps=2는 일반 텍스트 값을 나타냅니다.매개변수 집합을 참조합니다. | |
링크레디르 | 값에 대한 사이트 링크가 Wikidata에 없을 때 레이블과 동일한 이름의 리디렉션에 대한 확인을 켜거나 끄는 부울.가치no ,false 그리고.0 모두 거짓입니다. 그 밖의 모든 것은 참입니다. | 거짓의 |
기본 매개변수
- getValue 또한 명명된 매개 변수를 사용할 수 있습니다.
qid=
이것은 기사의 위키데이터 ID입니다.이것은 일반적으로 현재 기사의 기본값을 생략한 것으로 사용되지 않습니다. - 값을 반환할 속성은 이름이 없는 첫 번째 속성으로 전달되며 필요합니다.
- 이름이 없는 두 번째 매개 변수(제공된 경우)는 반환된 값이 되며 Wikidata에 대한 호출은 이루어지지 않습니다.
화이트리스트 및 블랙리스트
- 이 함수가 호출되는 필드의 이름이 명명된 매개 변수에 전달됩니다.
name=
, 처음에는 절대로 표시할 수 없는 필드의 블랙리스트에 대해 확인됩니다(즉, 모든 상황에서 호출이 0으로 반환되어야 함).필드가 블랙리스트에 없으면 화이트리스트에 대해 확인됩니다.필드 이름이 일치하는 경우 호출은 두 번째 이름 없는 매개 변수로 지정된 경우 로컬에서 제공된 값을 반환하고, 그렇지 않은 경우에는 Wikidata 값을 반환합니다. - 지정하기
fetchwikidata=ALL
는 블랙리스트에 포함되지 않은 모든 필드를 반환하는 바로 가기입니다. - 블랙리스트 또는 화이트리스트를 사용할 때 이름은 필수이므로 모듈이 제공되지 않으면 0을 반환합니다.
fetchwikidata=ALL
. - 블랙리스트는 명명된 매개 변수로 전달됩니다.
suppressfields=
- 화이트리스트는 명명된 매개 변수로 전달됩니다.
fetchwikidata=
소싱
getValue 함수는 부울 파라미터를 받아들입니다.onlysourced
이것은 출처가 없거나 위키미디어 프로젝트에만 출처가 있는 위키데이터 값의 반환을 억제합니다.파라미터 부재, 빈 파라미터 ( onlysourced=
) 및 빈 문자열(""
) 모든 기본값이 true로 설정됩니다(예: 참조된 값만 반환됨).그 값들은no
,false
그리고.0
거짓으로 처리됩니다(즉, 모든 값이 반환됨). 다른 값은 참입니다(단, onlysourced=yes/no
가독성을 위해 권장됩니다).
Wikidata 링크
getValue 함수는 부울 파라미터를 받아들입니다.noicon
후행 "edit at Wikidata" 아이콘을 억제하고 반환된 값이 infobox(예: url)에 의해 추가로 처리되는 경우에 대한 링크입니다.매개 변수가 없거나 빈 매개 변수가 없습니다( noicon=
) 기본값은 false입니다(즉, 아이콘이 추가됨).빈 문자열(""
) 및 값no
,false
그리고.0
거짓으로 취급되며, 다른 값은 참입니다(단, noicon=true
가독성을 위해 권장됩니다).
모듈에서 진행된 토론에 이어 다음을 수행합니다.위키데이터IB #Visibility of pen 아이콘, 펜 아이콘은 자동으로 확인되지 않는 사용자로부터 숨겨집니다.이것은 대부분의 독자들이 펜 아이콘을 보지 못한다는 것을 의미하며, 한편으로는 위키데이터의 미학과 공공 기물 파손, 다른 한편으로는 위키데이터 편집을 장려하는 것 사이의 균형을 나타냅니다.
날짜
mdy, dmy 또는 just year 형식의 날짜 요구 사항을 처리하기 위해 getValue는 명명된 매개 변수를 받아들입니다. df=
"dmy", "mdy" 또는 "y" 값을 사용할 수 있습니다. - 기본값은 "dmy"입니다.
아티클에 접미사 BC 및 BCE 중 하나가 필요할 수 있으므로 getValue는 명명된 매개 변수를 허용합니다. bc=
값 "BC" 또는 "BCE" - 기본값은 "BCE"입니다.일부 테스트 사례는 모듈 토크에서 볼 수 있습니다.위키데이터IB/testing #Calls to get Value for date.
순위
그 rank=
parameter를 preferred로 설정하면 선호하는 값만 반환하고, normal로 설정하면 normal 값만 반환하고, decreated로 설정하면 decreated 값만 반환합니다.매개 변수가 best로 설정되면 선호하는 값이 있으면 반환되고 그렇지 않으면 정상 값이 반환됩니다."p"로 시작하는 모든 매개 변수 값은 "preferred", "n"으로 시작하는 모든 매개 변수 값은 "normal", "d"로 시작하는 모든 매개 변수 값은 "decrecated", "b"로 시작하는 모든 매개 변수 값은 "best"입니다.예를 들어, 값의 조합이 허용됩니다. rank=p n
는 모든 선호 및 정규 값(기본값)을 반환하지만, "best"는 다른 매개 변수를 재정의합니다.
특정 값 유형 핸들러
모듈에는 다음 데이터 유형에 대한 특정 핸들러가 있습니다.
- 위키백과의 일부 기사에 해당하는 항목을 "위키베이스 항목"이라고 합니다.가능한 경우 영어 위키백과에 해당하는 기사로 연결됩니다.
- 날짜를 나타내는 항목입니다.수세기, 년, 년 및 월 또는 년, 월 및 일일 수 있습니다.
- Commons 미디어, URL, 외부 ID 또는 기타 일반 텍스트를 나타내는 항목입니다.
- 수량을 나타내는 항목.이들은 모두 관련 단위를 갖거나 무차원일 수 있으며 범위를 가질 수 있습니다.
- 전역 좌표를 나타내는 항목입니다.이 값은 위도와 경도로 표시되며 관련 정밀도를 갖습니다.
다른 유형의 데이터를 나타내는 항목은 현재 취급하지 않습니다.
데이터 유형의 세 번째 클래스는 다음 파라미터와 함께 사용할 수 있습니다.
prefix=
,postfix=
,linkprefix=
,linkpostfix=
만약 당신이 적어도 하나를 공급하지 않는다면, linkprefix=
아니면 linkpostfix=
, 그다음에 prefix=
그리고. postfix=
사용됩니다.예를 들어, 비엔나 천문대(Q532127)에서 Minor Planet Center 천문대 코드(P717)를 얻을 때:
{{#invoke:WikidataIB/sandbox getValue P717 fetchwikidata=ALL onlysourced=no prefix="before " postfix=" after" qid=Q532127}}
→ 045년도 이전에
매개 변수 값에 선행 공백 또는 후행 공백이 있는 경우에는 이중 따옴표를 사용하여 매개 변수 값을 묶습니다(그렇지 않으면 제거됨).공급하는 경우 linkprefix=
아니면 linkpostfix=
, 그런 다음 4개의 파라미터를 모두 사용하고 각 값에 대해 다음과 같이 링크를 만듭니다.
[[ linkprefix WikidataValue1 linkpostfix prefix WikidataValue1 postfix]], [[ linkprefix WikidataValue2 linkpostfix prefix WikidataValue2 postfix]], etc.
이를 통해 관측소 코드 목록과 같은 목록 문서의 다른 섹션에 대한 여러 링크를 만들 수 있습니다.예를 들어, 비엔나 천문대(Q532127)에서 소행성 센터 천문대 코드(P717)를 얻으면 다음과 같은 링크를 만들 수 있습니다.
{{#invoke:WikidataIB/sandbox getValue P717 fetchwikidata=ALL onlysourced=no prefix= postfix= linkprefix="List of observatory codes#" linkpostfix= qid=Q532127}}
→ [관측소 코드 목록 #045045]
매개변수들은 prefix=
, postfix=
, linkprefix=
, linkpostfix=
링크되어 있는 경우 위키베이스-items에도 적용됩니다.
반환된 여러 값 형식 지정
sorted=<yes no>
는 반환된 값을 정렬할 수 있도록 전달된 부울입니다.매개변수 없음, 빈 문자열, "false", "no" 또는 "0"은 정렬을 비활성화합니다.아주 바보 같은 알파벳 정렬일 뿐이고 연결된 값을 "[...]"로 정렬합니다.sep=<separator characters>
여러 반환된 값 사이의 구분자를 정의할 수 있습니다.기본값은", "
(comma + 일반 공간).구분자에 선행 또는 후행 공백이 있는 경우에는 큰따옴표로 묶습니다(예:sep=" - "
). 큰따옴표는 구분 기호에서 제거됩니다.파이프 문자({{!}}
. 접근성의 이유로(MOS:PLIST 참조), 를 사용하지 마십시오.sep=<br>
수직 언블렛 목록의 경우, 사용list=ubl
대신.list=<prose cslist hlist ubl blist olist>
반환된 여러 값을 "and"로 구분한 마지막 두 값을 문장으로 표시할 수 있습니다(list=prose
), 가로 쉼표로 구분된 목록 (list=cslist
, 산문에 사용되지 않음), 가로 목록(list=hlist
), 수직 언블렛 리스트 ( )list=ubl
), 세로 글머리 기호 목록( )list=blist
, 또는 세로 순서 목록 ( )list=olist
구분 기호를 무시하고 "Edit at Wikidata"에 연결된 '펜 아이콘'은 표시되지 않습니다.list=p-1
마지막 값을 표시합니다.와 결합합니다.maxvals=n
n번째 값을 표시합니다.
반환된 값 제한
때로는 속성이 이미지(P18)와 같이 단일 값을 가질 것으로 예상되지만 Wikidata에서는 여러 값을 가질 수 있습니다.세팅 maxvals=1
반환되는 값의 수를 1로 제한합니다.다른 값은 가능하며 예상대로 작동하지만 0은 "제한 없음"으로 처리됩니다.
연결 해제
로컬 위키의 기사를 나타내는 반환된 값은 기본적으로 연결됩니다.여기에는 리디렉션이 포함되지만 탭 페이지는 포함되지 않습니다.반환된 값을 링크하지 않아야 하는 경우가 있으며 이는 설정을 통해 수행될 수 있습니다. linked=no
.
단위 약어
반환된 값이 수량일 경우, 그 값이 표현되는 단위의 이름이 추가됩니다.인포박스에서는 공통 단위 대신 약어를 사용하고자 할 수 있습니다.설정으로 할 수 있습니다. unitabbr=true
.
예선자
매개변수 qual=
를 제공할 수 있으며, 이를 통해 필요한 속성의 한정자가 존재할 경우 반환됩니다.값이 속성 ID의 구두점으로 구분된 목록(예: P123, P456)으로 설정되면 해당 속성을 가진 한정자 값만 반환됩니다.값이 다음으로 설정된 경우 qual=ALL
, 그러면 모든 한정자 값이 반환됩니다.값이 다음으로 설정된 경우 qual=DATES
그런 다음 속성의 시작 시간(P580)과 종료 시간(P582)이 날짜 구분자와 함께 반환됩니다.각 경우 반환되는 한정자 값은 속성 값을 따르며 괄호 안에 포함됩니다.여러 한정자 값을 반환하는 경우 기본적으로 쉼표로 구분되지만 구분자는 다음을 지정하여 변경할 수 있습니다. qsep=
(공간을 포함할 수 있도록 벗겨낸 이중 quotes로 둘러싸일 수 있습니다.)파라미터 설정 qsorted=yes
는 반환된 한정자 값을 영숫자로 정렬합니다.
파라미터의 짧은 형태
더 긴 매개변수 중 일부는 인포박스 설계를 보다 압축적으로 만들기 위해 축약될 수 있습니다.
fwd → fetchwikidata
osd → onlysourced
spf → suppressfields
wdl → wdlinks
매개변수 집합
일반적으로.getValue
편집자의 합의 결정을 나타내는 매개 변수에 대한 일련의 기본값이 있습니다.예를들면, onlysourced=
기본값:true
따라서 "Wikipedia" 보다 더 나은 것에 출처를 둔 Wikidata 값만 반환됩니다. fetchwikidata=
기본값:none
따라서 일부 필드 이름 또는 "ALL"을 설정하여 활성화할 때까지 아무것도 반환되지 않습니다.이는 장애 방지 상태를 나타내며, 해당 기사에 대해 활성화될 때까지 기사를 변경하지 않고 정보 상자를 Wikidata 지원으로 만들 수 있습니다.
사용을 단순화하기 위해getValue
다른 상황에서, 파라미터들의 공통적인 조합들은 다음과 같이 지정될 수 있습니다. parameterset=
혹은 그 가명을 ps=
편의상현재 두 가지 조합이 구현되어 있으며 다음과 같습니다.
- ps=1
- 가능한 경우 연결된 단순한 값을 얻기 위한 일반적인 재정의 집합:
순위 ="최고" fetchwikidata="ALL"은(는) ="아니오" noicon ="true"만 소싱했습니다.
- ps=2
- 일반 텍스트의 일종의 원시 값:
순위 = "최고" fetchwikidata = "ALL"만 소스 = "no" no 아이콘 = "true" linked = "no" plaindate = "true"
수요가 있는 경우 다른 세트를 생성할 수 있습니다.
포장지 템플릿
템플릿 {{wdib}}을(를) 편리한 포장지로 사용할 수 있습니다.{{#invoke:WikidataIB getValue}}
.
기타주요기능
함수 getPreferredValue
getPreferredValue 함수는 getValue와 동일한 매개 변수를 사용하여 작동하지만 속성에 대한 값 중 선호 순위가 설정된 값이 있으면 해당 값만 반환합니다.이것은 현재 다음과 같이 더 이상 사용되지 않습니다.getValue rank=best
.
함수 getCoords
- getCoords는 명명된 매개변수를 취할 수도 있습니다.
qid=
이것은 기사의 위키데이터 ID입니다.이것은 일반적으로 현재 기사의 기본값을 생략한 것으로 사용되지 않습니다. - 이름이 지정되지 않은 첫 번째 매개 변수가 제공된 경우 반환된 값이 되며 Wikidata에 대한 호출이 이루어지지 않습니다.
- Wikidata의 좌표는 구문 분석되어 템플릿으로 전달됩니다.수동으로 호출한 것처럼 디스플레이를 반환하는 좌표입니다.
- 절대 표시되지 않는 필드의 블랙리스트 및 화이트리스트는 forgetValue 사용과 동일한 방식으로 구현됩니다.
suppressfields=
그리고.fetchwikidata=
- 그
format
parameter는 디스플레이 형식을 decimal 또는 dms로 설정합니다."dec"로 시작하는 값은 10진수로 설정하고, 그 외의 값은 dms로 설정합니다. - 그
display
parameter는 디스플레이 위치를 "inline", "title" 또는 "inline, 제목"으로 설정합니다.기본값은 아무것도 아닙니다(따라서 현재 "inline"인 {{Coord}}의 경우 기본값을 사용합니다).
함수 getQualifier 값
getQualifierValue 함수는 한정자 값을 가져올 때 사용합니다.우리는 한정자와 관련된 속성과 속성의 값을 알아야 합니다.매개 변수는 다음과 같습니다.
- 이름 없는 매개 변수에 전달된 속성 ID(또는
1=
) - 의 해당 속성에 대한 목표 값
pval=
- 의 해당 대상 값에 대한 한정자 ID
qual=
- 속성의 화이트리스트 및 블랙리스트를 ingetValue와 동일하게 구현하는 매개 변수
- 속성의 원본 값만 반환되는지 여부를 지정하는 선택적 부울입니다(기본값은 "아니오"입니다.
onlysourced=
- 에서 임의 접근을 위한 선택 항목 ID
qid=
- getValue에서와 동일한 형식의 출력 매개변수
getQualifier 값 예제
남극 망원경(Q1513315)에는 값 구성(Q385378)이 있는 속성 중요 이벤트(P793)가 있습니다.시작 시간(P580)과 종료 시간(P582)의 두 가지 한정자가 있습니다.시작 날짜 가져오기
{{#invoke:WikidataIB getQualifierValue qid=Q1513315 P793 pval=Q385378 qual=P580 name=xyz fetchwikidata=ALL }}
남극 망원경에서는 다음과 같이 반환됩니다.
- 2006년11월
함수 getValueByQual
getValueByQual 함수는 지정된 엔터티 값을 가진 한정자가 있는 속성의 값을 반환합니다.매개 변수는 다음과 같습니다.
- 이름 없는 매개 변수에 전달된 속성 ID(또는
1=
) - 의 한정자(또는 "ALL" 또는 "DATES")에 대한 속성 ID
qualID=
- 의 해당 한정자에 대한 값의 Wikibase-entity
qvalue=
- 속성의 화이트리스트 및 블랙리스트를 ingetValue와 동일하게 구현하는 매개 변수
- 속성의 원본 값만 반환되는지 여부를 지정하는 선택적 부울입니다(기본값은 "아니오"입니다.
onlysourced=
- 에서 임의 접근을 위한 선택 항목 ID
qid=
- getValue에서와 동일한 형식의 출력 매개변수
getValueByQual 예제
고기(Q10990)에는 복수의 값을 가지는 속성 발음 오디오(P443)가 있으며, 각각의 값은 작업 또는 이름의 한정자 언어(P407)를 갖습니다.한정자가 아랍어 값을 가지는 속성 값을 반환할 수 있습니다(Q13955).
{{#invoke:WikidataIB getValueByQual qid=Q10990 P443 qualID=P407 qvalue=Q13955 fwd=ALL osd=no noicon=true}}
→ 아르-لحم.ogg
함수 getValueByLang
getValueByLang 함수는 지정된 언어 코드를 가진 작업 또는 이름(P407)의 한정자 언어를 가진 속성의 값을 반환합니다.매개 변수는 다음과 같습니다.
- 이름 없는 매개 변수에 전달된 속성 ID(또는
1=
) - 코드가 부여된 언어와 일치하는 위키미디어 언어 코드(P424)
lang=xx[-yy]
. 코드가 제공되지 않으면 기본 언어를 사용합니다. - 속성의 화이트리스트 및 블랙리스트를 ingetValue와 동일하게 구현하는 매개 변수
- 속성의 원본 값만 반환되는지 여부를 지정하는 선택적 부울입니다(기본값은 "아니오"입니다.
onlysourced=
- 에서 임의 접근을 위한 선택 항목 ID
qid=
- getValue에서와 동일한 형식의 출력 매개변수
getValueByLang 예제
OSDN(Q7565108)에는 여러 개의 값을 가지는 속성 공식 웹 사이트(P856)가 있으며, 각 웹 사이트에는 작업 또는 이름의 한정자 언어(P407)가 있습니다.작업 언어 또는 이름(P407) 한정자 값(WD 항목) 자체에 "ja", 즉 일본어(Q5287) 속성이 있는 속성 값을 반환할 수 있습니다.
{{#invoke:WikidataIB getValueByLang qid=Q7565108 P856 lang=ja fwd=ALL osd=no noicon=true}}
→ https://ja.osdn.net/
한다면 lang=
지정되지 않았으며, 기본 언어로 동일한 값을 얻을 수 있습니다(여기서 영어(Q1860)와 위키미디어 언어 코드(P424)는 "en"입니다).
{{#invoke:WikidataIB getValueByLang qid=Q7565108 P856 fwd=ALL osd=no noicon=true}}
→ https://osdn.net/
유틸리티 함수
함수 getLink
getLink에는 Wikidata 엔티티의 qid가 첫 번째 이름 없는 매개 변수로 전달되거나 qid=로 전달됩니다.
로컬 Wiki에 기사에 대한 사이트 링크가 있으면 Wikidata 레이블이 표시된 텍스트로 기사에 대한 링크를 반환합니다.사이트 링크가 없는 경우 레이블을 일반 텍스트로 반환합니다.로컬 언어에 레이블이 없는 경우 qid를 대신 표시합니다.
- 위키데이터:코리스카와 사티르 (Q29016906)와 고고학자 (Q3621491)
함수 getLabel
getLabel은 Wikidata 엔티티의 qid를 첫 번째 이름 없는 매개 변수로 전달하거나 다음과 같이 전달합니다. qid=
지정된 qid로 항목에 대한 Wikidata 레이블을 로컬 언어로 반환합니다.로컬 언어에 레이블이 없으면 대신 qid를 반환합니다.라벨이 있는 경우, 현재 Wiki와 동일한 언어로 Wiki 데이터 항목에 부여된 라벨입니다.
- 위키데이터:코리스카와 사티르 (Q29016906)와 고고학자 (Q3621491)
{{#invoke:WikidataIB getLabel Q29016906}}
→ 코리스카와 사티르{{#invoke:WikidataIB getLabel Q3621491}}
→ 고고학자{{#invoke:WikidataIB getLabel Q19805408}}
→ 모듈:비블리오/우비지
함수라벨
레이블에는 위키데이터 개체의 qid가 첫 번째 이름 없는 매개 변수로 전달되거나 다음과 같이 전달됩니다. qid=
지정된 qid에 의해 또는 현재 페이지에 링크된 항목에 대한 Wikidata 레이블을 로컬 언어로 반환합니다.로컬 언어에 레이블이 없으면 빈 문자열을 반환합니다.라벨이 있는 경우, 현재 Wiki와 동일한 언어로 Wiki 데이터 항목에 부여된 라벨입니다.
- 위키데이터:코리스카와 사티르 (Q29016906)와 고고학자 (Q3621491)
{{#invoke:WikidataIB label Q29016906}}
→ 코리스카와 사티르{{#invoke:WikidataIB label Q3621491}}
→ 고고학자{{#invoke:WikidataIB label Q19805408}}
→ 모듈:비블리오/우비지
함수 get AT
getAT에는 Wikidata 엔티티의 qid가 첫 번째 이름 없는 매개 변수로 전달되거나 qid=로 전달됩니다.
로컬 위키에 기사에 대한 사이트 링크가 있으면 사이트 링크를 일반 텍스트, 즉 기사 제목으로 반환합니다.사이트 링크가 없으면 아무것도 반환되지 않습니다.위키데이터 항목에 언어 간 링크가 존재하는 경우, 현재 위키백과의 기사 제목입니다.
- 위키데이터:코리스카와 사티르 (Q29016906)와 고고학자 (Q3621491)
{{#invoke:WikidataIB getAT Q29016906}}
→ 코리스카와 사티르{{#invoke:WikidataIB getAT Q3621491}}
→ 고고학자
함수 getDescription
getDescription에는 Wikidata 엔티티의 qid가 qid=(누락된 경우 현재 기사의 관련 qid로 기본 설정됨)로 전달됩니다.이름 없는 첫 번째 매개 변수로 전달된 로컬 매개 변수가 있습니다.전달된 로컬 매개 변수("Wikidata" 또는 "none" 제외)가 반환 값이 됩니다.로컬 매개 변수가 "Wikidata"인 경우 Wikidata 엔티티에 대한 기사 설명을 일반 텍스트로 반환합니다.설명이 존재하지 않거나 "none"이 로컬 매개 변수로 전달되면 아무것도 반환되지 않습니다.
- 위키데이터:코리스카와 사티르 (Q29016906)와 고고학자 (Q3621491)
{{#invoke:WikidataIB getDescription qid=Q29016906 wikidata}}
→ 아르테미시아 젠틸레스키의 그림{{#invoke:WikidataIB getDescription qid=Q29016906 A painting}}
→ 그림을{{#invoke:WikidataIB getDescription qid=Q29016906 none}}
→{{#invoke:WikidataIB getDescription qid=Q3621491 wikidata}}
→ 과거 인간 활동을 연구하는 사람{{#invoke:WikidataIB getDescription qid=Q3621491 A profession}}
→ 직업을{{#invoke:WikidataIB getDescription qid=Q3621491 none}}
→
함수 형식 날짜
formatDate는 mw에서 일반 형식의 datetime을 허용합니다.wikibase.entity:"1 August 30 BCE"와 같이 parameter 1로 propertyValues를 포맷하고 df(날짜 형식) 및 bc 매개 변수에 따라 포맷합니다.
{{#invoke:WikidataIB formatDate 1 August 30 BCE bc=BCE df=dmy}}
→ 기원전 8월 30일{{#invoke:WikidataIB formatDate 1 August 30 BCE bc=BC df=mdy}}
→ 기원전 30년 8월 1일- df = "dmy" / "mdy" / "y" - 기본값은 "dmy"입니다.
- bc = "BC" / "BCE" - 기본값은 "BCE"입니다.
기능 체크 블랙리스트
checkBlacklist를 사용하면 테스트에서 명명된 필드가 허용되는지 여부를 확인할 수 있습니다.필드가 블랙리스트에 포함되지 않으면 true로 반환됩니다(즉, 허용됨).필드가 블랙리스트에 있으면 false를 반환합니다(즉, 허용되지 않음).
예:
{{#if:{{#invoke:WikidataIB checkBlacklist name=nationality suppressfields=residence; nationality; citizenship}} not blacklisted blacklisted}}
→ 블랙리스트에 올라 있지 않은{{#if:{{#invoke:WikidataIB checkBlacklist name=birth_place suppressfields=residence; nationality; citizenship}} not blacklisted blacklisted}}
→ 블랙리스트에 올라 있지 않은
함수 비움 또는
이름 없는 첫 번째 인수가 구두점, 공백 또는 html 태그일 경우 empty 또는 nil을 반환합니다. 그렇지 않으면 변경되지 않은 인수를 반환합니다(선행/trailing 공간 포함).
인수에 "="이 포함될 수 있는 경우 명시적으로 호출해야 합니다.
1 = whatever-the-argument-is
이 경우 선행 및 후행 공간이 잘립니다.
다음과 같은 테스트를 대체할 수 있는 인포박스에서 사용할 수 있습니다.
{{#if: {{#invoke:WikidataIB getvalue P99 fwd=ALL}} <span class="xxx">{{#invoke:WikidataIB getvalue P99 fwd=ALL}}</span> }}
Wikidata에 한 번의 호출만 사용할 수 있는 양식을 제공합니다.
{{#invoke WikidataIB emptyor 1= <span class="xxx">{{#invoke:WikidataIB getvalue P99 fwd=ALL}}</span> }}
함수라벨오리드
labelorid는 labelOrId()의 출력을 노출시키는 공용 기능입니다.
Q-number( entity ID)는 qid= 또는 이름 없는 매개 변수로 전달됩니다.
레이블이 없는 경우 해당 엔티티 또는 qid에 대한 Wikidata 레이블을 반환합니다.
함수 getQid
- getQid는 현재 페이지 및 관련 위키데이터 항목과 함께 작동합니다.
- 첫 번째 이름 없는 매개 변수로 제공되거나 다음과 같이 제공되는 경우 qid를 반환합니다.
qid=
; - 이에 실패한 경우, "카테고리의 주요 주제(P301)"의 위키데이터 개체 ID가 존재하는 경우,
- 현재 페이지와 연관된 위키데이터 개체 ID(존재하는 경우)에 실패하는 경우,
- 그렇지 않으면 아무것도 아닌
기능검사
inspect는 첫 번째 이름 없는 매개 변수에 주어진 전체 속성의 덤프를 제공합니다. pid=
qid) 매개 변수 'qid'에 의해 지정된 항목에서 또는 qid가 제공되지 않은 경우 현재 페이지에 해당하는 항목에서 nameed alias로 지정됩니다.두 매개 변수 모두 이름을 지정하지 않고 순서대로 지정할 수 있습니다.
Dump 기능과 유사한 방식으로 작동하지만 전체 Wikidata 항목이 아닌 하나의 클레임만 로드합니다.
- 예:
{{#invoke:WikidataIB examine qid=Q1396889 P50}}
템플릿이 있습니다.어떤 것이 통화의 포장지 역할을 하는지 조사합니다.
- 예:
{{examine Q4048254 P31}}
→
table#1 { table#2 { ["id"] = "Q4048254$9af461b4-a1d0-4c67-a7f0-f668944a17d6", ["mainsnak"] = table#3 { ["datatype"] = wikibase-item", ["datavalue"] = table#4 { ["type"] = ""type", ["value"] = table#5 {" wikid", ["value"] = "item", ["id"] = "Q4656150", ["numeric-id"] = 4656150, }, ["property"] = "P31", ["snaktype"] = "value", }, ["rank"] = "보통", ["refe 차이"] = table#6 { table#7 { ["hash"] = "3bf39867b037e8e8389ae8a03bad6825a7fc", ["snaks"] = table#8 { ["P143"] = table#9 { table#10 { ["datatype"] = "wikibase-item", ["datavalue"] = table#11 {["type"] = "wikibase-entityid", ["value"] = table#12 {["entity-type"] = "item", ["id"] = "Q191168", ["numeric-id"] = 191168, }, }, table#9 {"table", ["datatype"]["property"] = "P143", ["snaktype"] = "value", }, }, ["snaks-order"] = table#13 {"P143", }, }, ["type"] = "statement", ="," table#14 {["id"]" = "q4048254$d1f08825-499b-8d4a-d1ee-304b2498a7fd" = table#15 {["datatype"] = "wikbase-item", ["datavalue"] = table#16 {["type"] = "wikbase- entityid", ["value"] = table#17 {"entityty"]pe"] = "item", ["id"] = "Q14204246", ["numeric-id"] = 14204246, }, ["property"] = "P31", ["snaktype"] = "value", }, ["rank"] = "normal", ["type"] = "state", }
함수 url2
url2는 올바른 url인 매개 변수 url=을(를) 사용하여 인포박스에서 사용할 수 있도록 포맷합니다.
예:
{{#invoke:WikidataIB url2 url= http://www.example.com/ }}
→ www.example .com <span class="url">[http://www.example.com/ www<wbr/>example <wbr/>com]//span>
{{#invoke:WikidataIB url2 url= http://www.example.com/path/ }}
→ www.example .com /path / <span class="url">[http://www.example.com/path/ www<wbr/>example <wbr/>com<wbr/>/path<wbr/>/<span>
{{#invoke:WikidataIB url2 url= {{wdib P856 qid=Q23317 fwd=ALL osd=no}} }}
→ www.audi .com <span class="url">[https://www.audi.com/ www<wbr/>audi<wbr/>com]//span> <span class='penicon autoconfirmed-show'>[[파일:OOjs UI 아이콘 edit-ltr-progressive.svg frameless text-top 10px alt=Wikidata 링크에서 편집하기=https://www.wikidata.org/wiki/Q23317?uselang=en#P856 Wikidata에서 편집하기]//span>
{{wdib P856 qid=Q23317 fwd=ALL osd=no}}
→ https://www.audi.com/https://www.audi.com/ <span class='penicon autoconfirmed-show'> [[파일:OOjs UI 아이콘 edit-ltr-progressive.svg frameless text-top 10px alt=Wikidata 링크에서 편집하기=https://www.wikidata.org/wiki/Q23317?uselang=en#P856 Wikidata에서 편집하기]//span>
{{#invoke:WikidataIB url2 url= {{url http://www.example.com/}} }}
→ www.example.com www.example.com/ www<wbr/> example<wbr/>com]//span>]<span class="url">[http://www.example.com/ www<wbr/> example<wbr/>com]//span> www<wbr/>com<wbr/>example<wbr/>com<wbr/>/wwwwbr/>example<wbr/>com]<wbr/><wbr/>com></span>
{{URL}}의 출력과 비교:
{{URL http://www.example.com/ }}
→ www.example .com <span class="url">[http://www.example.com/ www<wbr/>example <wbr/>com]//span>
{{URL http://www.example.com/path/ }}
→ www.example .com /path / <span class="url">[http://www.example.com/path/ www<wbr/>example <wbr/>com<wbr/>/path<wbr/>//span>
{{URL {{wikidata property Q23317 P856}} }}
→ www.audi .com <span class="url">[https://www.audi.com/ www<wbr/>audi <wbr/>com>//span>
{{wikidata property Q23317 P856}}
→ https://www.audi.com/https://www.audi.com/
참고 항목
정보 상자로 코딩
일반적으로 적절한 템플릿 매개 변수를 사용하여 정보 상자 정의에서 getValue 호출이 호출됩니다.템플릿에는 한 가지 간단한 구현이 예로 제시되어 있습니다.인포박스 북/위키데이터/샌드박스예를 들어 인포박스의 '작성자' 필드는 다음과 같이 코딩됩니다.
label2 = 작성자{{#if:{{authors }}}s}} 데이터2 = {{#invoke:위키데이터IBgetValue P50 name=저자 fetchwikidata={{{fetchwikidata}}}억제필드={{{suppress필드}}{{{{저자}}}}}}}.
가져올 속성은 이름 없는 첫 번째 매개 변수입니다.이 경우 작성자입니다(P50).
필드 이름이 전달되었습니다. name=
블랙리스트와 화이트리스트를 기준으로 이름이 확인됩니다.특정 기사에서 작성자 필드를 항상 억제하려면 편집자가 다음을 설정합니다. suppressfields=author
정보함에.그러면 작성자 필드가 표시되지 않습니다.
필드가 블랙리스트에 없는 경우, 정보 상자는 단순히 설정하기만 하면 작성자에 대해 로컬로 제공된 값을 표시하도록 설정할 수 있습니다. author=George Orwell
, 예를 들어 info box에 있습니다.그것은 또한 수용합니다. authors=
. 필드 이름이 화이트리스트에 있는 경우(예: fetchwikidata=author; genre; pub_date; pages; dewey; congress
, 로컬 값이 제공되지 않으면 정보 상자에 Wikidata에서 검색된 값이 표시됩니다.및 {}을(를) 제외한 모든 구분자를 사용할 수 있습니다.
속기로, fetchwikidata=ALL
지정된 필드에 대한 로컬 값이 아티클에 이미 제공되지 않는 한 블랙리스트에 포함되지 않은 모든 필드를 가져옵니다.
Wikidata 레이블은 일반적으로 소문자이므로 모듈의 ucfirst 기능:문자열 2는 반환된 텍스트의 첫 글자를 대문자로 쓰는 데 사용할 수 있습니다.
{{#invoke:String2 ucfirst {{#invoke:WikidataIB getValue P136 name=genre fetchwikidata=ALL onlysourced=false}} }}
in Animal Farm(Q1396889)에서 생산:- 로마자 아클레프, 풍자 소설, 우화, 디스토피아 소설
정보 상자의 호출 예제
getValue의 기본 사용:
{{#invoke:WikidataIB getValue P000 name=fieldname qid={{{qid }}} fetchwikidata={{{fetchwikidata }}} onlysourced={{{onlysourced }}} {{{localparameter }}} }}
전체 파라미터 모음:
{{#invoke:WikidataIB getValue P000 name=fieldname qid={{{qid }}} suppressfields={{{suppressfields }}} fetchwikidata={{{fetchwikidata }}} onlysourced={{{onlysourced }}} noicon={{{noicon }}} wdl={{{wikidatalink }}} df={{dateformat }} bc={{{bc }}} prefix= postfix= linkprefix= linkpostfix= sorted={{{sorted }}} sep={{{separator }}} list={{listtype }}} {{{localparameter }}} }}
물론 모든 필드에 영향을 미치는 인포박스에 제공된 매개변수를 사용하지 않고 인포박스의 특정 필드에 대해 매개변수를 수정할 수 있습니다.예를 들어, 하나의 필드가 다음과 같이 설정할 수 있습니다. list=hlist
일련의 짧은 단어들이 예상되는 반면, 다른 분야는 다음을 사용할 수 있습니다. list=ubl
여기서 각 행에 여러 단어의 글머리표가 없는 수직 목록이 필요합니다.
좌표
getCoords 호출에는 Template의 출력이 표시됩니다.Wikidata에서 반환된 좌표와 함께 제공되면 좌표를 조정합니다.다음과 같이 코드화할 수 있습니다.
label20 = coordines data20 = {{# invoke:위키데이터IB getCoords name=coordinate suppressfields={{{suppress필드}}}}: fetchwikidata={{{fetchwikidata}}}{{{coordinate}}}}}.
템플릿을 예로 들 수 있습니다.인포박스 생물권보전지역
{{인포박스 생물권보전지역 fetchwikidata = ALL}}
Wikidata에 좌표가 있는 기사에서 사용할 경우 일반 위치의 좌표를 표시합니다.
기존 인포박스 업그레이드
파라미터 이후로 fetchwikidata=
Wikidata 기능에 필요합니다. 기존 인포박스는 어떠한 기사도 변경하지 않고 이러한 호출을 통합한 인포박스로 대체될 수 있습니다.새 정보 상자를 사용하는 각 문서는 나중에 다음을 제공하여 활성화할 수 있습니다. fetchwikidata=ALL
, 또는 해당 기사에 필요한 필드 목록입니다.이 시점에서 편집기에 있는 부담으로 인해 원하지 않는 필드가 표시되지 않는지 확인할 수 있습니다.그렇다면 다음과 같이 설정하여 해당 기사의 블랙리스트에 추가할 수 있습니다. suppressfields=
원하지 않는 필드 목록에 표시됩니다.
검증가능성
특정 필드에 참조된 값만 포함하는 것이 항상 필수적인 경우 를 사용합니다.getValue
, 을 확실히 하기 위해 onlysourced=
'false', '0' 또는 '아니오'로 설정되지 않았습니다.기본적으로 출처가 없거나 위키백과에서만 출처가 지정된 값은 제외되므로 기사 수준에서 확인 작업을 쉽게 수행할 수 있습니다.출처가 없는 데이터가 허용 가능한 경우(!) 설정 onlysourced=no
. 주어진 상황에서 기존 소스가 신뢰할 수 있는지 여부를 알 수 있는 자동화된 메커니즘을 만드는 것은 제가 할 수 있는 일이 아니기 때문에, 그 작업은 여전히 그 주제에 정통한 편집자에 의해 기사 수준에서 수행되어야 합니다.이 작업은 해당 기사에 대해 Wikidata를 처음 활성화할 때 항상 수행해야 합니다.
도우미 템플릿
- 템플릿:만약 그렇다면 보여주기
- 이름이 없는 첫 번째 매개 변수가 빈 문자열이 아닌지를 테스트하고 그렇지 않으면 반환합니다.그렇지 않으면 이름 없는 두 번째 매개 변수를 반환합니다.선택적인 세 번째 및 네 번째 이름 없는 매개 변수는 반환될 때 첫 번째 매개 변수의 접두사와 접미사를 제공합니다.첫 번째 매개 변수가 Wikidata 호출일 때 유용합니다.
- 템플릿:noteq인 경우 표시
- 는 첫 번째 이름 없는 매개 변수가 두 번째 이름 없는 매개 변수와 동일한지 여부를 테스트하고, 만약 그렇다면 세 번째 이름 없는 매개 변수를 반환합니다.그렇지 않으면 이름 없는 첫 번째 매개 변수를 반환합니다.첫 번째 파라미터가 a일 때 유용합니다.
{{#invoke:
특정 예외가 필요한 값을 반환하는 Lua 모듈. - 템플릿:만약 그렇다면 wikilink
- 는 이름이 없는 첫 번째 매개 변수가 빈 문자열이 아닌지를 테스트하고, 만약 그렇지 않다면 선택적 네임스페이스 접두사를 사용하여 piped wiki-link 형식의 매개 변수를 반환합니다.
- 템플릿:포맷터 링크
- 외부 식별자 코드를 다음과 같이 사용합니다.
code=
포맷터 URL을 사용합니다.url=
코드를 디스플레이로 사용하는 외부 리소스에 대한 링크를 구성합니다. - 템플릿:비움 또는
- 는 텍스트가 효과적으로 비어 있는지 또는 텍스트가 포함되어 있는지 확인하기 위해 텍스트 조각을 테스트합니다.이름 없는 매개 변수가 html 태그, 구두점(예: wiki markup) 및 공백으로만 구성된 경우 Empty 또는 nothing을 반환합니다. 그렇지 않으면 매개 변수가 변경되지 않습니다.p.empty or function의 포장지.
사용 예:인포박스북
이 섹션은 템플릿에서 가져온 것입니다.인포박스 북/위키데이터/샌드박스/doc
위키데이터 없음
{{인포박스 북/위키다타/샌드박스 억제필드 =페치위키다타 =이름 =동물농장 title_orig =동물농장:동화 이미지 =동물농장 -1판. jpg image_size =200 px 캡션 =초판 표지 저자 =[조지 오웰] country =영국어 =영어 장르 =정치 풍자 }
비인식 인포박스로 작동합니다. 로컬에서 제공되는 매개변수만 표시됩니다.
{{인포박스 book/Wikidata/샌드박스명 =동물농장 title_origin =동물농장 : 동화속 이미지 =동물농장 - 1판. jpg image_size =200 px 캡션 =초판 표지 저자 =[조지오웰] 국가 =영국어 =영어장르 =정치 풍자 }
블랙리스트 및 화이트리스트는 사용하지 않을 경우 생략할 수 있습니다.
모든 Wikidata
{{Infobox book/Wikidata/샌드박스 fetchwikidata =저자;장르;펍_데이트;페이지; 듀이;의회}}
Wikidata에서 작성자, 발행일, 페이지 수, Dewey 인덱스 및 의회도서관 카탈로그 번호 값을 가져옵니다.
{{인포박스 북/위키다타/샌드박스 페치위키다타 = ALL }
속기로 말하면, fetchwikidata=
사용 가능한 모든 필드를 가져오려면 매개 변수를 ALL로 설정할 수 있습니다.필드 이름을 지정하여 모든 필드를 억제할 수 있습니다. suppressfields=
, 로컬 값을 제공하여 재정의할 수 있습니다.
장르 표시 안 함
{{Infobox book/Wikidata/샌드박스 억제필드 =장르페치위키데이터 =작가;장르;펍_데이트;페이지; 듀이;의회}}
로컬 값이 제공되더라도 장르 필드는 항상 억제됩니다.
{{인포박스 북/위키다타/샌드박스 억제필드 =장르페치위키다타 =작가;장르;펍_데이트;페이지;듀이;의회장르=정치 풍자}
로컬 재정의
{{인포박스 북/위키다타/샌드박스 페치위키다타 =작가;장르;펍_데이트;페이지;듀이;의회장르=정치 풍자}
장르 필드는 위키데이터에 저장된 내용에 상관없이 '정치 풍자'를 표시하도록 설정되어 있습니다.
{{인포박스 북/위키다타/샌드박스 페치위키다타 = ALL장르 = 소설 }
장르 필드는 Wikidata에 저장된 내용에 상관없이 "소설"을 표시하도록 설정되어 있습니다.
장르를 가져오지 않음
{{Infobox book/Wikidata/샌드박스 억제필드 = fetchwikidata = 작성자; pub_date; pages; dewey; congress }
장르 필드는 Wikidata에서 가져올 수 없습니다.저자, 출판일, 페이지 수, 듀이 인덱스, 의회도서관 카탈로그 번호만 가져옵니다.장르에 대한 로컬 값이 표시됩니다.
모듈 내보내기
위키데이터IB는 최소한의 수정을 통해 모든 언어 위키(또는 위키미디어 프로젝트)에서 실행되도록 개발되었습니다.옵션인 하위 모듈 모듈:위키데이터IB/i18n은 모듈의 로컬 i18n 정의에 표시된 오류 메시지, 서수 접미사 등에 대한 값을 대체하도록 생성될 수 있습니다.Wikidata에서 이러한 값을 직접 편집하면 동일한 결과를 얻을 수 있음에도 불구하고IB는 하위 모듈을 사용하여 Wikidata의 업데이트된 버전을 사용할 수 있습니다.i18n 정의를 다시 편집할 필요 없이 구형 모듈을 직접 교체하는 IB.
연계항목
대상 Wiki에 특정 항목이 정상적으로 연결되지 않는다는 규칙이 있는 경우(다음 참조).위키백과:Style/Linking #일반적으로 예를 들어 링크하면 안 되는 것)의 매뉴얼, 그 다음 하위 모듈 모듈:위키데이터영어 위키백과 하위 모듈을 예로 들어 링크를 연결해서는 안 되는 항목을 나열하도록 IB/no링크를 만들 수 있습니다.
이탤릭체 제목
대상 위키에 특정 저작물을 이탤릭체로 하거나 인용해야 한다는 규칙이 있는 경우, 다음을 참조하십시오.위키백과:예를 들어 스타일/텍스트 형식 지정 #이름 및 제목 매뉴얼), 그런 다음 하위 모듈 모듈 모듈:위키데이터영어 위키백과 하위 모듈을 예제로 사용하여 이탤릭체로 표시하거나 따옴표로 표시해야 하는 항목을 나열하도록 IB/title 형식을 만들 수 있습니다.
Complex date
Most of the output from the module will use the local language (or any user-specified one on multi-lingual wikis) where the sitelink or label exists on Wikidata. However, dates are more complicated and not handled perfectly in all languages. To solve this, WikidataIB uses Module:Complex date – developed on Commons by Jarekt – which allows expansion to support a wider variety of languages. As a result, it is necessary to install Complex date and its dependencies alongside WikidataIB when installing on another Wikimedia project.
Complex date dependencies
Module:Complex_date relies on the following modules:
- Module:Calendar (lazy loading with no dependencies)
- Module:ISOdate
- Module:DateI18n (no dependencies)
- Module:i18n/complex date
- Module:Ordinal (lazy loading)
- Module:I18n/ordinal (no dependencies)
- Module:Yesno (from en.wikipedia) (no dependencies)
- Module:Formatnum (no dependencies)
- Module:Roman (lazy loading with no dependencies)
- Module:Linguistic (lazy loading with no dependencies)
- Module:Ordinal (lazy loading)
Unless otherwise noted, the authoritative version of each module can be found on Commons although the versions on English Wikipedia are usually kept in sync.
See also
- Module:Wikidata, handling Wikidata more basically
- Template:WikidataOI, a template that uses Module:Wd but also has and "opt-in" options
fetch=
andifeq=
similar to this module'sfetchwikidata=
orfwd=
Tracking categories
-- Version: 2023-07-10 -- Module to implement use of a blacklist and whitelist for infobox fields -- Can take a named parameter qid which is the Wikidata ID for the article -- if not supplied, it will use the Wikidata ID associated with the current page. -- Fields in blacklist are never to be displayed, i.e. module must return nil in all circumstances -- Fields in whitelist return local value if it exists or the Wikidata value otherwise -- The name of the field that this function is called from is passed in named parameter name -- The name is compulsory when blacklist or whitelist is used, -- so the module returns nil if it is not supplied. -- blacklist is passed in named parameter suppressfields (or spf) -- whitelist is passed in named parameter fetchwikidata (or fwd) require("strict") local p = {} local cdate -- initialise as nil and only load _complex_date function if needed -- Module:Complex date is loaded lazily and has the following dependencies: -- Module:Calendar -- Module:ISOdate -- Module:DateI18n -- Module:I18n/complex date -- Module:Ordinal -- Module:I18n/ordinal -- Module:Yesno -- Module:Formatnum -- Module:Linguistic -- -- The following, taken from https://www.mediawiki.org/wiki/Wikibase/DataModel#Dates_and_times, -- is needed to use Module:Complex date which seemingly requires date precision as a string. -- It would work better if only the authors of the mediawiki page could spell 'millennium'. local dp = { [6] = "millennium", [7] = "century", [8] = "decade", [9] = "year", [10] = "month", [11] = "day", } local i18n = { ["errors"] = { ["property-not-found"] = "Property not found.", ["No property supplied"] = "No property supplied", ["entity-not-found"] = "Wikidata entity not found.", ["unknown-claim-type"] = "Unknown claim type.", ["unknown-entity-type"] = "Unknown entity type.", ["qualifier-not-found"] = "Qualifier not found.", ["site-not-found"] = "Wikimedia project not found.", ["labels-not-found"] = "No labels found.", ["descriptions-not-found"] = "No descriptions found.", ["aliases-not-found"] = "No aliases found.", ["unknown-datetime-format"] = "Unknown datetime format.", ["local-article-not-found"] = "Article is available on Wikidata, but not on Wikipedia", ["dab-page"] = " (dab)", }, ["months"] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }, ["century"] = "century", ["BC"] = "BC", ["BCE"] = "BCE", ["ordinal"] = { [1] = "st", [2] = "nd", [3] = "rd", ["default"] = "th" }, ["filespace"] = "File", ["Unknown"] = "Unknown", ["NaN"] = "Not a number", -- set the following to the name of a tracking category, -- e.g. "[[Category:Articles with missing Wikidata information]]", or "" to disable: ["missinginfocat"] = "[[Category:Articles with missing Wikidata information]]", ["editonwikidata"] = "Edit this on Wikidata", ["latestdatequalifier"] = function (date) return "before " .. date end, -- some languages, e.g. Bosnian use a period as a suffix after each number in a date ["datenumbersuffix"] = "", ["list separator"] = ", ", ["multipliers"] = { [0] = "", [3] = " thousand", [6] = " million", [9] = " billion", [12] = " trillion", } } -- This allows an internationisation module to override the above table if 'en' ~= mw.getContentLanguage():getCode() then require("Module:i18n").loadI18n("Module:WikidataIB/i18n", i18n) end -- This piece of html implements a collapsible container. Check the classes exist on your wiki. local collapsediv = '<div class="mw-collapsible mw-collapsed" style="width:100%; overflow:auto;" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">' -- Some items should not be linked. -- Each wiki can create a list of those in Module:WikidataIB/nolinks -- It should return a table called itemsindex, containing true for each item not to be linked local donotlink = {} local nolinks_exists, nolinks = pcall(mw.loadData, "Module:WikidataIB/nolinks") if nolinks_exists then donotlink = nolinks.itemsindex end -- To satisfy Wikipedia:Manual of Style/Titles, certain types of items are italicised, and others are quoted. -- The submodule [[Module:WikidataIB/titleformats]] lists the entity-ids used in 'instance of' (P31), -- which allows this module to identify the values that should be formatted. -- WikidataIB/titleformats exports a table p.formats, which is indexed by entity-id, and contains the value " or '' local formats = {} local titleformats_exists, titleformats = pcall(mw.loadData, "Module:WikidataIB/titleformats") if titleformats_exists then formats = titleformats.formats end ------------------------------------------------------------------------------- -- Private functions ------------------------------------------------------------------------------- -- ------------------------------------------------------------------------------- -- makeOrdinal needs to be internationalised along with the above: -- takes cardinal number as a numeric and returns the ordinal as a string -- we need three exceptions in English for 1st, 2nd, 3rd, 21st, .. 31st, etc. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local makeOrdinal = function(cardinal) local ordsuffix = i18n.ordinal.default if cardinal % 10 == 1 then ordsuffix = i18n.ordinal[1] elseif cardinal % 10 == 2 then ordsuffix = i18n.ordinal[2] elseif cardinal % 10 == 3 then ordsuffix = i18n.ordinal[3] end -- In English, 1, 21, 31, etc. use 'st', but 11, 111, etc. use 'th' -- similarly for 12 and 13, etc. if (cardinal % 100 == 11) or (cardinal % 100 == 12) or (cardinal % 100 == 13) then ordsuffix = i18n.ordinal.default end return tostring(cardinal) .. ordsuffix end ------------------------------------------------------------------------------- -- findLang takes a "langcode" parameter if supplied and valid -- otherwise it tries to create it from the user's set language ({{int:lang}}) -- failing that it uses the wiki's content language. -- It returns a language object ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local findLang = function(langcode) local langobj langcode = mw.text.trim(langcode or "") if mw.language.isKnownLanguageTag(langcode) then langobj = mw.language.new( langcode ) else langcode = mw.getCurrentFrame():callParserFunction('int', {'lang'}) if mw.language.isKnownLanguageTag(langcode) then langobj = mw.language.new( langcode ) else langobj = mw.language.getContentLanguage() end end return langobj end ------------------------------------------------------------------------------- -- _getItemLangCode takes a qid parameter (using the current page's qid if blank) -- If the item for that qid has property country (P17) it looks at the first preferred value -- If the country has an official language (P37), it looks at the first preferred value -- If that official language has a language code (P424), it returns the first preferred value -- Otherwise it returns nothing. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local _getItemLangCode = function(qid) qid = mw.text.trim(qid or ""):upper() if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return end local prop17 = mw.wikibase.getBestStatements(qid, "P17")[1] if not prop17 or prop17.mainsnak.snaktype ~= "value" then return end local qid17 = prop17.mainsnak.datavalue.value.id local prop37 = mw.wikibase.getBestStatements(qid17, "P37")[1] if not prop37 or prop37.mainsnak.snaktype ~= "value" then return end local qid37 = prop37.mainsnak.datavalue.value.id local prop424 = mw.wikibase.getBestStatements(qid37, "P424")[1] if not prop424 or prop424.mainsnak.snaktype ~= "value" then return end return prop424.mainsnak.datavalue.value end ------------------------------------------------------------------------------- -- roundto takes a number (x) -- and returns it rounded to (sf) significant figures ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local roundto = function(x, sf) if x == 0 then return 0 end local s = 1 if x < 0 then x = -x s = -1 end if sf < 1 then sf = 1 end local p = 10 ^ (math.floor(math.log10(x)) - sf + 1) x = math.floor(x / p + 0.5) * p * s -- if it's integral, cast to an integer: if x == math.floor(x) then x = math.floor(x) end return x end ------------------------------------------------------------------------------- -- decimalToDMS takes a decimal degrees (x) with precision (p) -- and returns degrees/minutes/seconds according to the precision ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local decimalToDMS = function(x, p) -- if p is not supplied, use a precision around 0.1 seconds if not tonumber(p) then p = 1e-4 end local d = math.floor(x) local ms = (x - d) * 60 if p > 0.5 then -- precision is > 1/2 a degree if ms > 30 then d = d + 1 end ms = 0 end local m = math.floor(ms) local s = (ms - m) * 60 if p > 0.008 then -- precision is > 1/2 a minute if s > 30 then m = m +1 end s = 0 elseif p > 0.00014 then -- precision is > 1/2 a second s = math.floor(s + 0.5) elseif p > 0.000014 then -- precision is > 1/20 second s = math.floor(10 * s + 0.5) / 10 elseif p > 0.0000014 then -- precision is > 1/200 second s = math.floor(100 * s + 0.5) / 100 else -- cap it at 3 dec places for now s = math.floor(1000 * s + 0.5) / 1000 end return d, m, s end ------------------------------------------------------------------------------- -- decimalPrecision takes a decimal (x) with precision (p) -- and returns x rounded approximately to the given precision -- precision should be between 1 and 1e-6, preferably a power of 10. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local decimalPrecision = function(x, p) local s = 1 if x < 0 then x = -x s = -1 end -- if p is not supplied, pick an arbitrary precision if not tonumber(p) then p = 1e-4 elseif p > 1 then p = 1 elseif p < 1e-6 then p = 1e-6 else p = 10 ^ math.floor(math.log10(p)) end x = math.floor(x / p + 0.5) * p * s -- if it's integral, cast to an integer: if x == math.floor(x) then x = math.floor(x) end -- if it's less than 1e-4, it will be in exponent form, so return a string with 6dp -- 9e-5 becomes 0.000090 if math.abs(x) < 1e-4 then x = string.format("%f", x) end return x end ------------------------------------------------------------------------------- -- formatDate takes a datetime of the usual format from mw.wikibase.entity:formatPropertyValues -- like "1 August 30 BCE" as parameter 1 -- and formats it according to the df (date format) and bc parameters -- df = ["dmy" / "mdy" / "y"] default will be "dmy" -- bc = ["BC" / "BCE"] default will be "BCE" ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local format_Date = function(datetime, dateformat, bc) local datetime = datetime or "1 August 30 BCE" -- in case of nil value -- chop off multiple vales and/or any hours, mins, etc. -- keep anything before punctuation - we just want a single date: local dateval = string.match( datetime, "[%w ]+") local dateformat = string.lower(dateformat or "dmy") -- default to dmy local bc = string.upper(bc or "") -- can't use nil for bc -- we only want to accept two possibilities: BC or default to BCE if bc == "BC" then bc = " " .. i18n["BC"] -- prepend a non-breaking space. else bc = " " .. i18n["BCE"] end local postchrist = true -- start by assuming no BCE local dateparts = {} for word in string.gmatch(dateval, "%w+") do if word == "BCE" or word == "BC" then -- *** internationalise later *** postchrist = false else -- we'll keep the parts that are not 'BCE' in a table dateparts[#dateparts + 1] = word end end if postchrist then bc = "" end -- set AD dates to no suffix *** internationalise later *** local sep = " " -- separator is nbsp local fdate = table.concat(dateparts, sep) -- set formatted date to same order as input -- if we have day month year, check dateformat if #dateparts == 3 then if dateformat == "y" then fdate = dateparts[3] elseif dateformat == "mdy" then fdate = dateparts[2] .. sep .. dateparts[1] .. "," .. sep .. dateparts[3] end elseif #dateparts == 2 and dateformat == "y" then fdate = dateparts[2] end return fdate .. bc end ------------------------------------------------------------------------------- -- dateFormat is the handler for properties that are of type "time" -- It takes timestamp, precision (6 to 11 per mediawiki), dateformat (y/dmy/mdy), BC format (BC/BCE), -- a plaindate switch (yes/no/adj) to en/disable "sourcing circumstances"/use adjectival form, -- any qualifiers for the property, the language, and any adjective to use like 'before'. -- It passes the date through the "complex date" function -- and returns a string with the internatonalised date formatted according to preferences. ------------------------------------------------------------------------------- -- Dependencies: findLang(); cdate(); dp[] ------------------------------------------------------------------------------- local dateFormat = function(timestamp, dprec, df, bcf, pd, qualifiers, lang, adj, model) -- output formatting according to preferences (y/dmy/mdy/ymd) df = (df or ""):lower() -- if ymd is required, return the part of the timestamp in YYYY-MM-DD form -- but apply Year zero#Astronomers fix: 1 BC = 0000; 2 BC = -0001; etc. if df == "ymd" then if timestamp:sub(1,1) == "+" then return timestamp:sub(2,11) else local yr = tonumber(timestamp:sub(2,5)) - 1 yr = ("000" .. yr):sub(-4) if yr ~= "0000" then yr = "-" .. yr end return yr .. timestamp:sub(6,11) end end -- A year can be stored like this: "+1872-00-00T00:00:00Z", -- which is processed here as if it were the day before "+1872-01-01T00:00:00Z", -- and that's the last day of 1871, so the year is wrong. -- So fix the month 0, day 0 timestamp to become 1 January instead: timestamp = timestamp:gsub("%-00%-00T", "-01-01T") -- just in case date precision is missing dprec = dprec or 11 -- override more precise dates if required dateformat is year alone: if df == "y" and dprec > 9 then dprec = 9 end -- complex date only deals with precisions from 6 to 11, so clip range dprec = dprec>11 and 11 or dprec dprec = dprec<6 and 6 or dprec -- BC format is "BC" or "BCE" bcf = (bcf or ""):upper() -- plaindate only needs the first letter (y/n/a) pd = (pd or ""):sub(1,1):lower() if pd == "" or pd == "n" or pd == "f" or pd == "0" then pd = false end -- in case language isn't passed lang = lang or findLang().code -- set adj as empty if nil adj = adj or "" -- extract the day, month, year from the timestamp local bc = timestamp:sub(1, 1)=="-" and "BC" or "" local year, month, day = timestamp:match("[+-](%d*)-(%d*)-(%d*)T") local iso = tonumber(year) -- if year is missing, let it throw an error -- this will adjust the date format to be compatible with cdate -- possible formats are Y, YY, YYY0, YYYY, YYYY-MM, YYYY-MM-DD if dprec == 6 then iso = math.floor( (iso - 1) / 1000 ) + 1 end if dprec == 7 then iso = math.floor( (iso - 1) / 100 ) + 1 end if dprec == 8 then iso = math.floor( iso / 10 ) .. "0" end if dprec == 10 then iso = year .. "-" .. month end if dprec == 11 then iso = year .. "-" .. month .. "-" .. day end -- add "circa" (Q5727902) from "sourcing circumstances" (P1480) local sc = not pd and qualifiers and qualifiers.P1480 if sc then for k1, v1 in pairs(sc) do if v1.datavalue and v1.datavalue.value.id == "Q5727902" then adj = "circa" break end end end -- deal with Julian dates: -- no point in saying that dates before 1582 are Julian - they are by default -- doesn't make sense for dates less precise than year -- we can suppress it by setting plaindate, e.g. for use in constructing categories. local calendarmodel = "" if tonumber(year) > 1582 and dprec > 8 and not pd and model == "http://www.wikidata.org/entity/Q1985786" then calendarmodel = "julian" end if not cdate then cdate = require("Module:Complex date")._complex_date end local fdate = cdate(calendarmodel, adj, tostring(iso), dp[dprec], bc, "", "", "", "", lang, 1) -- this may have QuickStatements info appended to it in a div, so remove that fdate = fdate:gsub(' <div style="display: none;">[^<]*</div>', '') -- it may also be returned wrapped in a microformat, so remove that fdate = fdate:gsub("<[^>]*>", "") -- there may be leading zeros that we should remove fdate = fdate:gsub("^0*", "") -- if a plain date is required, then remove any links (like BC linked) if pd then fdate = fdate:gsub("%[%[.* ", ""):gsub("]]", "") end -- if 'circa', use the abbreviated form *** internationalise later *** fdate = fdate:gsub('circa ', '<abbr title="circa">c.</abbr> ') -- deal with BC/BCE if bcf == "BCE" then fdate = fdate:gsub('BC', 'BCE') end -- deal with mdy format if df == "mdy" then fdate = fdate:gsub("(%d+) (%w+) (%d+)", "%2 %1, %3") end -- deal with adjectival form *** internationalise later *** if pd == "a" then fdate = fdate:gsub(' century', '-century') end return fdate end ------------------------------------------------------------------------------- -- parseParam takes a (string) parameter, e.g. from the list of frame arguments, -- and makes "false", "no", and "0" into the (boolean) false -- it makes the empty string and nil into the (boolean) value passed as default -- allowing the parameter to be true or false by default. -- It returns a boolean. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local parseParam = function(param, default) if type(param) == "boolean" then param = tostring(param) end if param and param ~= "" then param = param:lower() if (param == "false") or (param:sub(1,1) == "n") or (param == "0") then return false else return true end else return default end end ------------------------------------------------------------------------------- -- _getSitelink takes the qid of a Wikidata entity passed as qid= -- It takes an optional parameter wiki= to determine which wiki is to be checked for a sitelink -- If the parameter is blank, then it uses the local wiki. -- If there is a sitelink to an article available, it returns the plain text link to the article -- If there is no sitelink, it returns nil. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local _getSitelink = function(qid, wiki) qid = (qid or ""):upper() if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return nil end wiki = wiki or "" local sitelink if wiki == "" then sitelink = mw.wikibase.getSitelink(qid) else sitelink = mw.wikibase.getSitelink(qid, wiki) end return sitelink end ------------------------------------------------------------------------------- -- _getCommonslink takes an optional qid of a Wikidata entity passed as qid= -- It returns one of the following in order of preference: -- the Commons sitelink of the Wikidata entity - but not if onlycat=true and it's not a category; -- the Commons sitelink of the topic's main category of the Wikidata entity; -- the Commons category of the Wikidata entity - unless fallback=false. ------------------------------------------------------------------------------- -- Dependencies: _getSitelink(); parseParam() ------------------------------------------------------------------------------- local _getCommonslink = function(qid, onlycat, fallback) qid = (qid or ""):upper() if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return nil end onlycat = parseParam(onlycat, false) if fallback == "" then fallback = nil end local sitelink = _getSitelink(qid, "commonswiki") if onlycat and sitelink and sitelink:sub(1,9) ~= "Category:" then sitelink = nil end if not sitelink then -- check for topic's main category local prop910 = mw.wikibase.getBestStatements(qid, "P910")[1] if prop910 then local tmcid = prop910.mainsnak.datavalue and prop910.mainsnak.datavalue.value.id sitelink = _getSitelink(tmcid, "commonswiki") end if not sitelink then -- check for list's main category local prop1754 = mw.wikibase.getBestStatements(qid, "P1754")[1] if prop1754 then local tmcid = prop1754.mainsnak.datavalue and prop1754.mainsnak.datavalue.value.id sitelink = _getSitelink(tmcid, "commonswiki") end end end if not sitelink and fallback then -- check for Commons category (string value) local prop373 = mw.wikibase.getBestStatements(qid, "P373")[1] if prop373 then sitelink = prop373.mainsnak.datavalue and prop373.mainsnak.datavalue.value if sitelink then sitelink = "Category:" .. sitelink end end end return sitelink end ------------------------------------------------------------------------------- -- The label in a Wikidata item is subject to vulnerabilities -- that an attacker might try to exploit. -- It needs to be 'sanitised' by removing any wikitext before use. -- If it doesn't exist, return the id for the item -- a second (boolean) value is also returned, value is true when the label exists ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local labelOrId = function(id, lang) if lang == "default" then lang = findLang().code end local label if lang then label = mw.wikibase.getLabelByLang(id, lang) else label = mw.wikibase.getLabel(id) end if label then return mw.text.nowiki(label), true else return id, false end end ------------------------------------------------------------------------------- -- linkedItem takes an entity-id and returns a string, linked if possible. -- This is the handler for "wikibase-item". Preferences: -- 1. Display linked disambiguated sitelink if it exists -- 2. Display linked label if it is a redirect -- 3. TBA: Display an inter-language link for the label if it exists other than in default language -- 4. Display unlinked label if it exists -- 5. Display entity-id for now to indicate a label could be provided -- dtxt is text to be used instead of label, or nil. -- shortname is boolean switch to use P1813 (short name) instead of label if true. -- lang is the current language code. -- uselbl is boolean switch to force display of the label instead of the sitelink (default: false) -- linkredir is boolean switch to allow linking to a redirect (default: false) -- formatvalue is boolean switch to allow formatting as italics or quoted (default: false) ------------------------------------------------------------------------------- -- Dependencies: labelOrId(); donotlink[] ------------------------------------------------------------------------------- local linkedItem = function(id, args) local lprefix = (args.lp or args.lprefix or args.linkprefix or ""):gsub('"', '') -- toughen against nil values passed local lpostfix = (args.lpostfix or ""):gsub('"', '') local prefix = (args.prefix or ""):gsub('"', '') local postfix = (args.postfix or ""):gsub('"', '') local dtxt = args.dtxt local shortname = args.shortname or args.sn local lang = args.lang or "en" -- fallback to default if missing local uselbl = args.uselabel or args.uselbl uselbl = parseParam(uselbl, false) local linkredir = args.linkredir linkredir = parseParam(linkredir, false) local formatvalue = args.formatvalue or args.fv formatvalue = parseParam(formatvalue, false) -- see if item might need italics or quotes local fmt = "" if next(formats) and formatvalue then for k, v in ipairs( mw.wikibase.getBestStatements(id, "P31") ) do if v.mainsnak.datavalue and formats[v.mainsnak.datavalue.value.id] then fmt = formats[v.mainsnak.datavalue.value.id] break -- pick the first match end end end local disp local sitelink = mw.wikibase.getSitelink(id) local label, islabel if dtxt then label, islabel = dtxt, true elseif shortname then -- see if there is a shortname in our language, and set label to it for k, v in ipairs( mw.wikibase.getBestStatements(id, "P1813") ) do if v.mainsnak.datavalue.value.language == lang then label, islabel = v.mainsnak.datavalue.value.text, true break end -- test for language match end -- loop through values of short name -- if we have no label set, then there was no shortname available if not islabel then label, islabel = labelOrId(id) shortname = false end else label, islabel = labelOrId(id) end if mw.site.siteName ~= "Wikimedia Commons" then if sitelink then if not (dtxt or shortname) then -- if sitelink and label are the same except for case, no need to process further if sitelink:lower() ~= label:lower() then -- strip any namespace or dab from the sitelink local pos = sitelink:find(":") or 0 local slink = sitelink if pos > 0 then local pfx = sitelink:sub(1,pos-1) if mw.site.namespaces[pfx] then -- that prefix is a valid namespace, so remove it slink = sitelink:sub(pos+1) end end -- remove stuff after commas or inside parentheses - ie. dabs slink = slink:gsub("%s%(.+%)$", ""):gsub(",.+$", "") -- if uselbl is false, use sitelink instead of label if not uselbl then -- use slink as display, preserving label case - find("^%u") is true for 1st char uppercase if label:find("^%u") then label = slink:gsub("^(%l)", string.upper) else label = slink:gsub("^(%u)", string.lower) end end end end if donotlink[label] then disp = prefix .. fmt .. label .. fmt .. postfix else disp = "[[" .. lprefix .. sitelink .. lpostfix .. " " .. prefix .. fmt .. label .. fmt .. postfix .. "]]" end elseif islabel then -- no sitelink, label exists, so check if a redirect with that title exists, if linkredir is true -- display plain label by default disp = prefix .. fmt .. label .. fmt .. postfix if linkredir then local artitle = mw.title.new(label, 0) -- only nil if label has invalid chars if not donotlink[label] and artitle and artitle.redirectTarget then -- there's a redirect with the same title as the label, so let's link to that disp = "[[".. lprefix .. label .. lpostfix .. " " .. prefix .. fmt .. label .. fmt .. postfix .. "]]" end end -- test if article title exists as redirect on current Wiki else -- no sitelink and no label, so return whatever was returned from labelOrId for now -- add tracking category [[Category:Articles with missing Wikidata information]] -- for enwiki, just return the tracking category if mw.wikibase.getGlobalSiteId() == "enwiki" then disp = i18n.missinginfocat else disp = prefix .. label .. postfix .. i18n.missinginfocat end end else local ccat = mw.wikibase.getBestStatements(id, "P373")[1] if ccat and ccat.mainsnak.datavalue then ccat = ccat.mainsnak.datavalue.value disp = "[[" .. lprefix .. "Category:" .. ccat .. lpostfix .. " " .. prefix .. label .. postfix .. "]]" elseif sitelink then -- this asumes that if a sitelink exists, then a label also exists disp = "[[" .. lprefix .. sitelink .. lpostfix .. " " .. prefix .. label .. postfix .. "]]" else -- no sitelink and no Commons cat, so return label from labelOrId for now disp = prefix .. label .. postfix end end return disp end ------------------------------------------------------------------------------- -- sourced takes a table representing a statement that may or may not have references -- it looks for a reference sourced to something not containing the word "wikipedia" -- it returns a boolean = true if it finds a sourced reference. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local sourced = function(claim) if claim.references then for kr, vr in pairs(claim.references) do local ref = mw.wikibase.renderSnaks(vr.snaks) if not ref:find("Wiki") then return true end end end end ------------------------------------------------------------------------------- -- setRanks takes a flag (parameter passed) that requests the values to return -- "b[est]" returns preferred if available, otherwise normal -- "p[referred]" returns preferred -- "n[ormal]" returns normal -- "d[eprecated]" returns deprecated -- multiple values are allowed, e.g. "preferred normal" (which is the default) -- "best" will override the other flags, and set p and n ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local setRanks = function(rank) rank = (rank or ""):lower() -- if nothing passed, return preferred and normal -- if rank == "" then rank = "p n" end local ranks = {} for w in string.gmatch(rank, "%a+") do w = w:sub(1,1) if w == "b" or w == "p" or w == "n" or w == "d" then ranks[w] = true end end -- check if "best" is requested or no ranks requested; and if so, set preferred and normal if ranks.b or not next(ranks) then ranks.p = true ranks.n = true end return ranks end ------------------------------------------------------------------------------- -- parseInput processes the Q-id , the blacklist and the whitelist -- if an input parameter is supplied, it returns that and ends the call. -- it returns (1) either the qid or nil indicating whether or not the call should continue -- and (2) a table containing all of the statements for the propertyID and relevant Qid -- if "best" ranks are requested, it returns those instead of all non-deprecated ranks ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- local parseInput = function(frame, input_parm, property_id) -- There may be a local parameter supplied, if it's blank, set it to nil input_parm = mw.text.trim(input_parm or "") if input_parm == "" then input_parm = nil end -- return nil if Wikidata is not available if not mw.wikibase then return false, input_parm end local args = frame.args -- can take a named parameter qid which is the Wikidata ID for the article. -- if it's not supplied, use the id for the current page local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end -- if there's no Wikidata item for the current page return nil if not qid then return false, input_parm end -- The blacklist is passed in named parameter suppressfields local blacklist = args.suppressfields or args.spf or "" -- The whitelist is passed in named parameter fetchwikidata local whitelist = args.fetchwikidata or args.fwd or "" if whitelist == "" then whitelist = "NONE" end -- The name of the field that this function is called from is passed in named parameter name local fieldname = args.name or "" if blacklist ~= "" then -- The name is compulsory when blacklist is used, so return nil if it is not supplied if fieldname == "" then return false, nil end -- If this field is on the blacklist, then return nil if blacklist:find(fieldname) then return false, nil end end -- If we got this far then we're not on the blacklist -- The blacklist overrides any locally supplied parameter as well -- If a non-blank input parameter was supplied return it if input_parm then return false, input_parm end -- We can filter out non-valid properties if property_id:sub(1,1):upper() ~="P" or property_id == "P0" then return false, nil end -- Otherwise see if this field is on the whitelist: -- needs a bit more logic because find will return its second value = 0 if fieldname is "" -- but nil if fieldname not found on whitelist local _, found = whitelist:find(fieldname) found = ((found or 0) > 0) if whitelist ~= 'ALL' and (whitelist:upper() == "NONE" or not found) then return false, nil end -- See what's on Wikidata (the call always returns a table, but it may be empty): local props = {} if args.reqranks.b then props = mw.wikibase.getBestStatements(qid, property_id) else props = mw.wikibase.getAllStatements(qid, property_id) end if props[1] then return qid, props end -- no property on Wikidata return false, nil end ------------------------------------------------------------------------------- -- createicon assembles the "Edit at Wikidata" pen icon. -- It returns a wikitext string inside a span class="penicon" -- if entityID is nil or empty, the ID associated with current page is used -- langcode and propertyID may be nil or empty ------------------------------------------------------------------------------- -- Dependencies: i18n[]; ------------------------------------------------------------------------------- local createicon = function(langcode, entityID, propertyID) langcode = langcode or "" if not entityID or entityID == "" then entityID= mw.wikibase.getEntityIdForCurrentPage() end propertyID = propertyID or "" local icon = " <span class='penicon autoconfirmed-show'>[[" -- " <span data-bridge-edit-flow='overwrite' class='penicon'>[[" -> enable Wikidata Bridge .. i18n["filespace"] .. ":OOjs UI icon edit-ltr-progressive.svg frameless text-top 10px alt=" .. i18n["editonwikidata"] .. " link=https://www.wikidata.org/wiki/" .. entityID if langcode ~= "" then icon = icon .. "?uselang=" .. langcode end if propertyID ~= "" then icon = icon .. "#" .. propertyID end icon = icon .. " " .. i18n["editonwikidata"] .. "]]</span>" return icon end ------------------------------------------------------------------------------- -- assembleoutput takes the sequence table containing the property values -- and formats it according to switches given. It returns a string or nil. -- It uses the entityID (and optionally propertyID) to create a link in the pen icon. ------------------------------------------------------------------------------- -- Dependencies: parseParam(); ------------------------------------------------------------------------------- local assembleoutput = function(out, args, entityID, propertyID) -- sorted is a boolean passed to enable sorting of the values returned -- if nothing or an empty string is passed set it false -- if "false" or "no" or "0" is passed set it false local sorted = parseParam(args.sorted, false) -- noicon is a boolean passed to suppress the trailing "edit at Wikidata" icon -- for use when the value is processed further by the infobox -- if nothing or an empty string is passed set it false -- if "false" or "no" or "0" is passed set it false local noic = parseParam(args.noicon, false) -- list is the name of a template that a list of multiple values is passed through -- examples include "hlist" and "ubl" -- setting it to "prose" produces something like "1, 2, 3, and 4" local list = args.list or "" -- sep is a string that is used to separate multiple returned values -- if nothing or an empty string is passed set it to the default -- any double-quotes " are stripped out, so that spaces may be passed -- e.g. sep=" - " local sepdefault = i18n["list separator"] local separator = args.sep or "" separator = string.gsub(separator, '"', '') if separator == "" then separator = sepdefault end -- collapse is a number that determines the maximum number of returned values -- before the output is collapsed. -- Zero or not a number result in no collapsing (default becomes 0). local collapse = tonumber(args.collapse) or 0 -- replacetext (rt) is a string that is returned instead of any non-empty Wikidata value -- this is useful for tracking and debugging local replacetext = mw.text.trim(args.rt or args.replacetext or "") -- if there's anything to return, then return a list -- comma-separated by default, but may be specified by the sep parameter -- optionally specify a hlist or ubl or a prose list, etc. local strout if #out > 0 then if sorted then table.sort(out) end -- if there's something to display and a pen icon is wanted, add it the end of the last value local hasdisplay = false for i, v in ipairs(out) do if v ~= i18n.missinginfocat then hasdisplay = true break end end if not noic and hasdisplay then out[#out] = out[#out] .. createicon(args.langobj.code, entityID, propertyID) end if list == "" then strout = table.concat(out, separator) elseif list:lower() == "prose" then strout = mw.text.listToText( out ) else strout = mw.getCurrentFrame():expandTemplate{title = list, args = out} end if collapse >0 and #out > collapse then strout = collapsediv .. strout .. "</div>" end else strout = nil -- no items had valid reference end if replacetext ~= "" and strout then strout = replacetext end return strout end ------------------------------------------------------------------------------- -- rendersnak takes a table (propval) containing the information stored on one property value -- and returns the value as a string and its language if monolingual text. -- It handles data of type: -- wikibase-item -- time -- string, url, commonsMedia, external-id -- quantity -- globe-coordinate -- monolingualtext -- It also requires linked, the link/pre/postfixes, uabbr, and the arguments passed from frame. -- The optional filter parameter allows quantities to be be filtered by unit Qid. ------------------------------------------------------------------------------- -- Dependencies: parseParam(); labelOrId(); i18n[]; dateFormat(); -- roundto(); decimalPrecision(); decimalToDMS(); linkedItem(); ------------------------------------------------------------------------------- local rendersnak = function(propval, args, linked, lpre, lpost, pre, post, uabbr, filter) lpre = lpre or "" lpost = lpost or "" pre = pre or "" post = post or "" args.lang = args.lang or findLang().code -- allow values to display a fixed text instead of label local dtxt = args.displaytext or args.dt if dtxt == "" then dtxt = nil end -- switch to use display of short name (P1813) instead of label local shortname = args.shortname or args.sn shortname = parseParam(shortname, false) local snak = propval.mainsnak or propval local dtype = snak.datatype local dv = snak.datavalue dv = dv and dv.value -- value and monolingual text language code returned local val, mlt if propval.rank and not args.reqranks[propval.rank:sub(1, 1)] then -- val is nil: value has a rank that isn't requested ------------------------------------ elseif snak.snaktype == "somevalue" then -- value is unknown val = i18n["Unknown"] ------------------------------------ elseif snak.snaktype == "novalue" then -- value is none -- val = "No value" -- don't return anything ------------------------------------ elseif dtype == "wikibase-item" then -- data type is a wikibase item: -- it's wiki-linked value, so output as link if enabled and possible local qnumber = dv.id if linked then val = linkedItem(qnumber, args) else -- no link wanted so check for display-text, otherwise test for lang code local label, islabel if dtxt then label = dtxt else label, islabel = labelOrId(qnumber) local langlabel = mw.wikibase.getLabelByLang(qnumber, args.lang) if langlabel then label = mw.text.nowiki( langlabel ) end end val = pre .. label .. post end -- test for link required ------------------------------------ elseif dtype == "time" then -- data type is time: -- time is in timestamp format -- date precision is integer per mediawiki -- output formatting according to preferences (y/dmy/mdy) -- BC format as BC or BCE -- plaindate is passed to disable looking for "sourcing cirumstances" -- or to set the adjectival form -- qualifiers (if any) is a nested table or nil -- lang is given, or user language, or site language -- -- Here we can check whether args.df has a value -- If not, use code from Module:Sandbox/RexxS/Getdateformat to set it from templates like {{Use mdy dates}} val = dateFormat(dv.time, dv.precision, args.df, args.bc, args.pd, propval.qualifiers, args.lang, "", dv.calendarmodel) ------------------------------------ -- data types which are strings: elseif dtype == "commonsMedia" or dtype == "external-id" or dtype == "string" or dtype == "url" then -- commonsMedia or external-id or string or url -- all have mainsnak.datavalue.value as string if (lpre == "" or lpre == ":") and lpost == "" then -- don't link if no linkpre/postfix or linkprefix is just ":" val = pre .. dv .. post elseif dtype == "external-id" then val = "[" .. lpre .. dv .. lpost .. " " .. pre .. dv .. post .. "]" else val = "[[" .. lpre .. dv .. lpost .. " " .. pre .. dv .. post .. "]]" end -- check for link requested (i.e. either linkprefix or linkpostfix exists) ------------------------------------ -- data types which are quantities: elseif dtype == "quantity" then -- quantities have mainsnak.datavalue.value.amount and mainsnak.datavalue.value.unit -- the unit is of the form http://www.wikidata.org/entity/Q829073 -- -- implement a switch to turn on/off numerical formatting later local fnum = true -- -- a switch to turn on/off conversions - only for en-wiki local conv = parseParam(args.conv or args.convert, false) -- if we have conversions, we won't have formatted numbers or scales if conv then uabbr = true fnum = false args.scale = "0" end -- -- a switch to turn on/off showing units, default is true local showunits = parseParam(args.su or args.showunits, true) -- -- convert amount to a number local amount = tonumber(dv.amount) or i18n["NaN"] -- -- scale factor for millions, billions, etc. local sc = tostring(args.scale or ""):sub(1,1):lower() local scale if sc == "a" then -- automatic scaling if amount > 1e15 then scale = 12 elseif amount > 1e12 then scale = 9 elseif amount > 1e9 then scale = 6 elseif amount > 1e6 then scale = 3 else scale = 0 end else scale = tonumber(args.scale) or 0 if scale < 0 or scale > 12 then scale = 0 end scale = math.floor(scale/3) * 3 end local factor = 10^scale amount = amount / factor -- ranges: local range = "" -- check if upper and/or lower bounds are given and significant local upb = tonumber(dv.upperBound) local lowb = tonumber(dv.lowerBound) if upb and lowb then -- differences rounded to 2 sig fig: local posdif = roundto(upb - amount, 2) / factor local negdif = roundto(amount - lowb, 2) / factor upb, lowb = amount + posdif, amount - negdif -- round scaled numbers to integers or 4 sig fig if (scale > 0 or sc == "a") then if amount < 1e4 then amount = roundto(amount, 4) else amount = math.floor(amount + 0.5) end end if fnum then amount = args.langobj:formatNum( amount ) end if posdif ~= negdif then -- non-symmetrical range = " +" .. posdif .. " -" .. negdif elseif posdif ~= 0 then -- symmetrical and non-zero range = " ±" .. posdif else -- otherwise range is zero, so leave it as "" end else -- round scaled numbers to integers or 4 sig fig if (scale > 0 or sc == "a") then if amount < 1e4 then amount = roundto(amount, 4) else amount = math.floor(amount + 0.5) end end if fnum then amount = args.langobj:formatNum( amount ) end end -- unit names and symbols: -- extract the qid in the form 'Qnnn' from the value.unit url -- and then fetch the label from that - or symbol if unitabbr is true local unit = "" local usep = "" local usym = "" local unitqid = string.match( dv.unit, "(Q%d+)" ) if filter and unitqid ~= filter then return nil end if unitqid and showunits then local uname = mw.wikibase.getLabelByLang(unitqid, args.lang) or "" if uname ~= "" then usep, unit = " ", uname end if uabbr then -- see if there's a unit symbol (P5061) local unitsymbols = mw.wikibase.getBestStatements(unitqid, "P5061") -- construct fallback table, add local lang and multiple languages local fbtbl = mw.language.getFallbacksFor( args.lang ) table.insert( fbtbl, 1, args.lang ) table.insert( fbtbl, 1, "mul" ) local found = false for idx1, us in ipairs(unitsymbols) do for idx2, fblang in ipairs(fbtbl) do if us.mainsnak.datavalue.value.language == fblang then usym = us.mainsnak.datavalue.value.text found = true break end if found then break end end -- loop through fallback table end -- loop through values of P5061 if found then usep, unit = " ", usym end end end -- format display: if conv then if range == "" then val = mw.getCurrentFrame():expandTemplate{title = "cvt", args = {amount, unit}} else val = mw.getCurrentFrame():expandTemplate{title = "cvt", args = {lowb, "to", upb, unit}} end elseif unit == "$" or unit == "£" then val = unit .. amount .. range .. i18n.multipliers[scale] else val = amount .. range .. i18n.multipliers[scale] .. usep .. unit end ------------------------------------ -- datatypes which are global coordinates: elseif dtype == "globe-coordinate" then -- 'display' parameter defaults to "inline, title" *** unused for now *** -- local disp = args.display or "" -- if disp == "" then disp = "inline, title" end -- -- format parameter switches from deg/min/sec to decimal degrees -- default is deg/min/sec -- decimal degrees needs format = dec local form = (args.format or ""):lower():sub(1,3) if form ~= "dec" then form = "dms" end -- not needed for now -- -- show parameter allows just the latitude, or just the longitude, or both -- to be returned as a signed decimal, ignoring the format parameter. local show = (args.show or ""):lower() if show ~= "longlat" then show = show:sub(1,3) end -- local lat, long, prec = dv.latitude, dv.longitude, dv.precision if show == "lat" then val = decimalPrecision(lat, prec) elseif show == "lon" then val = decimalPrecision(long, prec) elseif show == "longlat" then val = decimalPrecision(long, prec) .. ", " .. decimalPrecision(lat, prec) else local ns = "N" local ew = "E" if lat < 0 then ns = "S" lat = - lat end if long < 0 then ew = "W" long = - long end if form == "dec" then lat = decimalPrecision(lat, prec) long = decimalPrecision(long, prec) val = lat .. "°" .. ns .. " " .. long .. "°" .. ew else local latdeg, latmin, latsec = decimalToDMS(lat, prec) local longdeg, longmin, longsec = decimalToDMS(long, prec) if latsec == 0 and longsec == 0 then if latmin == 0 and longmin == 0 then val = latdeg .. "°" .. ns .. " " .. longdeg .. "°" .. ew else val = latdeg .. "°" .. latmin .. "′" .. ns .. " " val = val .. longdeg .. "°".. longmin .. "′" .. ew end else val = latdeg .. "°" .. latmin .. "′" .. latsec .. "″" .. ns .. " " val = val .. longdeg .. "°" .. longmin .. "′" .. longsec .. "″" .. ew end end end ------------------------------------ elseif dtype == "monolingualtext" then -- data type is Monolingual text: -- has mainsnak.datavalue.value as a table containing language/text pairs -- collect all the values in 'out' and languages in 'mlt' and process them later val = pre .. dv.text .. post mlt = dv.language ------------------------------------ else -- some other data type so write a specific handler val = "unknown data type: " .. dtype end -- of datatype/unknown value/sourced check return val, mlt end ------------------------------------------------------------------------------- -- propertyvalueandquals takes a property object, the arguments passed from frame, -- and a qualifier propertyID. -- It returns a sequence (table) of values representing the values of that property -- and qualifiers that match the qualifierID if supplied. ------------------------------------------------------------------------------- -- Dependencies: parseParam(); sourced(); labelOrId(); i18n.latestdatequalifier(); format_Date(); -- makeOrdinal(); roundto(); decimalPrecision(); decimalToDMS(); assembleoutput(); ------------------------------------------------------------------------------- local function propertyvalueandquals(objproperty, args, qualID) -- needs this style of declaration because it's re-entrant -- onlysourced is a boolean passed to return only values sourced to other than Wikipedia -- if nothing or an empty string is passed set it true local onlysrc = parseParam(args.onlysourced or args.osd, true) -- linked is a a boolean that enables the link to a local page via sitelink -- if nothing or an empty string is passed set it true local linked = parseParam(args.linked, true) -- prefix is a string that may be nil, empty (""), or a string of characters -- this is prefixed to each value -- useful when when multiple values are returned -- any double-quotes " are stripped out, so that spaces may be passed local prefix = (args.prefix or ""):gsub('"', '') -- postfix is a string that may be nil, empty (""), or a string of characters -- this is postfixed to each value -- useful when when multiple values are returned -- any double-quotes " are stripped out, so that spaces may be passed local postfix = (args.postfix or ""):gsub('"', '') -- linkprefix is a string that may be nil, empty (""), or a string of characters -- this creates a link and is then prefixed to each value -- useful when when multiple values are returned and indirect links are needed -- any double-quotes " are stripped out, so that spaces may be passed local lprefix = (args.linkprefix or args.lp or ""):gsub('"', '') -- linkpostfix is a string that may be nil, empty (""), or a string of characters -- this is postfixed to each value when linking is enabled with lprefix -- useful when when multiple values are returned -- any double-quotes " are stripped out, so that spaces may be passed local lpostfix = (args.linkpostfix or ""):gsub('"', '') -- wdlinks is a boolean passed to enable links to Wikidata when no article exists -- if nothing or an empty string is passed set it false local wdl = parseParam(args.wdlinks or args.wdl, false) -- unitabbr is a boolean passed to enable unit abbreviations for common units -- if nothing or an empty string is passed set it false local uabbr = parseParam(args.unitabbr or args.uabbr, false) -- qualsonly is a boolean passed to return just the qualifiers -- if nothing or an empty string is passed set it false local qualsonly = parseParam(args.qualsonly or args.qo, false) -- maxvals is a string that may be nil, empty (""), or a number -- this determines how many items may be returned when multiple values are available -- setting it = 1 is useful where the returned string is used within another call, e.g. image local maxvals = tonumber(args.maxvals) or 0 -- pd (plain date) is a string: yes/true/1 no/false/0 adj -- to disable/enable "sourcing cirumstances" or use adjectival form for the plain date local pd = args.plaindate or args.pd or "no" args.pd = pd -- allow qualifiers to have a different date format; default to year unless qualsonly is set args.qdf = args.qdf or args.qualifierdateformat or args.df or (not qualsonly and "y") local lang = args.lang or findLang().code -- qualID is a string list of wanted qualifiers or "ALL" qualID = qualID or "" -- capitalise list of wanted qualifiers and substitute "DATES" qualID = qualID:upper():gsub("DATES", "P580, P582") local allflag = (qualID == "ALL") -- create table of wanted qualifiers as key local qwanted = {} -- create sequence of wanted qualifiers local qorder = {} for q in mw.text.gsplit(qualID, "%p") do -- split at punctuation and iterate local qtrim = mw.text.trim(q) if qtrim ~= "" then qwanted[mw.text.trim(q)] = true qorder[#qorder+1] = qtrim end end -- qsep is the output separator for rendering qualifier list local qsep = (args.qsep or ""):gsub('"', '') -- qargs are the arguments to supply to assembleoutput() local qargs = { ["osd"] = "false", ["linked"] = tostring(linked), ["prefix"] = args.qprefix, ["postfix"] = args.qpostfix, ["linkprefix"] = args.qlinkprefix or args.qlp, ["linkpostfix"] = args.qlinkpostfix, ["wdl"] = "false", ["unitabbr"] = tostring(uabbr), ["maxvals"] = 0, ["sorted"] = tostring(args.qsorted), ["noicon"] = "true", ["list"] = args.qlist, ["sep"] = qsep, ["langobj"] = args.langobj, ["lang"] = args.langobj.code, ["df"] = args.qdf, ["sn"] = parseParam(args.qsn or args.qshortname, false), } -- all proper values of a Wikidata property will be the same type as the first -- qualifiers don't have a mainsnak, properties do local datatype = objproperty[1].datatype or objproperty[1].mainsnak.datatype -- out[] holds the a list of returned values for this property -- mlt[] holds the language code if the datatype is monolingual text local out = {} local mlt = {} for k, v in ipairs(objproperty) do local hasvalue = true if (onlysrc and not sourced(v)) then -- no value: it isn't sourced when onlysourced=true hasvalue = false else local val, lcode = rendersnak(v, args, linked, lprefix, lpostfix, prefix, postfix, uabbr) if not val then hasvalue = false -- rank doesn't match elseif qualsonly and qualID then -- suppress value returned: only qualifiers are requested else out[#out+1], mlt[#out+1] = val, lcode end end -- See if qualifiers are to be returned: local snak = v.mainsnak or v if hasvalue and v.qualifiers and qualID ~= "" and snak.snaktype~="novalue" then -- collect all wanted qualifier values returned in qlist, indexed by propertyID local qlist = {} local timestart, timeend = "", "" -- loop through qualifiers for k1, v1 in pairs(v.qualifiers) do if allflag or qwanted[k1] then if k1 == "P1326" then local ts = v1[1].datavalue.value.time local dp = v1[1].datavalue.value.precision qlist[k1] = dateFormat(ts, dp, args.qdf, args.bc, pd, "", lang, "before") elseif k1 == "P1319" then local ts = v1[1].datavalue.value.time local dp = v1[1].datavalue.value.precision qlist[k1] = dateFormat(ts, dp, args.qdf, args.bc, pd, "", lang, "after") elseif k1 == "P580" then timestart = propertyvalueandquals(v1, qargs)[1] or "" -- treat only one start time as valid elseif k1 == "P582" then timeend = propertyvalueandquals(v1, qargs)[1] or "" -- treat only one end time as valid else local q = assembleoutput(propertyvalueandquals(v1, qargs), qargs) -- we already deal with circa via 'sourcing circumstances' if the datatype was time -- circa may be either linked or unlinked *** internationalise later *** if datatype ~= "time" or q ~= "circa" and not (type(q) == "string" and q:find("circa]]")) then qlist[k1] = q end end end -- of test for wanted end -- of loop through qualifiers -- set date separator local t = timestart .. timeend -- *** internationalise date separators later *** local dsep = "–" if t:find("%s") or t:find(" ") then dsep = " – " end -- set the order for the list of qualifiers returned; start time and end time go last if next(qlist) then local qlistout = {} if allflag then for k2, v2 in pairs(qlist) do qlistout[#qlistout+1] = v2 end else for i2, v2 in ipairs(qorder) do qlistout[#qlistout+1] = qlist[v2] end end if t ~= "" then qlistout[#qlistout+1] = timestart .. dsep .. timeend end local qstr = assembleoutput(qlistout, qargs) if qualsonly then out[#out+1] = qstr else out[#out] = out[#out] .. " (" .. qstr .. ")" end elseif t ~= "" then if qualsonly then if timestart == "" then out[#out+1] = timeend elseif timeend == "" then out[#out+1] = timestart else out[#out+1] = timestart .. dsep .. timeend end else out[#out] = out[#out] .. " (" .. timestart .. dsep .. timeend .. ")" end end end -- of test for qualifiers wanted if maxvals > 0 and #out >= maxvals then break end end -- of for each value loop -- we need to pick one value to return if the datatype was "monolingualtext" -- if there's only one value, use that -- otherwise look through the fallback languages for a match if datatype == "monolingualtext" and #out >1 then lang = mw.text.split( lang, '-', true )[1] local fbtbl = mw.language.getFallbacksFor( lang ) table.insert( fbtbl, 1, lang ) local bestval = "" local found = false for idx1, lang1 in ipairs(fbtbl) do for idx2, lang2 in ipairs(mlt) do if (lang1 == lang2) and not found then bestval = out[idx2] found = true break end end -- loop through values of property end -- loop through fallback languages if found then -- replace output table with a table containing the best value out = { bestval } else -- more than one value and none of them on the list of fallback languages -- sod it, just give them the first one out = { out[1] } end end return out end ------------------------------------------------------------------------------- -- Common code for p.getValueByQual and p.getValueByLang ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; assembleoutput; ------------------------------------------------------------------------------- local _getvaluebyqual = function(frame, qualID, checkvalue) -- The property ID that will have a qualifier is the first unnamed parameter local propertyID = mw.text.trim(frame.args[1] or "") if propertyID == "" then return "no property supplied" end if qualID == "" then return "no qualifier supplied" end -- onlysourced is a boolean passed to return property values -- only when property values are sourced to something other than Wikipedia -- if nothing or an empty string is passed set it true -- if "false" or "no" or 0 is passed set it false local onlysrc = parseParam(frame.args.onlysourced or frame.args.osd, true) -- set the requested ranks flags frame.args.reqranks = setRanks(frame.args.rank) -- set a language object and code in the frame.args table frame.args.langobj = findLang(frame.args.lang) frame.args.lang = frame.args.langobj.code local args = frame.args -- check for locally supplied parameter in second unnamed parameter -- success means no local parameter and the property exists local qid, props = parseInput(frame, args[2], propertyID) local linked = parseParam(args.linked, true) local lpre = (args.linkprefix or args.lp or ""):gsub('"', '') local lpost = (args.linkpostfix or ""):gsub('"', '') local pre = (args.prefix or ""):gsub('"', '') local post = (args.postfix or ""):gsub('"', '') local uabbr = parseParam(args.unitabbr or args.uabbr, false) local filter = (args.unit or ""):upper() local maxvals = tonumber(args.maxvals) or 0 if filter == "" then filter = nil end if qid then local out = {} -- Scan through the values of the property -- we want something like property is "pronunciation audio (P443)" in propertyID -- with a qualifier like "language of work or name (P407)" in qualID -- whose value has the required ID, like "British English (Q7979)", in qval for k1, v1 in ipairs(props) do if v1.mainsnak.snaktype == "value" then -- check if it has the right qualifier local v1q = v1.qualifiers if v1q and v1q[qualID] then if onlysrc == false or sourced(v1) then -- if we've got this far, we have a (sourced) claim with qualifiers -- so see if matches the required value -- We'll only deal with wikibase-items and strings for now if v1q[qualID][1].datatype == "wikibase-item" then if checkvalue(v1q[qualID][1].datavalue.value.id) then out[#out + 1] = rendersnak(v1, args, linked, lpre, lpost, pre, post, uabbr, filter) end elseif v1q[qualID][1].datatype == "string" then if checkvalue(v1q[qualID][1].datavalue.value) then out[#out + 1] = rendersnak(v1, args, linked, lpre, lpost, pre, post, uabbr, filter) end end end -- of check for sourced end -- of check for matching required value and has qualifiers else return nil end -- of check for string if maxvals > 0 and #out >= maxvals then break end end -- of loop through values of propertyID return assembleoutput(out, frame.args, qid, propertyID) else return props -- either local parameter or nothing end -- of test for success return nil end ------------------------------------------------------------------------------- -- _location takes Q-id and follows P276 (location) -- or P131 (located in the administrative territorial entity) or P706 (located on terrain feature) -- from the initial item to higher level territories/locations until it reaches the highest. -- An optional boolean, 'first', determines whether the first item is returned (default: false). -- An optional boolean 'skip' toggles the display to skip to the last item (default: false). -- It returns a table containing the locations - linked where possible, except for the highest. ------------------------------------------------------------------------------- -- Dependencies: findLang(); labelOrId(); linkedItem ------------------------------------------------------------------------------- local _location = function(qid, first, skip) first = parseParam(first, false) skip = parseParam(skip, false) local locs = {"P276", "P131", "P706"} local out = {} local langcode = findLang():getCode() local finished = false local count = 0 local prevqid = "Q0" repeat local prop for i1, v1 in ipairs(locs) do local proptbl = mw.wikibase.getBestStatements(qid, v1) if #proptbl > 1 then -- there is more than one higher location local prevP131, prevP131id if prevqid ~= "Q0" then prevP131 = mw.wikibase.getBestStatements(prevqid, "P131")[1] prevP131id = prevP131 and prevP131.mainsnak.datavalue and prevP131.mainsnak.datavalue.value.id end for i2, v2 in ipairs(proptbl) do local parttbl = v2.qualifiers and v2.qualifiers.P518 if parttbl then -- this higher location has qualifier 'applies to part' (P518) for i3, v3 in ipairs(parttbl) do if v3.snaktype == "value" and v3.datavalue.value.id == prevqid then -- it has a value equal to the previous location prop = proptbl[i2] break end -- of test for matching last location end -- of loop through values of 'applies to part' else -- there's no qualifier 'applies to part' (P518) -- so check if the previous location had a P131 that matches this alternate if qid == prevP131id then prop = proptbl[i2] break end -- of test for matching previous P131 end end -- of loop through parent locations -- fallback to second value if match not found prop = prop or proptbl[2] elseif #proptbl > 0 then prop = proptbl[1] end if prop then break end end -- check if it's an instance of (P31) a country (Q6256) or sovereign state (Q3624078) -- and terminate the chain if it is local inst = mw.wikibase.getAllStatements(qid, "P31") if #inst > 0 then for k, v in ipairs(inst) do local instid = v.mainsnak.datavalue and v.mainsnak.datavalue.value.id -- stop if it's a country (or a country within the United Kingdom if skip is true) if instid == "Q6256" or instid == "Q3624078" or (skip and instid == "Q3336843") then prop = nil -- this will ensure this is treated as top-level location break end end end -- get the name of this location and update qid to point to the parent location if prop and prop.mainsnak.datavalue then if not skip or count == 0 then local args = { lprefix = ":" } out[#out+1] = linkedItem(qid, args) -- get a linked value if we can end qid, prevqid = prop.mainsnak.datavalue.value.id, qid else -- This is top-level location, so get short name except when this is the first item -- Use full label if there's no short name or this is the first item local prop1813 = mw.wikibase.getAllStatements(qid, "P1813") -- if there's a short name and this isn't the only item if prop1813[1] and (#out > 0)then local shortname -- short name is monolingual text, so look for match to the local language -- choose the shortest 'short name' in that language for k, v in pairs(prop1813) do if v.mainsnak.datavalue.value.language == langcode then local name = v.mainsnak.datavalue.value.text if (not shortname) or (#name < #shortname) then shortname = name end end end -- add the shortname if one is found, fallback to the label -- but skip it if it's "USA" if shortname ~= "USA" then out[#out+1] = shortname or labelOrId(qid) else if skip then out[#out+1] = "US" end end else -- no shortname, so just add the label local loc = labelOrId(qid) -- exceptions go here: if loc == "United States of America" then out[#out+1] = "United States" else out[#out+1] = loc end end finished = true end count = count + 1 until finished or count >= 10 -- limit to 10 levels to avoid infinite loops -- remove the first location if not required if not first then table.remove(out, 1) end -- we might have duplicate text for consecutive locations, so remove them if #out > 2 then local plain = {} for i, v in ipairs(out) do -- strip any links plain[i] = v:gsub("^%[%[[^ ]* ", ""):gsub("]]$", "") end local idx = 2 repeat if plain[idx] == plain[idx-1] then -- duplicate found local removeidx = 0 if (plain[idx] ~= out[idx]) and (plain[idx-1] == out[idx-1]) then -- only second one is linked, so drop the first removeidx = idx - 1 elseif (plain[idx] == out[idx]) and (plain[idx-1] ~= out[idx-1]) then -- only first one is linked, so drop the second removeidx = idx else -- pick one removeidx = idx - (os.time()%2) end table.remove(out, removeidx) table.remove(plain, removeidx) else idx = idx +1 end until idx >= #out end return out end ------------------------------------------------------------------------------- -- _getsumofparts scans the property 'has part' (P527) for values matching a list. -- The list (args.vlist) consists of a string of Qids separated by spaces or any usual punctuation. -- If the matched values have a qualifer 'quantity' (P1114), those quantites are summed. -- The sum is returned as a number (i.e. 0 if none) -- a table of arguments is supplied implementing the usual parameters. ------------------------------------------------------------------------------- -- Dependencies: setRanks; parseParam; parseInput; sourced; assembleoutput; ------------------------------------------------------------------------------- local _getsumofparts = function(args) local vallist = (args.vlist or ""):upper() if vallist == "" then return end args.reqranks = setRanks(args.rank) local f = {} f.args = args local qid, props = parseInput(f, "", "P527") if not qid then return 0 end local onlysrc = parseParam(args.onlysourced or args.osd, true) local sum = 0 for k1, v1 in ipairs(props) do if (onlysrc == false or sourced(v1)) and v1.mainsnak.snaktype == "value" and v1.mainsnak.datavalue.type == "wikibase-entityid" and vallist:match( v1.mainsnak.datavalue.value.id ) and v1.qualifiers then local quals = v1.qualifiers["P1114"] if quals then for k2, v2 in ipairs(quals) do sum = sum + v2.datavalue.value.amount end end end end return sum end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Public functions ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- _getValue makes the functionality of getValue available to other modules ------------------------------------------------------------------------------- -- Dependencies: setRanks; parseInput; propertyvalueandquals; assembleoutput; parseParam; sourced; -- labelOrId; i18n.latestdatequalifier; format_Date; makeOrdinal; roundto; decimalPrecision; decimalToDMS; ------------------------------------------------------------------------------- p._getValue = function(args) -- parameter sets for commonly used groups of parameters local paraset = tonumber(args.ps or args.parameterset or 0) if paraset == 1 then -- a common setting args.rank = "best" args.fetchwikidata = "ALL" args.onlysourced = "no" args.noicon = "true" elseif paraset == 2 then -- equivalent to raw args.rank = "best" args.fetchwikidata = "ALL" args.onlysourced = "no" args.noicon = "true" args.linked = "no" args.pd = "true" elseif paraset == 3 then -- third set goes here end -- implement eid parameter local eid = args.eid if eid == "" then return nil elseif eid then args.qid = eid end local propertyID = mw.text.trim(args[1] or "") args.reqranks = setRanks(args.rank) -- replacetext (rt) is a string that is returned instead of any non-empty Wikidata value -- this is useful for tracking and debugging, so we set fetchwikidata=ALL to fill the whitelist local replacetext = mw.text.trim(args.rt or args.replacetext or "") if replacetext ~= "" then args.fetchwikidata = "ALL" end local f = {} f.args = args local entityid, props = parseInput(f, f.args[2], propertyID) if not entityid then return props -- either the input parameter or nothing end -- qual is a string containing the property ID of the qualifier(s) to be returned -- if qual == "ALL" then all qualifiers returned -- if qual == "DATES" then qualifiers P580 (start time) and P582 (end time) returned -- if nothing or an empty string is passed set it nil -> no qualifiers returned local qualID = mw.text.trim(args.qual or ""):upper() if qualID == "" then qualID = nil end -- set a language object and code in the args table args.langobj = findLang(args.lang) args.lang = args.langobj.code -- table 'out' stores the return value(s): local out = propertyvalueandquals(props, args, qualID) -- format the table of values and return it as a string: return assembleoutput(out, args, entityid, propertyID) end ------------------------------------------------------------------------------- -- getValue is used to get the value(s) of a property -- The property ID is passed as the first unnamed parameter and is required. -- A locally supplied parameter may optionaly be supplied as the second unnamed parameter. -- The function will now also return qualifiers if parameter qual is supplied ------------------------------------------------------------------------------- -- Dependencies: _getValue; setRanks; parseInput; propertyvalueandquals; assembleoutput; parseParam; sourced; -- labelOrId; i18n.latestdatequalifier; format_Date; makeOrdinal; roundto; decimalPrecision; decimalToDMS; ------------------------------------------------------------------------------- p.getValue = function(frame) local args= frame.args if not args[1] then args = frame:getParent().args if not args[1] then return i18n.errors["No property supplied"] end end return p._getValue(args) end ------------------------------------------------------------------------------- -- getPreferredValue is used to get a value, -- (or a comma separated list of them if multiple values exist). -- If preferred ranks are set, it will return those values, otherwise values with normal ranks -- now redundant to getValue with rank=best ------------------------------------------------------------------------------- -- Dependencies: p.getValue; setRanks; parseInput; propertyvalueandquals; assembleoutput; -- parseParam; sourced; labelOrId; i18n.latestdatequalifier; format_Date; -- makeOrdinal; roundto; decimalPrecision; decimalToDMS; ------------------------------------------------------------------------------- p.getPreferredValue = function(frame) frame.args.rank = "best" return p.getValue(frame) end ------------------------------------------------------------------------------- -- getCoords is used to get coordinates for display in an infobox -- whitelist and blacklist are implemented -- optional 'display' parameter is allowed, defaults to nil - was "inline, title" ------------------------------------------------------------------------------- -- Dependencies: setRanks(); parseInput(); decimalPrecision(); ------------------------------------------------------------------------------- p.getCoords = function(frame) local propertyID = "P625" -- if there is a 'display' parameter supplied, use it -- otherwise default to nothing local disp = frame.args.display or "" if disp == "" then disp = nil -- default to not supplying display parameter, was "inline, title" end -- there may be a format parameter to switch from deg/min/sec to decimal degrees -- default is deg/min/sec -- decimal degrees needs format = dec local form = (frame.args.format or ""):lower():sub(1,3) if form ~= "dec" then form = "dms" end -- just deal with best values frame.args.reqranks = setRanks("best") local qid, props = parseInput(frame, frame.args[1], propertyID) if not qid then return props -- either local parameter or nothing else local dv = props[1].mainsnak.datavalue.value local lat, long, prec = dv.latitude, dv.longitude, dv.precision lat = decimalPrecision(lat, prec) long = decimalPrecision(long, prec) local lat_long = { lat, long } lat_long["display"] = disp lat_long["format"] = form -- invoke template Coord with the values stored in the table return frame:expandTemplate{title = 'coord', args = lat_long} end end ------------------------------------------------------------------------------- -- getQualifierValue is used to get a formatted value of a qualifier -- -- The call needs: a property (the unnamed parameter or 1=) -- a target value for that property (pval=) -- a qualifier for that target value (qual=) -- The usual whitelisting and blacklisting of the property is implemented -- The boolean onlysourced= parameter can be set to return nothing -- when the property is unsourced (or only sourced to Wikipedia) ------------------------------------------------------------------------------- -- Dependencies: parseParam(); setRanks(); parseInput(); sourced(); -- propertyvalueandquals(); assembleoutput(); -- labelOrId(); i18n.latestdatequalifier(); format_Date(); -- findLang(); makeOrdinal(); roundto(); decimalPrecision(); decimalToDMS(); ------------------------------------------------------------------------------- p.getQualifierValue = function(frame) -- The property ID that will have a qualifier is the first unnamed parameter local propertyID = mw.text.trim(frame.args[1] or "") -- The value of the property we want to match whose qualifier value is to be returned -- is passed in named parameter pval= local propvalue = frame.args.pval -- The property ID of the qualifier -- whose value is to be returned is passed in named parameter qual= local qualifierID = frame.args.qual -- A filter can be set like this: filter=P642==Q22674854 local filter, fprop, fval local ftable = mw.text.split(frame.args.filter or "", "==") if ftable[2] then fprop = mw.text.trim(ftable[1]) fval = mw.text.trim(ftable[2]) filter = true end -- onlysourced is a boolean passed to return qualifiers -- only when property values are sourced to something other than Wikipedia -- if nothing or an empty string is passed set it true -- if "false" or "no" or 0 is passed set it false local onlysrc = parseParam(frame.args.onlysourced or frame.args.osd, true) -- set a language object and language code in the frame.args table frame.args.langobj = findLang(frame.args.lang) frame.args.lang = frame.args.langobj.code -- set the requested ranks flags frame.args.reqranks = setRanks(frame.args.rank) -- check for locally supplied parameter in second unnamed parameter -- success means no local parameter and the property exists local qid, props = parseInput(frame, frame.args[2], propertyID) if qid then local out = {} -- Scan through the values of the property -- we want something like property is P793, significant event (in propertyID) -- whose value is something like Q385378, construction (in propvalue) -- then we can return the value(s) of a qualifier such as P580, start time (in qualifierID) for k1, v1 in pairs(props) do if v1.mainsnak.snaktype == "value" and v1.mainsnak.datavalue.type == "wikibase-entityid" then -- It's a wiki-linked value, so check if it's the target (in propvalue) and if it has qualifiers if v1.mainsnak.datavalue.value.id == propvalue and v1.qualifiers then if onlysrc == false or sourced(v1) then -- if we've got this far, we have a (sourced) claim with qualifiers -- which matches the target, so apply the filter and find the value(s) of the qualifier we want if not filter or (v1.qualifiers[fprop] and v1.qualifiers[fprop][1].datavalue.value.id == fval) then local quals = v1.qualifiers[qualifierID] if quals then -- can't reference qualifer, so set onlysourced = "no" (args are strings, not boolean) local qargs = frame.args qargs.onlysourced = "no" local vals = propertyvalueandquals(quals, qargs, qid) for k, v in ipairs(vals) do out[#out + 1] = v end end end end -- of check for sourced end -- of check for matching required value and has qualifiers end -- of check for wikibase entity end -- of loop through values of propertyID return assembleoutput(out, frame.args, qid, propertyID) else return props -- either local parameter or nothing end -- of test for success return nil end ------------------------------------------------------------------------------- -- getSumOfParts scans the property 'has part' (P527) for values matching a list. -- The list is passed in parameter vlist. -- It consists of a string of Qids separated by spaces or any usual punctuation. -- If the matched values have a qualifier 'quantity' (P1114), those quantities are summed. -- The sum is returned as a number or nothing if zero. ------------------------------------------------------------------------------- -- Dependencies: _getsumofparts; ------------------------------------------------------------------------------- p.getSumOfParts = function(frame) local sum = _getsumofparts(frame.args) if sum == 0 then return end return sum end ------------------------------------------------------------------------------- -- getValueByQual gets the value of a property which has a qualifier with a given entity value -- The call needs: -- a property ID (the unnamed parameter or 1=Pxxx) -- the ID of a qualifier for that property (qualID=Pyyy) -- either the Wikibase-entity ID of a value for that qualifier (qvalue=Qzzz) -- or a string value for that qualifier (qvalue=abc123) -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented ------------------------------------------------------------------------------- -- Dependencies: _getvaluebyqual; parseParam; setRanks; parseInput; sourced; -- assembleoutput; ------------------------------------------------------------------------------- p.getValueByQual = function(frame) local qualID = frame.args.qualID -- The Q-id of the value for the qualifier we want to match is in named parameter qvalue= local qval = frame.args.qvalue or "" if qval == "" then return "no qualifier value supplied" end local function checkQID(id) return id == qval end return _getvaluebyqual(frame, qualID, checkQID) end ------------------------------------------------------------------------------- -- getValueByLang gets the value of a property which has a qualifier P407 -- ("language of work or name") whose value has the given language code -- The call needs: -- a property ID (the unnamed parameter or 1=Pxxx) -- the MediaWiki language code to match the language (lang=xx[-yy]) -- (if no code is supplied, it uses the default language) -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented ------------------------------------------------------------------------------- -- Dependencies: _getvaluebyqual; parseParam; setRanks; parseInput; sourced; assembleoutput; ------------------------------------------------------------------------------- p.getValueByLang = function(frame) -- The language code for the qualifier we want to match is in named parameter lang= local langcode = findLang(frame.args.lang).code local function checkLanguage(id) -- id should represent a language like "British English (Q7979)" -- it should have string property "Wikimedia language code (P424)" -- qlcode will be a table: local qlcode = mw.wikibase.getBestStatements(id, "P424") if (#qlcode > 0) and (qlcode[1].mainsnak.datavalue.value == langcode) then return true end end return _getvaluebyqual(frame, "P407", checkLanguage) end ------------------------------------------------------------------------------- -- getValueByRefSource gets the value of a property which has a reference "stated in" (P248) -- whose value has the given entity-ID. -- The call needs: -- a property ID (the unnamed parameter or 1=Pxxx) -- the entity ID of a value to match where the reference is stated in (match=Qzzz) -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p.getValueByRefSource = function(frame) -- The property ID that we want to check is the first unnamed parameter local propertyID = mw.text.trim(frame.args[1] or ""):upper() if propertyID == "" then return "no property supplied" end -- The Q-id of the value we want to match is in named parameter qvalue= local qval = (frame.args.match or ""):upper() if qval == "" then qval = "Q21540096" end local unit = (frame.args.unit or ""):upper() if unit == "" then unit = "Q4917" end local onlysrc = parseParam(frame.args.onlysourced or frame.args.osd, true) -- set the requested ranks flags frame.args.reqranks = setRanks(frame.args.rank) -- set a language object and code in the frame.args table frame.args.langobj = findLang(frame.args.lang) frame.args.lang = frame.args.langobj.code local linked = parseParam(frame.args.linked, true) local uabbr = parseParam(frame.args.uabbr or frame.args.unitabbr, false) -- qid not nil means no local parameter and the property exists local qid, props = parseInput(frame, frame.args[2], propertyID) if qid then local out = {} local mlt= {} for k1, v1 in ipairs(props) do if onlysrc == false or sourced(v1) then if v1.references then for k2, v2 in ipairs(v1.references) do if v2.snaks.P248 then for k3, v3 in ipairs(v2.snaks.P248) do if v3.datavalue.value.id == qval then out[#out+1], mlt[#out+1] = rendersnak(v1, frame.args, linked, "", "", "", "", uabbr, unit) if not mlt[#out] then -- we only need one match per property value -- unless datatype was monolingual text break end end -- of test for match end -- of loop through values "stated in" end -- of test that "stated in" exists end -- of loop through references end -- of test that references exist end -- of test for sourced end -- of loop through values of propertyID if #mlt > 0 then local langcode = frame.args.lang langcode = mw.text.split( langcode, '-', true )[1] local fbtbl = mw.language.getFallbacksFor( langcode ) table.insert( fbtbl, 1, langcode ) local bestval = "" local found = false for idx1, lang1 in ipairs(fbtbl) do for idx2, lang2 in ipairs(mlt) do if (lang1 == lang2) and not found then bestval = out[idx2] found = true break end end -- loop through values of property end -- loop through fallback languages if found then -- replace output table with a table containing the best value out = { bestval } else -- more than one value and none of them on the list of fallback languages -- sod it, just give them the first one out = { out[1] } end end return assembleoutput(out, frame.args, qid, propertyID) else return props -- no property or local parameter supplied end -- of test for success end ------------------------------------------------------------------------------- -- getPropertyIDs takes most of the usual parameters. -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented. -- It returns the Entity-IDs (Qids) of the values of a property if it is a Wikibase-Entity. -- Otherwise it returns nothing. ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p._getPropertyIDs = function(args) args.reqranks = setRanks(args.rank) args.langobj = findLang(args.lang) args.lang = args.langobj.code -- change default for noicon to true args.noicon = tostring(parseParam(args.noicon or "", true)) local f = {} f.args = args local pid = mw.text.trim(args[1] or ""):upper() -- get the qid and table of claims for the property, or nothing and the local value passed local qid, props = parseInput(f, args[2], pid) if not qid then return props end if not props[1] then return nil end local onlysrc = parseParam(args.onlysourced or args.osd, true) local maxvals = tonumber(args.maxvals) or 0 local out = {} for i, v in ipairs(props) do local snak = v.mainsnak if ( snak.datatype == "wikibase-item" ) and ( v.rank and args.reqranks[v.rank:sub(1, 1)] ) and ( snak.snaktype == "value" ) and ( sourced(v) or not onlysrc ) then out[#out+1] = snak.datavalue.value.id end if maxvals > 0 and #out >= maxvals then break end end return assembleoutput(out, args, qid, pid) end p.getPropertyIDs = function(frame) local args = frame.args return p._getPropertyIDs(args) end ------------------------------------------------------------------------------- -- getQualifierIDs takes most of the usual parameters. -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented. -- It takes a property-id as the first unnamed parameter, and an optional parameter qlist -- which is a list of qualifier property-ids to search for (default is "ALL") -- It returns the Entity-IDs (Qids) of the values of a property if it is a Wikibase-Entity. -- Otherwise it returns nothing. ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p.getQualifierIDs = function(frame) local args = frame.args args.reqranks = setRanks(args.rank) args.langobj = findLang(args.lang) args.lang = args.langobj.code -- change default for noicon to true args.noicon = tostring(parseParam(args.noicon or "", true)) local f = {} f.args = args local pid = mw.text.trim(args[1] or ""):upper() -- get the qid and table of claims for the property, or nothing and the local value passed local qid, props = parseInput(f, args[2], pid) if not qid then return props end if not props[1] then return nil end -- get the other parameters local onlysrc = parseParam(args.onlysourced or args.osd, true) local maxvals = tonumber(args.maxvals) or 0 local qlist = args.qlist or "" if qlist == "" then qlist = "ALL" end qlist = qlist:gsub("[%p%s]+", " ") .. " " local out = {} for i, v in ipairs(props) do local snak = v.mainsnak if ( v.rank and args.reqranks[v.rank:sub(1, 1)] ) and ( snak.snaktype == "value" ) and ( sourced(v) or not onlysrc ) then if v.qualifiers then for k1, v1 in pairs(v.qualifiers) do if qlist == "ALL " or qlist:match(k1 .. " ") then for i2, v2 in ipairs(v1) do if v2.datatype == "wikibase-item" and v2.snaktype == "value" then out[#out+1] = v2.datavalue.value.id end -- of test that id exists end -- of loop through qualifier values end -- of test for kq in qlist end -- of loop through qualifiers end -- of test for qualifiers end -- of test for rank value, sourced, and value exists if maxvals > 0 and #out >= maxvals then break end end -- of loop through property values return assembleoutput(out, args, qid, pid) end ------------------------------------------------------------------------------- -- getPropOfProp takes two propertyIDs: prop1 and prop2 (as well as the usual parameters) -- If the value(s) of prop1 are of type "wikibase-item" then it returns the value(s) of prop2 -- of each of those wikibase-items. -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p._getPropOfProp = function(args) -- parameter sets for commonly used groups of parameters local paraset = tonumber(args.ps or args.parameterset or 0) if paraset == 1 then -- a common setting args.rank = "best" args.fetchwikidata = "ALL" args.onlysourced = "no" args.noicon = "true" elseif paraset == 2 then -- equivalent to raw args.rank = "best" args.fetchwikidata = "ALL" args.onlysourced = "no" args.noicon = "true" args.linked = "no" args.pd = "true" elseif paraset == 3 then -- third set goes here end args.reqranks = setRanks(args.rank) args.langobj = findLang(args.lang) args.lang = args.langobj.code local pid1 = args.prop1 or args.pid1 or "" local pid2 = args.prop2 or args.pid2 or "" if pid1 == "" or pid2 == "" then return nil end local f = {} f.args = args local qid1, statements1 = parseInput(f, args[1], pid1) -- parseInput nulls empty args[1] and returns args[1] if nothing on Wikidata if not qid1 then return statements1 end -- otherwise it returns the qid and a table for the statement local onlysrc = parseParam(args.onlysourced or args.osd, true) local maxvals = tonumber(args.maxvals) or 0 local qualID = mw.text.trim(args.qual or ""):upper() if qualID == "" then qualID = nil end local out = {} for k, v in ipairs(statements1) do if not onlysrc or sourced(v) then local snak = v.mainsnak if snak.datatype == "wikibase-item" and snak.snaktype == "value" then local qid2 = snak.datavalue.value.id local statements2 = {} if args.reqranks.b then statements2 = mw.wikibase.getBestStatements(qid2, pid2) else statements2 = mw.wikibase.getAllStatements(qid2, pid2) end if statements2[1] then local out2 = propertyvalueandquals(statements2, args, qualID) out[#out+1] = assembleoutput(out2, args, qid2, pid2) end end -- of test for valid property1 value end -- of test for sourced if maxvals > 0 and #out >= maxvals then break end end -- of loop through values of property1 return assembleoutput(out, args, qid1, pid1) end p.getPropOfProp = function(frame) local args= frame.args if not args.prop1 and not args.pid1 then args = frame:getParent().args if not args.prop1 and not args.pid1 then return i18n.errors["No property supplied"] end end return p._getPropOfProp(args) end ------------------------------------------------------------------------------- -- getAwardCat takes most of the usual parameters. If the item has values of P166 (award received), -- then it examines each of those awards for P2517 (category for recipients of this award). -- If it exists, it returns the corresponding category, -- with the item's P734 (family name) as sort key, or no sort key if there is no family name. -- The sort key may be overridden by the parameter sortkey (alias sk). -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p.getAwardCat = function(frame) frame.args.reqranks = setRanks(frame.args.rank) frame.args.langobj = findLang(frame.args.lang) frame.args.lang = frame.args.langobj.code local args = frame.args args.sep = " " local pid1 = args.prop1 or "P166" local pid2 = args.prop2 or "P2517" if pid1 == "" or pid2 == "" then return nil end -- locally supplied value: local localval = mw.text.trim(args[1] or "") local qid1, statements1 = parseInput(frame, localval, pid1) if not qid1 then return localval end -- linkprefix (strip quotes) local lp = (args.linkprefix or args.lp or ""):gsub('"', '') -- sort key (strip quotes, hyphens and periods): local sk = (args.sortkey or args.sk or ""):gsub('["-.]', '') -- family name: local famname = "" if sk == "" then local p734 = mw.wikibase.getBestStatements(qid1, "P734")[1] local p734id = p734 and p734.mainsnak.snaktype == "value" and p734.mainsnak.datavalue.value.id or "" famname = mw.wikibase.getSitelink(p734id) or "" -- strip namespace and disambigation local pos = famname:find(":") or 0 famname = famname:sub(pos+1):gsub("%s%(.+%)$", "") if famname == "" then local lbl = mw.wikibase.getLabel(p734id) famname = lbl and mw.text.nowiki(lbl) or "" end end local onlysrc = parseParam(args.onlysourced or args.osd, true) local maxvals = tonumber(args.maxvals) or 0 local qualID = mw.text.trim(args.qual or ""):upper() if qualID == "" then qualID = nil end local out = {} for k, v in ipairs(statements1) do if not onlysrc or sourced(v) then local snak = v.mainsnak if snak.datatype == "wikibase-item" and snak.snaktype == "value" then local qid2 = snak.datavalue.value.id local statements2 = {} if args.reqranks.b then statements2 = mw.wikibase.getBestStatements(qid2, pid2) else statements2 = mw.wikibase.getAllStatements(qid2, pid2) end if statements2[1] and statements2[1].mainsnak.snaktype == "value" then local qid3 = statements2[1].mainsnak.datavalue.value.id local sitelink = mw.wikibase.getSitelink(qid3) -- if there's no local sitelink, create the sitelink from English label if not sitelink then local lbl = mw.wikibase.getLabelByLang(qid3, "en") if lbl then if lbl:sub(1,9) == "Category:" then sitelink = mw.text.nowiki(lbl) else sitelink = "Category:" .. mw.text.nowiki(lbl) end end end if sitelink then if sk ~= "" then out[#out+1] = "[[" .. lp .. sitelink .. " " .. sk .. "]]" elseif famname ~= "" then out[#out+1] = "[[" .. lp .. sitelink .. " " .. famname .. "]]" else out[#out+1] = "[[" .. lp .. sitelink .. "]]" end -- of check for sort keys end -- of test for sitelink end -- of test for category end -- of test for wikibase item has a value end -- of test for sourced if maxvals > 0 and #out >= maxvals then break end end -- of loop through values of property1 return assembleoutput(out, args, qid1, pid1) end ------------------------------------------------------------------------------- -- getIntersectCat takes most of the usual parameters. -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented -- It takes two properties, prop1 and prop2 (e.g. occupation and country of citizenship) -- Each property's value is a wiki-base entity -- For each value of the first parameter (ranks implemented) it fetches the value's main category -- and then each value of the second parameter (possibly substituting a simpler description) -- then it returns all of the categories representing the intersection of those properties, -- (e.g. Category:Actors from Canada). A joining term may be supplied (e.g. join=from). -- The item's P734 (family name) is the sort key, or no sort key if there is no family name. -- The sort key may be overridden by the parameter sortkey (alias sk). ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; propertyvalueandquals assembleoutput; ------------------------------------------------------------------------------- p.getIntersectCat = function(frame) frame.args.reqranks = setRanks(frame.args.rank) frame.args.langobj = findLang(frame.args.lang) frame.args.lang = frame.args.langobj.code local args = frame.args args.sep = " " args.linked = "no" local pid1 = args.prop1 or "P106" local pid2 = args.prop2 or "P27" if pid1 == "" or pid2 == "" then return nil end local qid, statements1 = parseInput(frame, "", pid1) if not qid then return nil end local qid, statements2 = parseInput(frame, "", pid2) if not qid then return nil end -- topics like countries may have different names in categories from their label in Wikidata local subs_exists, subs = pcall(mw.loadData, "Module:WikidataIB/subs") local join = args.join or "" local onlysrc = parseParam(args.onlysourced or args.osd, true) local maxvals = tonumber(args.maxvals) or 0 -- linkprefix (strip quotes) local lp = (args.linkprefix or args.lp or ""):gsub('"', '') -- sort key (strip quotes, hyphens and periods): local sk = (args.sortkey or args.sk or ""):gsub('["-.]', '') -- family name: local famname = "" if sk == "" then local p734 = mw.wikibase.getBestStatements(qid, "P734")[1] local p734id = p734 and p734.mainsnak.snaktype == "value" and p734.mainsnak.datavalue.value.id or "" famname = mw.wikibase.getSitelink(p734id) or "" -- strip namespace and disambigation local pos = famname:find(":") or 0 famname = famname:sub(pos+1):gsub("%s%(.+%)$", "") if famname == "" then local lbl = mw.wikibase.getLabel(p734id) famname = lbl and mw.text.nowiki(lbl) or "" end end local cat1 = {} for k, v in ipairs(statements1) do if not onlysrc or sourced(v) then -- get the ID representing the value of the property local pvalID = (v.mainsnak.snaktype == "value") and v.mainsnak.datavalue.value.id if pvalID then -- get the topic's main category (P910) for that entity local p910 = mw.wikibase.getBestStatements(pvalID, "P910")[1] if p910 and p910.mainsnak.snaktype == "value" then local tmcID = p910.mainsnak.datavalue.value.id -- use sitelink or the English label for the cat local cat = mw.wikibase.getSitelink(tmcID) if not cat then local lbl = mw.wikibase.getLabelByLang(tmcID, "en") if lbl then if lbl:sub(1,9) == "Category:" then cat = mw.text.nowiki(lbl) else cat = "Category:" .. mw.text.nowiki(lbl) end end end cat1[#cat1+1] = cat end -- of test for topic's main category exists end -- of test for property has vaild value end -- of test for sourced if maxvals > 0 and #cat1 >= maxvals then break end end local cat2 = {} for k, v in ipairs(statements2) do if not onlysrc or sourced(v) then local cat = rendersnak(v, args) if subs[cat] then cat = subs[cat] end cat2[#cat2+1] = cat end if maxvals > 0 and #cat2 >= maxvals then break end end local out = {} for k1, v1 in ipairs(cat1) do for k2, v2 in ipairs(cat2) do if sk ~= "" then out[#out+1] = "[[" .. lp .. v1 .. " " .. join .. " " .. v2 .. " " .. sk .. "]]" elseif famname ~= "" then out[#out+1] = "[[" .. lp .. v1 .. " " .. join .. " " .. v2 .. " " .. famname .. "]]" else out[#out+1] = "[[" .. lp .. v1 .. " " .. join .. " " .. v2 .. "]]" end -- of check for sort keys end end args.noicon = "true" return assembleoutput(out, args, qid, pid1) end ------------------------------------------------------------------------------- -- qualsToTable takes most of the usual parameters. -- The usual whitelisting, blacklisting, onlysourced, etc. are implemented. -- A qid may be given, and the first unnamed parameter is the property ID, which is of type wikibase item. -- It takes a list of qualifier property IDs as quals= -- For a given qid and property, it creates the rows of an html table, -- each row being a value of the property (optionally only if the property matches the value in pval= ) -- each cell being the first value of the qualifier corresponding to the list in quals ------------------------------------------------------------------------------- -- Dependencies: parseParam; setRanks; parseInput; sourced; ------------------------------------------------------------------------------- p.qualsToTable = function(frame) local args = frame.args local quals = args.quals or "" if quals == "" then return "" end args.reqranks = setRanks(args.rank) local propertyID = mw.text.trim(args[1] or "") local f = {} f.args = args local entityid, props = parseInput(f, "", propertyID) if not entityid then return "" end args.langobj = findLang(args.lang) args.lang = args.langobj.code local pval = args.pval or "" local qplist = mw.text.split(quals, "%p") -- split at punctuation and make a sequential table for i, v in ipairs(qplist) do qplist[i] = mw.text.trim(v):upper() -- remove whitespace and capitalise end local col1 = args.firstcol or "" if col1 ~= "" then col1 = col1 .. "</td><td>" end local emptycell = args.emptycell or " " -- construct a 2-D array of qualifier values in qvals local qvals = {} for i, v in ipairs(props) do local skip = false if pval ~= "" then local pid = v.mainsnak.datavalue and v.mainsnak.datavalue.value.id if pid ~= pval then skip = true end end if not skip then local qval = {} local vqualifiers = v.qualifiers or {} -- go through list of wanted qualifier properties for i1, v1 in ipairs(qplist) do -- check for that property ID in the statement's qualifiers local qv, qtype if vqualifiers[v1] then qtype = vqualifiers[v1][1].datatype if qtype == "time" then if vqualifiers[v1][1].snaktype == "value" then qv = mw.wikibase.renderSnak(vqualifiers[v1][1]) qv = frame:expandTemplate{title="dts", args={qv}} else qv = "?" end elseif qtype == "url" then if vqualifiers[v1][1].snaktype == "value" then qv = mw.wikibase.renderSnak(vqualifiers[v1][1]) local display = mw.ustring.match( mw.uri.decode(qv, "WIKI"), "([%w ]+)$" ) if display then qv = "[" .. qv .. " " .. display .. "]" end end else qv = mw.wikibase.formatValue(vqualifiers[v1][1]) end end -- record either the value or a placeholder qval[i1] = qv or emptycell end -- of loop through list of qualifiers -- add the list of qualifier values as a "row" in the main list qvals[#qvals+1] = qval end end -- of for each value loop local out = {} for i, v in ipairs(qvals) do out[i] = "<tr><td>" .. col1 .. table.concat(qvals[i], "</td><td>") .. "</td></tr>" end return table.concat(out, "\n") end ------------------------------------------------------------------------------- -- getGlobe takes an optional qid of a Wikidata entity passed as qid= -- otherwise it uses the linked item for the current page. -- If returns the Qid of the globe used in P625 (coordinate location), -- or nil if there isn't one. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getGlobe = function(frame) local qid = frame.args.qid or frame.args[1] or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end local coords = mw.wikibase.getBestStatements(qid, "P625")[1] local globeid if coords and coords.mainsnak.snaktype == "value" then globeid = coords.mainsnak.datavalue.value.globe:match("(Q%d+)") end return globeid end ------------------------------------------------------------------------------- -- getCommonsLink takes an optional qid of a Wikidata entity passed as qid= -- It returns one of the following in order of preference: -- the Commons sitelink of the linked Wikidata item; -- the Commons sitelink of the topic's main category of the linked Wikidata item; ------------------------------------------------------------------------------- -- Dependencies: _getCommonslink(); _getSitelink(); parseParam() ------------------------------------------------------------------------------- p.getCommonsLink = function(frame) local oc = frame.args.onlycat or frame.args.onlycategories local fb = parseParam(frame.args.fallback or frame.args.fb, true) return _getCommonslink(frame.args.qid, oc, fb) end ------------------------------------------------------------------------------- -- getSitelink takes the qid of a Wikidata entity passed as qid= -- It takes an optional parameter wiki= to determine which wiki is to be checked for a sitelink -- If the parameter is blank, then it uses the local wiki. -- If there is a sitelink to an article available, it returns the plain text link to the article -- If there is no sitelink, it returns nil. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getSiteLink = function(frame) return _getSitelink(frame.args.qid, frame.args.wiki or mw.text.trim(frame.args[1] or "")) end ------------------------------------------------------------------------------- -- getLink has the qid of a Wikidata entity passed as the first unnamed parameter or as qid= -- If there is a sitelink to an article on the local Wiki, it returns a link to the article -- with the Wikidata label as the displayed text. -- If there is no sitelink, it returns the label as plain text. -- If there is no label in the local language, it displays the qid instead. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getLink = function(frame) local itemID = mw.text.trim(frame.args[1] or frame.args.qid or "") if itemID == "" then return end local sitelink = mw.wikibase.getSitelink(itemID) local label = labelOrId(itemID) if sitelink then return "[[:" .. sitelink .. " " .. label .. "]]" else return label end end ------------------------------------------------------------------------------- -- getLabel has the qid of a Wikidata entity passed as the first unnamed parameter or as qid= -- It returns the Wikidata label for the local language as plain text. -- If there is no label in the local language, it displays the qid instead. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getLabel = function(frame) local itemID = mw.text.trim(frame.args[1] or frame.args.qid or "") if itemID == "" then return end local lang = frame.args.lang or "" if lang == "" then lang = nil end local label = labelOrId(itemID, lang) return label end ------------------------------------------------------------------------------- -- label has the qid of a Wikidata entity passed as the first unnamed parameter or as qid= -- if no qid is supplied, it uses the qid associated with the current page. -- It returns the Wikidata label for the local language as plain text. -- If there is no label in the local language, it returns nil. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.label = function(frame) local qid = mw.text.trim(frame.args[1] or frame.args.qid or "") if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return end local lang = frame.args.lang or "" if lang == "" then lang = nil end local label, success = labelOrId(qid, lang) if success then return label end end ------------------------------------------------------------------------------- -- getAT (Article Title) -- has the qid of a Wikidata entity passed as the first unnamed parameter or as qid= -- If there is a sitelink to an article on the local Wiki, it returns the sitelink as plain text. -- If there is no sitelink or qid supplied, it returns nothing. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getAT = function(frame) local itemID = mw.text.trim(frame.args[1] or frame.args.qid or "") if itemID == "" then return end return mw.wikibase.getSitelink(itemID) end ------------------------------------------------------------------------------- -- getDescription has the qid of a Wikidata entity passed as qid= -- (it defaults to the associated qid of the current article if omitted) -- and a local parameter passed as the first unnamed parameter. -- Any local parameter passed (other than "Wikidata" or "none") becomes the return value. -- It returns the article description for the Wikidata entity if the local parameter is "Wikidata". -- Nothing is returned if the description doesn't exist or "none" is passed as the local parameter. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getDescription = function(frame) local desc = mw.text.trim(frame.args[1] or "") local itemID = mw.text.trim(frame.args.qid or "") if itemID == "" then itemID = nil end if desc:lower() == 'wikidata' then return mw.wikibase.getDescription(itemID) elseif desc:lower() == 'none' then return nil else return desc end end ------------------------------------------------------------------------------- -- getAliases has the qid of a Wikidata entity passed as qid= -- (it defaults to the associated qid of the current article if omitted) -- and a local parameter passed as the first unnamed parameter. -- It implements blacklisting and whitelisting with a field name of "alias" by default. -- Any local parameter passed becomes the return value. -- Otherwise it returns the aliases for the Wikidata entity with the usual list options. -- Nothing is returned if the aliases do not exist. ------------------------------------------------------------------------------- -- Dependencies: findLang(); assembleoutput() ------------------------------------------------------------------------------- p.getAliases = function(frame) local args = frame.args local fieldname = args.name or "" if fieldname == "" then fieldname = "alias" end local blacklist = args.suppressfields or args.spf or "" if blacklist:find(fieldname) then return nil end local localval = mw.text.trim(args[1] or "") if localval ~= "" then return localval end local whitelist = args.fetchwikidata or args.fwd or "" if whitelist == "" then whitelist = "NONE" end if not (whitelist == 'ALL' or whitelist:find(fieldname)) then return nil end local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid or not mw.wikibase.entityExists(qid) then return nil end local aliases = mw.wikibase.getEntity(qid).aliases if not aliases then return nil end args.langobj = findLang(args.lang) local langcode = args.langobj.code args.lang = langcode local out = {} for k1, v1 in pairs(aliases) do if v1[1].language == langcode then for k1, v2 in ipairs(v1) do out[#out+1] = v2.value end break end end return assembleoutput(out, args, qid) end ------------------------------------------------------------------------------- -- pageId returns the page id (entity ID, Qnnn) of the current page -- returns nothing if the page is not connected to Wikidata ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.pageId = function(frame) return mw.wikibase.getEntityIdForCurrentPage() end ------------------------------------------------------------------------------- -- formatDate is a wrapper to export the private function format_Date ------------------------------------------------------------------------------- -- Dependencies: format_Date(); ------------------------------------------------------------------------------- p.formatDate = function(frame) return format_Date(frame.args[1], frame.args.df, frame.args.bc) end ------------------------------------------------------------------------------- -- location is a wrapper to export the private function _location -- it takes the entity-id as qid or the first unnamed parameter -- optional boolean parameter first toggles the display of the first item -- optional boolean parameter skip toggles the display to skip to the last item -- parameter debug=<y/n> (default 'n') adds error msg if not a location ------------------------------------------------------------------------------- -- Dependencies: _location(); ------------------------------------------------------------------------------- p.location = function(frame) local debug = (frame.args.debug or ""):sub(1, 1):lower() if debug == "" then debug = "n" end local qid = mw.text.trim(frame.args.qid or frame.args[1] or ""):upper() if qid == "" then qid=mw.wikibase.getEntityIdForCurrentPage() end if not qid then if debug ~= "n" then return i18n.errors["entity-not-found"] else return nil end end local first = mw.text.trim(frame.args.first or "") local skip = mw.text.trim(frame.args.skip or "") return table.concat( _location(qid, first, skip), ", " ) end ------------------------------------------------------------------------------- -- checkBlacklist implements a test to check whether a named field is allowed -- returns true if the field is not blacklisted (i.e. allowed) -- returns false if the field is blacklisted (i.e. disallowed) -- {{#if:{{#invoke:WikidataIB checkBlacklist name=Joe suppressfields=Dave; Joe; Fred}} not blacklisted blacklisted}} -- displays "blacklisted" -- {{#if:{{#invoke:WikidataIB checkBlacklist name=Jim suppressfields=Dave; Joe; Fred}} not blacklisted blacklisted}} -- displays "not blacklisted" ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.checkBlacklist = function(frame) local blacklist = frame.args.suppressfields or frame.args.spf or "" local fieldname = frame.args.name or "" if blacklist ~= "" and fieldname ~= "" then if blacklist:find(fieldname) then return false else return true end else -- one of the fields is missing: let's call that "not on the list" return true end end ------------------------------------------------------------------------------- -- emptyor returns nil if its first unnamed argument is just punctuation, whitespace or html tags -- otherwise it returns the argument unchanged (including leading/trailing space). -- If the argument may contain "=", then it must be called explicitly: -- 1=arg -- (In that case, leading and trailing spaces are trimmed) -- It finds use in infoboxes where it can replace tests like: -- {{#if: {{#invoke:WikidatIB getvalue P99 fwd=ALL}} <span class="xxx">{{#invoke:WikidatIB getvalue P99 fwd=ALL}}</span> }} -- with a form that uses just a single call to Wikidata: -- {{#invoke WikidataIB emptyor 1= <span class="xxx">{{#invoke:WikidataIB getvalue P99 fwd=ALL}}</span> }} ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.emptyor = function(frame) local s = frame.args[1] or "" if s == "" then return nil end local sx = s:gsub("%s", ""):gsub("<[^>]*>", ""):gsub("%p", "") if sx == "" then return nil else return s end end ------------------------------------------------------------------------------- -- labelorid is a public function to expose the output of labelOrId() -- Pass the Q-number as qid= or as an unnamed parameter. -- It returns the Wikidata label for that entity or the qid if no label exists. ------------------------------------------------------------------------------- -- Dependencies: labelOrId ------------------------------------------------------------------------------- p.labelorid = function(frame) return (labelOrId(frame.args.qid or frame.args[1])) end ------------------------------------------------------------------------------- -- getLang returns the MediaWiki language code of the current content. -- If optional parameter style=full, it returns the language name. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getLang = function(frame) local style = (frame.args.style or ""):lower() local langcode = mw.language.getContentLanguage().code if style == "full" then return mw.language.fetchLanguageName( langcode ) end return langcode end ------------------------------------------------------------------------------- -- getItemLangCode takes a qid parameter (using the current page's qid if blank) -- If the item for that qid has property country (P17) it looks at the first preferred value -- If the country has an official language (P37), it looks at the first preferred value -- If that official language has a language code (P424), it returns the first preferred value -- Otherwise it returns nothing. ------------------------------------------------------------------------------- -- Dependencies: _getItemLangCode() ------------------------------------------------------------------------------- p.getItemLangCode = function(frame) return _getItemLangCode(frame.args.qid or frame.args[1]) end ------------------------------------------------------------------------------- -- findLanguage exports the local findLang() function -- It takes an optional language code and returns, in order of preference: -- the code if a known language; -- the user's language, if set; -- the server's content language. ------------------------------------------------------------------------------- -- Dependencies: findLang ------------------------------------------------------------------------------- p.findLanguage = function(frame) return findLang(frame.args.lang or frame.args[1]).code end ------------------------------------------------------------------------------- -- getQid returns the qid, if supplied -- failing that, the Wikidata entity ID of the "category's main topic (P301)", if it exists -- failing that, the Wikidata entity ID associated with the current page, if it exists -- otherwise, nothing ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getQid = function(frame) local qid = (frame.args.qid or ""):upper() -- check if a qid was passed; if so, return it: if qid ~= "" then return qid end -- check if there's a "category's main topic (P301)": qid = mw.wikibase.getEntityIdForCurrentPage() if qid then local prop301 = mw.wikibase.getBestStatements(qid, "P301") if prop301[1] then local mctid = prop301[1].mainsnak.datavalue.value.id if mctid then return mctid end end end -- otherwise return the page qid (if any) return qid end ------------------------------------------------------------------------------- -- followQid takes four optional parameters: qid, props, list and all. -- If qid is not given, it uses the qid for the connected page -- or returns nil if there isn't one. -- props is a list of properties, separated by punctuation. -- If props is given, the Wikidata item for the qid is examined for each property in turn. -- If that property contains a value that is another Wikibase-item, that item's qid is returned, -- and the search terminates, unless all=y when all of the qids are returned, separated by spaces. -- If list= is set to a template, the qids are passed as arguments to the template. -- If props is not given, the qid is returned. ------------------------------------------------------------------------------- -- Dependencies: parseParam() ------------------------------------------------------------------------------- p._followQid = function(args) local qid = (args.qid or ""):upper() local all = parseParam(args.all, false) local list = args.list or "" if list == "" then list = nil end if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return nil end local out = {} local props = (args.props or ""):upper() if props ~= "" then for p in mw.text.gsplit(props, "%p") do -- split at punctuation and iterate p = mw.text.trim(p) for i, v in ipairs( mw.wikibase.getBestStatements(qid, p) ) do local linkedid = v.mainsnak.datavalue and v.mainsnak.datavalue.value.id if linkedid then if all then out[#out+1] = linkedid else return linkedid end -- test for all or just the first one found end -- test for value exists for that property end -- loop through values of property to follow end -- loop through list of properties to follow end if #out > 0 then local ret = "" if list then ret = mw.getCurrentFrame():expandTemplate{title = list, args = out} else ret = table.concat(out, " ") end return ret else return qid end end p.followQid = function(frame) return p._followQid(frame.args) end ------------------------------------------------------------------------------- -- globalSiteID returns the globalSiteID for the current wiki -- e.g. returns "enwiki" for the English Wikipedia, "enwikisource" for English Wikisource, etc. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.globalSiteID = function(frame) return mw.wikibase.getGlobalSiteId() end ------------------------------------------------------------------------------- -- siteID returns the root of the globalSiteID -- e.g. "en" for "enwiki", "enwikisource", etc. -- treats "en-gb" as "en", etc. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.siteID = function(frame) local txtlang = frame:callParserFunction('int', {'lang'}) or "" -- This deals with specific exceptions: be-tarask -> be-x-old if txtlang == "be-tarask" then return "be_x_old" end local pos = txtlang:find("-") local ret = "" if pos then ret = txtlang:sub(1, pos-1) else ret = txtlang end return ret end ------------------------------------------------------------------------------- -- projID returns the code used to link to the reader's language's project -- e.g "en" for [[:en:WikidataIB]] -- treats "en-gb" as "en", etc. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.projID = function(frame) local txtlang = frame:callParserFunction('int', {'lang'}) or "" -- This deals with specific exceptions: be-tarask -> be-x-old if txtlang == "be-tarask" then return "be-x-old" end local pos = txtlang:find("-") local ret = "" if pos then ret = txtlang:sub(1, pos-1) else ret = txtlang end return ret end ------------------------------------------------------------------------------- -- formatNumber formats a number according to the the supplied language code (" lang=") -- or the default language if not supplied. -- The number is the first unnamed parameter or " num=" ------------------------------------------------------------------------------- -- Dependencies: findLang() ------------------------------------------------------------------------------- p.formatNumber = function(frame) local lang local num = tonumber(frame.args[1] or frame.args.num) or 0 lang = findLang(frame.args.lang) return lang:formatNum( num ) end ------------------------------------------------------------------------------- -- examine dumps the property (the unnamed parameter or pid) -- from the item given by the parameter 'qid' (or the other unnamed parameter) -- or from the item corresponding to the current page if qid is not supplied. -- e.g. {{#invoke:WikidataIB examine pid=P26 qid=Q42}} -- or {{#invoke:WikidataIB examine P26 Q42}} or any combination of these -- or {{#invoke:WikidataIB examine P26}} for the current page. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.examine = function( frame ) local args if frame.args[1] or frame.args.pid or frame.args.qid then args = frame.args else args = frame:getParent().args end local par = {} local pid = (args.pid or ""):upper() local qid = (args.qid or ""):upper() par[1] = mw.text.trim( args[1] or "" ):upper() par[2] = mw.text.trim( args[2] or "" ):upper() table.sort(par) if par[2]:sub(1,1) == "P" then par[1], par[2] = par[2], par[1] end if pid == "" then pid = par[1] end if qid == "" then qid = par[2] end local q1 = qid:sub(1,1) if pid:sub(1,1) ~= "P" then return "No property supplied" end if q1 ~= "Q" and q1 ~= "M" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return "No item for this page" end return "<pre>" .. mw.dumpObject( mw.wikibase.getAllStatements( qid, pid ) ) .. "</pre>" end ------------------------------------------------------------------------------- -- checkvalue looks for 'val' as a wikibase-item value of a property (the unnamed parameter or pid) -- from the item given by the parameter 'qid' -- or from the Wikidata item associated with the current page if qid is not supplied. -- It only checks ranks that are requested (preferred and normal by default) -- If property is not supplied, then P31 (instance of) is assumed. -- It returns val if found or nothing if not found. -- e.g. {{#invoke:WikidataIB checkvalue val=Q5 pid=P31 qid=Q42}} -- or {{#invoke:WikidataIB checkvalue val=Q5 P31 qid=Q42}} -- or {{#invoke:WikidataIB checkvalue val=Q5 qid=Q42}} -- or {{#invoke:WikidataIB checkvalue val=Q5 P31}} for the current page. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.checkvalue = function( frame ) local args if frame.args.val then args = frame.args else args = frame:getParent().args end local val = args.val if not val then return nil end local pid = mw.text.trim(args.pid or args[1] or "P31"):upper() local qid = (args.qid or ""):upper() if pid:sub(1,1) ~= "P" then return nil end if qid:sub(1,1) ~= "Q" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return nil end local ranks = setRanks(args.rank) local stats = {} if ranks.b then stats = mw.wikibase.getBestStatements(qid, pid) else stats = mw.wikibase.getAllStatements( qid, pid ) end if not stats[1] then return nil end if stats[1].mainsnak.datatype == "wikibase-item" then for k, v in pairs( stats ) do local ms = v.mainsnak if ranks[v.rank:sub(1,1)] and ms.snaktype == "value" and ms.datavalue.value.id == val then return val end end end return nil end ------------------------------------------------------------------------------- -- url2 takes a parameter url= that is a proper url and formats it for use in an infobox. -- If no parameter is supplied, it returns nothing. -- This is the equivalent of Template:URL -- but it keeps the "edit at Wikidata" pen icon out of the microformat. -- Usually it will take its url parameter directly from a Wikidata call: -- e.g. {{#invoke:WikidataIB url2 url={{wdib P856 qid=Q23317 fwd=ALL osd=no}} }} ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.url2 = function(frame) local txt = frame.args.url or "" if txt == "" then return nil end -- extract any icon local url, icon = txt:match("(.+) (.+)") -- make sure there's at least a space at the end url = (url or txt) .. " " icon = icon or "" -- extract any protocol like https:// local prot = url:match("(https*://).+[ \"\']") -- extract address local addr = "" if prot then addr = url:match("https*://(.+)[ \"\']") or " " else prot = "//" addr = url:match("[^%p%s]+%.(.+)[ \"\']") or " " end -- strip trailing / from end of domain-only url and add <wbr/> before . and / local disp, n = addr:gsub( "^([^/]+)/$", "%1" ):gsub("%/", "<wbr/>/"):gsub("%.", "<wbr/>.") return '<span class="url">[' .. prot .. addr .. " " .. disp .. "]</span> " .. icon end ------------------------------------------------------------------------------- -- getWebsite fetches the Official website (P856) and formats it for use in an infobox. -- This is similar to Template:Official website but with a url displayed, -- and it adds the "edit at Wikidata" pen icon beyond the microformat if enabled. -- A local value will override the Wikidata value. "NONE" returns nothing. -- e.g. {{#invoke:WikidataIB getWebsite qid= noicon= lang= url= }} ------------------------------------------------------------------------------- -- Dependencies: findLang(); parseParam(); ------------------------------------------------------------------------------- p.getWebsite = function(frame) local url = frame.args.url or "" if url:upper() == "NONE" then return nil end local urls = {} local quals = {} local qid = frame.args.qid or "" if url and url ~= "" then urls[1] = url else if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return nil end local prop856 = mw.wikibase.getBestStatements(qid, "P856") for k, v in pairs(prop856) do if v.mainsnak.snaktype == "value" then urls[#urls+1] = v.mainsnak.datavalue.value if v.qualifiers and v.qualifiers["P1065"] then -- just take the first archive url (P1065) local au = v.qualifiers["P1065"][1] if au.snaktype == "value" then quals[#urls] = au.datavalue.value end -- test for archive url having a value end -- test for qualifers end -- test for website having a value end -- loop through website(s) end if #urls == 0 then return nil end local out = {} for i, u in ipairs(urls) do local link = quals[i] or u local prot, addr = u:match("(http[s]*://)(.+)") addr = addr or u local disp, n = addr:gsub("%.", "<wbr/>%.") out[#out+1] = '<span class="url">[' .. link .. " " .. disp .. "]</span>" end local langcode = findLang(frame.args.lang).code local noicon = parseParam(frame.args.noicon, false) if url == "" and not noicon then out[#out] = out[#out] .. createicon(langcode, qid, "P856") end local ret = "" if #out > 1 then ret = mw.getCurrentFrame():expandTemplate{title = "ubl", args = out} else ret = out[1] end return ret end ------------------------------------------------------------------------------- -- getAllLabels fetches the set of labels and formats it for display as wikitext. -- It takes a parameter 'qid' for arbitrary access, otherwise it uses the current page. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getAllLabels = function(frame) local args = frame.args or frame:getParent().args or {} local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid or not mw.wikibase.entityExists(qid) then return i18n["entity-not-found"] end local labels = mw.wikibase.getEntity(qid).labels if not labels then return i18n["labels-not-found"] end local out = {} for k, v in pairs(labels) do out[#out+1] = v.value .. " (" .. v.language .. ")" end return table.concat(out, "; ") end ------------------------------------------------------------------------------- -- getAllDescriptions fetches the set of descriptions and formats it for display as wikitext. -- It takes a parameter 'qid' for arbitrary access, otherwise it uses the current page. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getAllDescriptions = function(frame) local args = frame.args or frame:getParent().args or {} local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid or not mw.wikibase.entityExists(qid) then return i18n["entity-not-found"] end local descriptions = mw.wikibase.getEntity(qid).descriptions if not descriptions then return i18n["descriptions-not-found"] end local out = {} for k, v in pairs(descriptions) do out[#out+1] = v.value .. " (" .. v.language .. ")" end return table.concat(out, "; ") end ------------------------------------------------------------------------------- -- getAllAliases fetches the set of aliases and formats it for display as wikitext. -- It takes a parameter 'qid' for arbitrary access, otherwise it uses the current page. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.getAllAliases = function(frame) local args = frame.args or frame:getParent().args or {} local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid or not mw.wikibase.entityExists(qid) then return i18n["entity-not-found"] end local aliases = mw.wikibase.getEntity(qid).aliases if not aliases then return i18n["aliases-not-found"] end local out = {} for k1, v1 in pairs(aliases) do local lang = v1[1].language local val = {} for k1, v2 in ipairs(v1) do val[#val+1] = v2.value end out[#out+1] = table.concat(val, ", ") .. " (" .. lang .. ")" end return table.concat(out, "; ") end ------------------------------------------------------------------------------- -- showNoLinks displays the article titles that should not be linked. ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- p.showNoLinks = function(frame) local out = {} for k, v in pairs(donotlink) do out[#out+1] = k end table.sort( out ) return table.concat(out, "; ") end ------------------------------------------------------------------------------- -- checkValidity checks whether the first unnamed parameter represents a valid entity-id, -- that is, something like Q1235 or P123. -- It returns the strings "true" or "false". -- Change false to nil to return "true" or "" (easier to test with #if:). ------------------------------------------------------------------------------- -- Dependencies: none ------------------------------------------------------------------------------- function p.checkValidity(frame) local id = mw.text.trim(frame.args[1] or "") if mw.wikibase.isValidEntityId(id) then return true else return false end end ------------------------------------------------------------------------------- -- getEntityFromTitle returns the Entity-ID (Q-number) for a given title. -- Modification of Module:ResolveEntityId -- The title is the first unnamed parameter. -- The site parameter determines the site/language for the title. Defaults to current wiki. -- The showdab parameter determines whether dab pages should return the Q-number or nil. Defaults to true. -- Returns the Q-number or nil if it does not exist. ------------------------------------------------------------------------------- -- Dependencies: parseParam ------------------------------------------------------------------------------- function p.getEntityFromTitle(frame) local args=frame.args if not args[1] then args=frame:getParent().args end if not args[1] then return nil end local title = mw.text.trim(args[1]) local site = args.site or "" local showdab = parseParam(args.showdab, true) local qid = mw.wikibase.getEntityIdForTitle(title, site) if qid then local prop31 = mw.wikibase.getBestStatements(qid, "P31")[1] if not showdab and prop31 and prop31.mainsnak.datavalue.value.id == "Q4167410" then return nil else return qid end end end ------------------------------------------------------------------------------- -- getDatePrecision returns the number representing the precision of the first best date value -- for the given property. -- It takes the qid and property ID -- The meanings are given at https://www.mediawiki.org/wiki/Wikibase/DataModel#Dates_and_times -- 0 = 1 billion years .. 6 = millennium, 7 = century, 8 = decade, 9 = year, 10 = month, 11 = day -- Returns 0 (or the second unnamed parameter) if the Wikidata does not exist. ------------------------------------------------------------------------------- -- Dependencies: parseParam; sourced; ------------------------------------------------------------------------------- function p.getDatePrecision(frame) local args=frame.args if not args[1] then args=frame:getParent().args end local default = tonumber(args[2] or args.default) or 0 local prop = mw.text.trim(args[1] or "") if prop == "" then return default end local qid = args.qid or "" if qid == "" then qid = mw.wikibase.getEntityIdForCurrentPage() end if not qid then return default end local onlysrc = parseParam(args.onlysourced or args.osd, true) local stat = mw.wikibase.getBestStatements(qid, prop) for i, v in ipairs(stat) do local prec = (onlysrc == false or sourced(v)) and v.mainsnak.datavalue and v.mainsnak.datavalue.value and v.mainsnak.datavalue.value.precision if prec then return prec end end return default end return p ------------------------------------------------------------------------------- -- List of exported functions ------------------------------------------------------------------------------- --[[ _getValue getValue getPreferredValue getCoords getQualifierValue getSumOfParts getValueByQual getValueByLang getValueByRefSource getPropertyIDs getQualifierIDs getPropOfProp getAwardCat getIntersectCat getGlobe getCommonsLink getSiteLink getLink getLabel label getAT getDescription getAliases pageId formatDate location checkBlacklist emptyor labelorid getLang getItemLangCode findLanguage getQID followQid globalSiteID siteID projID formatNumber examine checkvalue url2 getWebsite getAllLabels getAllDescriptions getAllAliases showNoLinks checkValidity getEntityFromTitle getDatePrecision --]] -------------------------------------------------------------------------------