我的維基文章包含指向特定數據集的鏈接。我希望強制這些鏈接是唯一的(因爲沒有人可以使用另一個頁面中的鏈接創建新頁面)。我已經爲此擴展編寫了大部分代碼。我創建了一個表「unique_external_links」存儲URL作爲索引,並且該URL住在頁面IDMediawiki停止頁面保存並重定向回編輯頁面,並顯示錯誤消息
這裏是我寫的代碼的一部分。
$wgHooks['ParserFirstCallInit'][] = 'UniqueURLSetupParserFunction';
$wgHooks['LoadExtensionSchemaUpdates'][] = 'fnExternalLinksDBHook';
// Allow translation of the parser function name
$wgExtensionMessagesFiles['UniqueUrl'] = dirname(__FILE__) . '/UniqueUrl.i18n.php';
// Tell MediaWiki that the parser function exists.
function UniqueURLSetupParserFunction(&$parser) {
$parser->setFunctionHook('example', 'UniqueURLParserFunction');
return true;
}
function UniqueURLParserFunction($parser, $param1 = '', $param2 = '') {
// The input parameters are wikitext with templates expanded.
// The output should be wikitext too.
global $wgRequest, $wgOut;
$return_url = $wgRequest->getRequestURL();
$pid = $param2;
$param1 = trim($param1);
$url_pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
$match = preg_match($url_pattern, $param1);
if (!$match) {
// return ERROR not a valid URL!
}
$patterns = array('/^(https?:\/\/)/', '/\/$/');
$replace = array('','');
$url = preg_replace($patterns, $replace, $param1);
if (empty($param2)) { // creating a new page
try {
$dbw = wfGetDB(DB_MASTER);
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
// return ERROR page with this link already exists!
}
} else { //Trying to edit existing page
$dbr = wfGetDB(DB_SLAVE);
$res = $dbr->select(
'unique_external_links',
array('link_url'),
'link_url = "' .$url.'" AND page_id = "' .$pid.'"'
);
if ($dbr->numRows($res) == 0) {
try {
$dbw = wfGetDB(DB_MASTER);
$res = $dbw->insert('unique_external_links',
array('link_url' => $url , 'page_id' => $pid));
} catch(Exception $e) {
//return ERROR Dataset Already Exists
$response = $wgRequest -> response();
$response -> header('Location: '.$return_url);
return $return_url;
}
}else {
//just editing page, not changing link, all is good
return $param1;
}
}
return $param1;
}
首先,我向你道歉對於潦草的代碼,真的只是把它放在一起很快就沒有預先的擴展體驗...... 正如你所看到的,有些地方我有評論//返回錯誤我想停止媒體wiki保存頁面,如果一個這些條件是真的。我不想保存,而是希望將用戶返回到編輯頁面,並顯示一條消息,告訴他們他們提供的鏈接存在問題。
任何想法?我環顧四周,但找不到任何類似的東西,我認爲這是因爲我不知道要問什麼問題。我知道有像'ArticleSave'這樣的鉤子,但我不知道如何將它與解析器結合使用。
任何幫助將是偉大的!即使它告訴我完全重做我所做的,因爲它的全部錯誤哈哈。
編輯:我解決了這個問題,拋出MWExceptions在我想要返回錯誤的地方。然後我去了Exceptions.php,並且更新了MWExceptionhandler,當它看到異常消息與我從這個擴展中拋出的異常消息相匹配時採取不同的操作。這很冒昧,我承認..但是,你有時可以做什麼..
你從那以後有過使用LoadExtensionSchemaUpdates的經驗嗎?我正在尋找一個鉤子來執行SQL語句只有一次 - 安裝擴展時,而不是在更新MediaWiki時。 – bernland 2015-08-25 06:57:27