מדיה ויקי:Common.js/externalsmaker.js

מתוך חב"דפדיה, אנציקלופדיה חב"דית חופשית
גרסה מ־10:09, 23 בפברואר 2022 מאת חלוקת קונטרסים (שיחה | תרומות) (אוצר החכמה מויקיפדיה: https://he.wikipedia.org/wiki/%D7%9E%D7%93%D7%99%D7%94_%D7%95%D7%99%D7%A7%D7%99:Common.js/externalsmaker.js)
(הבדל) → הגרסה הקודמת | הגרסה האחרונה (הבדל) | הגרסה הבאה ← (הבדל)
קפיצה לניווט קפיצה לחיפוש

הערה: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אינטרנט אקספלורר / אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
  • אופרה: ללחוץ על Ctrl-F5.
function wikiit(event, force_popup) {
	window.$ = window.jQuery;

	function dateFormat(dateArr) {
		if (dateArr instanceof Array) {
			var m = ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"];

			if (dateArr.length != 3)
				return '';

			dateArr[1] = m[Number(dateArr[1]) - 1];
			if (Number(dateArr[2]) <= 50)
				dateArr[2] = 20 + dateArr[2];
			else if (Number(dateArr[2]) >= 50 && Number(dateArr[2]) < 100)
				dateArr[2] = 19 + dateArr[2];

			if (dateArr[0].charAt(0) == '0')
				dateArr[0] = dateArr[0].substring(1, dateArr[0].length);

			dateArr = dateArr[0] + " ב" + dateArr[1] + " " + dateArr[2];
		}
		return jQuery.trim(dateArr);
	}

	function engDateParse(engDate) {
		var m = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		engDate = engDate.match(/(\w+) (\d+), (\d+)/);
		return [engDate[2], (m.indexOf(engDate[1]) + 1), engDate[3]];
	}

	function match(str, expr) { str = str ? str.match(expr) : str; return (str && str.length > 1) ? str[1] : ''; }

	function getParameterByName(name) {
		/* http://james.padolsey.com/javascript/bujs-1-getparameterbyname/ */
		var match = RegExp('[?&]' + name + '=([^&]*)')
			.exec(window.location.search);
		return match && decodeURIComponent(match[1].replace(/\+/gi, ' '));
	}

	var VE = ' ו',
		TODAY = 'היום',
		YESTERDAY = 'אתמול';

	var data = [
    {
			hostname: 'old2.ih.chabad.info', hrefmatch:/audio\.php/,
			params: [
				{ str: 'קישור חבד אינפו שמע' },
				{ urlparam: 'id' },
				{ func: function(){
              var oReq = new XMLHttpRequest();
              oReq.open("get", $("param[name=movie]").val().match(/ram=(.*?)$/)[1], false);
              oReq.overrideMimeType("text/plain; charset=x-user-defined");
              oReq.send();
              s = oReq.response.split("&")[3].split("=")[1];
              z = ""
              for(var i=0;i<s.length;i++)
              {
                q = s.charCodeAt(i);
                if(q > 0xff)
                {
                  y = (q&0xff);
                  z += String.fromCharCode(y+1264)
                }
                else
                  z += s.charAt(i);
              }
              q = z.split(">").join("+|+");
              return q;
				}}
			]
		},
    {
			hostname: 'video.chabad.info',
			params: [
				{ str: 'קישור חבד וידפו' },
				{ urlparam: 'id' },
				{ telem: '.art_title' }
			]
		},
    {
			hostname: 'old2.ih.chabad.info', hrefmatch:/video/,
			params: [
				{ str: '2קישור חבד וידפו' },
				{ urlparam: 'id' },
				{ telem: '.art_title' }
			]
		},
   {
			hostname: 'old2.ih.chabad.info', hrefmatch:/#!g=1&tag=*/,
			params: [
				{ str: 'תגית באינפו הישן' },
				{ telem: 'div.news_action_desc',remove:["תגית: "] }
			]
		},
    {
			hostname: 'chabad.info', hrefmatch:/tag/,
			params: [
				{ str: 'קישור לתג באינפו' },
				{ telem: 'h2:first',remove:["Posts related to the tag '","':  "] }
			]
		},

    {
			hostname: 'chabad.info', hrefmatch:/(.*)\/(.*)/,
			params: [
				{ str: 'קישור חבד אינפו' },
				{ telem: 'div.banner_category' },
				{ str: location.pathname.split('/')[2]},
				{ telem: '.div-post-ttl > h1:nth-child(1)'} ,
				{ telem: '.single-author > div:nth-child(1)' },
				{ telem: '.single-author > div:nth-child(2)' }
				
			]
		},
 

		{
			hostname: 'old2.ih.chabad.info',hrefmatch:/#!g=1&url=article*/, 
			params: [
				{ str: 'קישור חבד אינפו ישן' },
				{ urlparam: 'id' },
				{ telem: 'div.art_title' },
				{ telem: 'div.art_author' },
				{ telem: 'div.art_time_id', match:/(\d+\.\d+\.\d+)/, split:'.', func:dateFormat }
			]
		},

		{
			hostname: 'www.chabad.co.il',
			params: [
				{ str: 'קישור חבד בישראל' },
				{ urlparam: 'topic' },
				{ urlparam: 'article' },
				{ telem: 'div.art_title' },
				{ telem: 'div.art_author' },
				{ telem: 'div.art_date', match:/(\d+\.\d+\.\d+)/, split:'.', func:dateFormat }
			]
		},
		{
			hostname: 'hageula.com',
			params: [
				{ str: 'קישור הגאולה' },
				{ str:  location.href, match: /hageula.com\/[^/]+\/([^/]+)\/\d+\.htm/ },
				{ str:  location.href, match: /hageula.com\/[^/]+\/[^/]+\/(\d+)\.htm/ },
				{ telem: 'h1:first' },
				{ elem: ['a[href^="/author"]', 'parent', 'text'], remove:"מערכת האתר"},
				{ telem: 'table.Aborder tr:first td:last div', split:'.', func:dateFormat},
				{ str:  location.href, match: /hageula.com\/([^/]+)\/[^/]+\/\d+\.htm/, defvalue:'news'}
			]
		},
		{
			hostname: 'col.org.il',
			params: [
				{ str: 'קישור חבד און ליין' },
				[
          { urlparam: 'artID'},
          { str:location.href, match:/_(\d+)\.html?$/}
        ],
				{ telem: 'table:eq(6) div:first' },
				{ str: '' }, //author
				{ telem: 'table:eq(6) div:eq(1)', match:/\(יום .+, (.*?)\)/}
			]
		},
		{
			hostname: 'shturem.net',
			params: [
				{ str: 'קישור שטורעם' },
				{ urlparam:'id' },
				{ urlparam:'section' },
				{ telem: '.artTitle' },
				{ telem: '.artReporter' },
				{ telem: '.artDate' }
			]
		},
		{
			hostname: 'www.chabad.org.il', hrefmatch:/Magazines/,
			params: [
				{ str: 'קישור התקשרות צאח' },
				{ urlparam: 'CategoryID' },
				{ urlparam: 'ArticleID' },
				{ telem: "a.navigationTab:contains('התקשרות'):last" , match:/(\d+)/ },
				{ telem: ".CategoryTitle" },
				{ telem: '.bodyinsmall' , match:/^מאת:?(.*?)\n/m },
			]
		},
		{
      hostname: "www.scribd.com",
      params: [
        { str: 'קישור בית משיח'},
        { str: location.href, match: /doc\/(\d+)\//},
        { func: function(){return $(".pager input").val();} },
        { telem: "h1.book_title"},
        { func: function(){return prompt("כותרת כתבה")}},
        { func: function(){return prompt("שם כתב")}}
      ]
		},
		{
			hostname: 'otzar.org',
			params: [
				{ str: 'אוצר החכמה' },
				[
					{ urlparam: 'book', func: function(bookid){
						if (!bookid) try{bookid = $('#book-iframe').attr('src').match(/book=(\d+)/)[1]}catch{}
						if (bookid && location.hostname == 'tablet.otzar.org') {
							window.detail_data =
								JSON.parse($.post({url:'//tablet.otzar.org/he/php/detailBook.php', async: false,
									data:'{"ParamQuery":"{\\"NUMBOOK\\":\\"'+bookid+'\\",\\"USERDATAID\\":0}","sqlFile":"selectSubOfBook"}'}
								).responseText).arr[0];
						} else if (window.booknameS && window.authorS){
							bookid = bookid || window.bookid;
							window.detail_data = {
								AUTHOR: authorS,
								FULLNAME: booknameS,
								bookid: bookid,
							}
						} else {
							bookid = bookid || window.bookid;
							var parts = $('title').text().replace('  - אוצר החכמה','').split('/');
							window.detail_data = {
								AUTHOR: parts[1],
								FULLNAME: parts[0],
								YEAR: parts[2],
								PrintedP_AND_YEAR: parts[0].split('-')[1],
								bookid: bookid,
							}
						}
					}}, // TODO: hack to have all the info ready in tablet page
					{ var: ['detail_data', 'AUTHOR']},
				],
				{ var: ['detail_data','FULLNAME']},
				{ var: ['detail_data','bookid']},
				[
					{ var: ['detail_data', 'PrintedP_AND_YEAR']},
					{ func: function () {
						return [
							window.detail_data['PrintedP'].match(/[\u0590-\u05FF ]+/)[0],
							window.detail_data['YEAR'],
						].join(' ')
					}},
					{ var: ['detail_data', 'YEAR']},
				],
				{ str: '' },
				[
					{ attr: ["ab", "value"], match: /^([^ ]*) /, prefix: 'עמוד=' },
					{ elem: ["#ab", "val"], prefix: 'עמוד=', match: /^(\d+) / },
					{ urlparam: 'pagenum', prefix: 'עמוד=' }
				],
			]
		},
		{
      hostname: "chabad-il.org", hrefmatch:/hit/,
      params: [
        { str: 'קישור התקשרות צאח ישן'},
        { str: location.href, match: /hit(\d+)\./},
        { func: function(){return location.hash.substr(1)} },
        { func: function(){return jQuery("a[name="+location.hash.substr(1)+"]").parent().find("h1:first").text().split('').reverse().join('').split('\n').reverse().join(' ')} }
      ]
		},
		{
			hostname: /otzar770.com/,
			params: [
				{ str: 'קישור אוצר 770' },
				[
          { urlparam:"nBookId"},
          { str:'', func: function(_){return $($($("frame[name='site']")[0].contentWindow.document)
                                .find("frame[name='main']")[0].contentWindow.document)
                                .find("iframe#mainArea").contents().get(0).location.href.match(/nBookId=(\d+)/)[1]}
          }
        ],
        [
          { urlparam:"nPageNumber"},
          { str:'', func: function(_){return $($($($("frame[name='site']")[0].contentWindow.document)
                                .find("frame[name='main']")[0].contentWindow.document)
                                .find("iframe#mainArea").contents()
                                .find("frame[name='navFrame']")[0]
                                .contentWindow.document).find("input[name=nCurrentPage]").val()}}
        ],
        [
          { urlparam:"cPartLetter"},
          { str:'', func: function(_){return $($($($("frame[name='site']")[0].contentWindow.document)
                                .find("frame[name='main']")[0].contentWindow.document)
                                .find("iframe#mainArea").contents()
                                .find("frame[name='navFrame']")[0]
                                .contentWindow.document).find("input[name=cPartLetter]").val()}}
        ],
				{str:'', func: function(_){
                              var main = $("frame[name='site']").length ?
                                $($($("frame[name='site']")[0].contentWindow.document).find("frame[name='main']")[0].contentWindow.document):
                                document;
                              var title = $($(main)
                              .find("iframe#mainArea").contents()
                              .find("frame[name='navFrame']")[0]
                              .contentWindow.document).find("#titleSpan").text();
                              rm = ["(מוגה)","(בלתי מוגה)", /^מאמרים/g, "ספרים שונים", "(Edited)","(Unedited)", 'ספרים בלה"ק'];
                              for (x in rm) title = title.trim().replace(rm[x],'');
                              return title},
        },
        {func:function(_){return prompt("האדמו\"ר מחבר הספר?");}},
			]
		} 
	];
	for (var i = 0; i < data.length; i++) {
		if (
			location.hostname.match(data[i].hostname)
			&& (!data[i].hrefmatch || location.href.match(data[i].hrefmatch))
			&& (!data[i].condition || data[i].condition())
		) {
			var params = [];
			for (var j = 0; j < data[i].params.length; j++) {
				if (!(data[i].params[j] instanceof Array)) {
					data[i].params[j] = [data[i].params[j]];
				}
				for (var k=0; k < data[i].params[j].length; k++) {
					try {
						var curParam = data[i].params[j][k];
						params[j] = '';
						if (typeof curParam.str != "undefined") {
							params[j] = curParam.str;
						} else if (typeof curParam.ldjson != "undefined") {
							var ldjson = null
							var ldjsons = $('script[type="application/ld+json"]').map(function(i,e){return JSON.parse($(e).text())})
							if (typeof curParam.ldjson.n != "undefined"){
								ldjson = ldjsons[curParam.ldjson.n]
							} else {
								var filteredLdjson = ldjsons.filter(function(i,e){return (curParam.ldjson.type?[curParam.ldjson.type]:['NewsArticle','Article']).includes(e['@type'])})
								if (filteredLdjson.length == 1){
									ldjson = filteredLdjson[0]
								} else {
									console.error("more/less than single ldjson", filteredLdjson)
									return
								}
							}
							if (curParam.ldjson.key == "datePublished"){
								params[j] = ldjson.datePublished;
								if (!curParam.date){
									curParam.date = ['-', '210']
								}
							} else if (curParam.ldjson.key == "author"){
								params[j] =
									$.map($(ldjson.author), function(a){return a.name})
									.join(VE)
							} else if (typeof curParam.ldjson.raw != "undefined"){
								if (!(curParam.ldjson.raw instanceof Array)) {
									curParam.ldjson.raw = [curParam.ldjson.raw]
								}
								params[j] = ldjson
								for (var t=0; t < curParam.ldjson.raw.length; t++){
									console.log('curParam.ldjson.raw[t]', curParam.ldjson.raw[t])
									params[j] = params[j][curParam.ldjson.raw[t]];
								}
							}
						} else if (typeof curParam.url != "undefined") {
							params[j] = location.href;
							if (curParam.url == 'decodeURIComponent')
								params[j] = decodeURIComponent(params[j])
							else if (curParam.url == 'decodeURI')
								params[j] = decodeURI(params[j])
						} else if (typeof curParam.attr != "undefined"){
							params[j] = jQuery('html').find(curParam.attr[0]).attr(curParam.attr[1]);
						} else if (typeof curParam.var != "undefined") {
							if (!(curParam.var instanceof Array))
								curParam.var = [curParam.var]
							params[j] = window;
							for (var vi=0; vi < curParam.var.length; vi++) {
								params[j] = params[j][curParam.var[vi]]
								// console.log(vi, params[j], curParam.var[vi])
								if (!params[j])
									break
							}
							if (params[j] == window)
								params[j] = undefined
						}
						else if (typeof curParam.urlparam != "undefined") {
							params[j] = getParameterByName(curParam.urlparam) || "";
						} else if (typeof curParam.elem != "undefined") {
							if (curParam.elem instanceof Array) {
								params[j] = jQuery('html').find(curParam.elem[0]);
								for (var elemIdx = 1; elemIdx < curParam.elem.length; elemIdx++) {
									var func = curParam.elem[elemIdx].split(',');
									params[j] = (func.length > 1) ? params[j][func[0]](func[1]) : params[j] = params[j][func[0]]();
								}
								if (typeof (params[j]) != "string")
									params[j] = params[j].html();
							}
							else
								params[j] = jQuery('html').find(curParam.elem).html();
						}
						else if (typeof curParam.first_text_node != "undefined"){
							params[j] = jQuery('html').find(curParam.first_text_node).contents().filter(function () { return this.nodeType === 3 }).text()
						} else if (typeof curParam.elements != "undefined" || (typeof curParam.telements != "undefined")) {
							var sep;
							if (typeof curParam.elements != "undefined"){
								params[j] = jQuery('html').find(curParam.elements[0]).map(function (el) { return $(this).html(); }).toArray()
								sep = curParam.elements[1];
							}
							if (typeof curParam.telements != "undefined"){
								params[j] = jQuery('html').find(curParam.telements[0]).map(function (el) { return $(this).text(); }).toArray();
								sep = curParam.telements[1];
							}
							if (sep != VE){ // hack for VE
								params[j] = params[j].join(sep);
							} else {
								if (params[j].length > 2){
									params[j] = [params[j].slice(0,-1).join(', '), params[j].slice(-1)].join(sep);
								} else {
									params[j] = params[j].join(sep);
								}
							}
						}
						else if (typeof curParam.telem != "undefined") {
							params[j] = jQuery('html').find(curParam.telem).first().text().trim();
						}

						if (typeof curParam.match != "undefined") {
							if (!(curParam.match instanceof Array))
								params[j] = match(params[j], curParam.match);
							else for (var patIdx = 0; patIdx < curParam.match.length; patIdx++) {
								var temp = match(params[j], curParam.match[patIdx]);
								if (temp != '') {
									params[j] = temp;
									break;
								}
							}
						}

						if (typeof curParam.remove != "undefined")
							for (var removeIdx = 0; removeIdx < curParam.remove.length; removeIdx++)
								params[j] = params[j].replace(curParam.remove[removeIdx], "");

						if (typeof curParam.split != "undefined")
							params[j] = params[j].split(curParam.split);

						if (typeof curParam.func != "undefined") {
							if (!(curParam.func instanceof Array))
								curParam.func = [curParam.func];
							for (var funcIdx = 0; funcIdx < curParam.func.length; funcIdx++) {
								params[j] = curParam.func[funcIdx](params[j]);
							}
						}
						if (typeof curParam.date != "undefined") {
							if (!(curParam.date instanceof Array))
								curParam.date = [curParam.date, [0,1,2]];
							var sep = curParam.date[0].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
							params[j] = match(params[j], RegExp(('(\\d+' + sep + '\\d+' + sep + '\\d+)')))
							if (params[j]){
								params[j] = params[j].split(curParam.date[0]);
								params[j] = [params[j][curParam.date[1][0]], params[j][curParam.date[1][1]], params[j][curParam.date[1][2]]]
								params[j] = dateFormat(params[j]);
							}
						}
						if (typeof curParam.stringDate != "undefined") {
							if (params[j]) {
								var today = new Date(),
									dd = (today.getDate() - (params[j] == YESTERDAY ? 1 : 0)).toString(),
									mm = (today.getMonth() + 1).toString(),
									yy = today.getFullYear().toString().slice(-2);
								params[j] = dateFormat([dd, mm, yy]);
							}
						}
						if (typeof params[j] == "string") {
							try {
								params[j] = jQuery.trim(decodeURIComponent(params[j]))
							} catch (e) {
								console.error(e)
							}
							params[j] = params[j]
								.replace(/&nbsp;|\u202B-\u202d/gm, " "
									.replace(/\s+/gm, ' '))
								.replace(/=/g, "{{=}}")
								.replace(/(\|\|?)/gm, function(x) { return "{{" + x.replace(/\|/g, "!") + "}}" })
								.replace(/(\|\|?)/gm, function(x) { return "{{" + x.replace(/\|/g, "!") + "}}" });
						}
						else if (jQuery.isArray(params[j])) {
							params[j] = jQuery.trim(params[j].join("|"));
						}

						if (params[j] && typeof curParam.prefix != "undefined")
							params[j] = curParam.prefix + params[j];

						if (typeof curParam.defvalue != "undefined" && params[j] == curParam.defvalue)
							params[j] = '';

						if (typeof curParam.shouldnt != "undefined" && typeof params[j] == "string" && params[j].match(curParam.shouldnt))
							params[j] = '';

						if ((params[j] != '') && (params[j] != undefined)) {
							console.log('found', j, params[j])
							break;
						}
						console.log('not found', j, curParam)
					}
					catch (e) {
						console.error(e)
					}
				}
			}

			var minimum = (typeof data[i].minimum != "undefined") ? (data[i].minimum) : (0);

			while (params[params.length - 1] == "" && params.length > minimum) //remove all last empty params
				params.pop();

			if (window.popup_template_canceled && !force_popup){
				console.log('popup_template_canceled');
			} else {
				var result = '{{' + params.join('|') + '}}'
				if (prompt("לחיצה על אישור תעתיק את התבנית:", result) != null){
					$('<input>').val(result).appendTo('body').select();document.execCommand('copy');
				}
				window.popup_template_canceled = false;
				if (window.old$) {window.$ = window.old$;}
			}
			return
		}
	}

	try {
		var ldjson = $('script[type="application/ld+json"]').map(function(i,e){return JSON.parse($(e).text())}).filter(function(i,e){return ['NewsArticle', 'Article', 'article'].includes(e['@type'])})
		var ldjson_website = [{}]
		//saw on 0404 and hwzone
		if (ldjson.length == 0){
			ldjson = $('script[type="application/ld+json"]').map(function(i,e){return JSON.parse($(e).text())}).filter(function(i,e){return e['@graph']})
			if (ldjson.length == 1){
				ldjson_website = ldjson[0]['@graph'].filter(function(i,e){return ['WebSite'].includes(i['@type'])})
				ldjson = ldjson[0]['@graph'].filter(function(i,e){return ['WebPage'].includes(i['@type'])})
			}
		}

		console.log('ldjson:', ldjson)
		if (ldjson.length == 1){
			ldjson = ldjson[0]
			var date = new Date(ldjson.datePublished)
			if (isNaN(date)){
				// for example in Israel Hayom
				date = new Date(ldjson.publisher.datePublished)
			}
			console.log('date', date)
			var general = {
				'הכותב': $.map($(ldjson.author), function(a){return a.name}).join(VE),
				'כותרת': ldjson.name || ldjson.headline,
				'אתר': (ldjson.publisher||ldjson_website[0]).name,
				'תאריך': dateFormat([''+date.getDay(), ''+date.getMonth(), ''+date.getFullYear()]),
				'כתובת': location.href
			}
			var result = '{{קישור כללי|'+$.map(general, function(v,k){
				return k + '=' +  jQuery.trim(decodeURIComponent($('<a />').html(v).text())).replace(/&nbsp;|\u202B-\u202d/gm, " "
					.replace(/\s+/gm, ' '))
					.replace(/=/g, "{{=}}")
					.replace(/''/g, '"')
					.replace(/(\|\|?)/gm, function (x) { return "{{" + x.replace(/\|/g, "!") + "}}" })
					.replace(/(\|\|?)/gm, function (x) { return "{{" + x.replace(/\|/g, "!") + "}}" })
			}).join('|') + '}}'
			if (prompt("לחיצה על אישור תעתיק את התבנית:", result) != null){
				$('<input>').val(result).appendTo('body').select();document.execCommand('copy');
			}
			if (window.old$) {window.$ = window.old$;}
			return
		}
	} catch (e){
		console.error('failed to create general link', e)
	}

	alert("אתר או עמוד זה אינו נתמך על ידי הבוקמרקלט.");
	if (window.old$) {window.$ = window.old$;}
}
(function () {
	if (typeof (jQuery) == "undefined"){
		if (typeof ($) != "undefined"){
			window.old$ = window.$;
			console.log('store old dollar')
		}
		var s = document.createElement('script');
		s.setAttribute('src', "https://he.wikipedia.org/w/load.php?modules=jquery&only=scripts");
		s.onload = wikiit;
		document.getElementsByTagName('body')[0].appendChild(s);
	} else {
		wikiit()
	}
})();