本文整理汇总了PHP中Title::legalChars方法的典型用法代码示例。如果您正苦于以下问题:PHP Title::legalChars方法的具体用法?PHP Title::legalChars怎么用?PHP Title::legalChars使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Title
的用法示例。
在下文中一共展示了Title::legalChars方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getConfig
/**
* @param ResourceLoaderContext $context
* @return array
*/
protected function getConfig($context)
{
$hash = $context->getHash();
if (isset($this->configVars[$hash])) {
return $this->configVars[$hash];
}
global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension, $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgVersion, $wgEnableAPI, $wgEnableWriteAPI, $wgDBname, $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath, $wgCookiePrefix, $wgResourceLoaderMaxQueryLength, $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion, $wgSearchType;
$mainPage = Title::newMainPage();
/**
* Namespace related preparation
* - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
* - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
*/
$namespaceIds = $wgContLang->getNamespaceIds();
$caseSensitiveNamespaces = array();
foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
$namespaceIds[$wgContLang->lc($name)] = $index;
if (!MWNamespace::isCapitalized($index)) {
$caseSensitiveNamespaces[] = $index;
}
}
// Build list of variables
$vars = array('wgLoadScript' => $wgLoadScript, 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $wgStylePath, 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $wgArticlePath, 'wgScriptPath' => $wgScriptPath, 'wgScriptExtension' => $wgScriptExtension, 'wgScript' => $wgScript, 'wgSearchType' => $wgSearchType, 'wgVariantArticlePath' => $wgVariantArticlePath, 'wgActionPaths' => (object) $wgActionPaths, 'wgServer' => $wgServer, 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgVersion' => $wgVersion, 'wgEnableAPI' => $wgEnableAPI, 'wgEnableWriteAPI' => $wgEnableWriteAPI, 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $wgSitename, 'wgFileExtensions' => array_values(array_unique($wgFileExtensions)), 'wgDBname' => $wgDBname, 'wgFileCanRotate' => BitmapHandler::canRotate(), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $wgExtensionAssetsPath, 'wgCookiePrefix' => $wgCookiePrefix, 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength, 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion, 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled);
wfRunHooks('ResourceLoaderGetConfigVars', array(&$vars));
$this->configVars[$hash] = $vars;
return $this->configVars[$hash];
}
示例2: readFromVariable
public function readFromVariable( $data ) {
# Authors first
$matches = array();
preg_match_all( '/^ \* @author\s+(.+)$/m', $data, $matches );
$authors = $matches[1];
# Then messages
$matches = array();
$regex = '/^\$(.*?)\s*=\s*[\'"](.*?)[\'"];.*?$/mus';
preg_match_all( $regex, $data, $matches, PREG_SET_ORDER );
$messages = array();
foreach ( $matches as $_ ) {
$legal = Title::legalChars();
$key = preg_replace( "/([^$legal]|\\\\)/ue", '\'\x\'.' . "dechex(ord('\\0'))", $_[1] );
$value = str_replace( array( "\'", "\\\\" ), array( "'", "\\" ), $_[2] );
$messages[$key] = $value;
}
$messages = $this->group->getMangler()->mangle( $messages );
return array(
'AUTHORS' => $authors,
'MESSAGES' => $messages,
);
}
示例3: getConfigSettings
/**
* @param ResourceLoaderContext $context
* @return array
*/
protected function getConfigSettings($context)
{
$hash = $context->getHash();
if (isset($this->configVars[$hash])) {
return $this->configVars[$hash];
}
global $wgContLang;
$mainPage = Title::newMainPage();
/**
* Namespace related preparation
* - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
* - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
*/
$namespaceIds = $wgContLang->getNamespaceIds();
$caseSensitiveNamespaces = array();
foreach (MWNamespace::getCanonicalNamespaces() as $index => $name) {
$namespaceIds[$wgContLang->lc($name)] = $index;
if (!MWNamespace::isCapitalized($index)) {
$caseSensitiveNamespaces[] = $index;
}
}
$conf = $this->getConfig();
// Build list of variables
$vars = array('wgLoadScript' => wfScript('load'), 'debug' => $context->getDebug(), 'skin' => $context->getSkin(), 'stylepath' => $conf->get('StylePath'), 'wgUrlProtocols' => wfUrlProtocols(), 'wgArticlePath' => $conf->get('ArticlePath'), 'wgScriptPath' => $conf->get('ScriptPath'), 'wgScriptExtension' => '.php', 'wgScript' => wfScript(), 'wgSearchType' => $conf->get('SearchType'), 'wgVariantArticlePath' => $conf->get('VariantArticlePath'), 'wgActionPaths' => (object) $conf->get('ActionPaths'), 'wgServer' => $conf->get('Server'), 'wgServerName' => $conf->get('ServerName'), 'wgUserLanguage' => $context->getLanguage(), 'wgContentLanguage' => $wgContLang->getCode(), 'wgTranslateNumerals' => $conf->get('TranslateNumerals'), 'wgVersion' => $conf->get('Version'), 'wgEnableAPI' => $conf->get('EnableAPI'), 'wgEnableWriteAPI' => $conf->get('EnableWriteAPI'), 'wgMainPageTitle' => $mainPage->getPrefixedText(), 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(), 'wgNamespaceIds' => $namespaceIds, 'wgContentNamespaces' => MWNamespace::getContentNamespaces(), 'wgSiteName' => $conf->get('Sitename'), 'wgDBname' => $conf->get('DBname'), 'wgExtraSignatureNamespaces' => $conf->get('ExtraSignatureNamespaces'), 'wgAvailableSkins' => Skin::getSkinNames(), 'wgExtensionAssetsPath' => $conf->get('ExtensionAssetsPath'), 'wgCookiePrefix' => $conf->get('CookiePrefix'), 'wgCookieDomain' => $conf->get('CookieDomain'), 'wgCookiePath' => $conf->get('CookiePath'), 'wgCookieExpiration' => $conf->get('CookieExpiration'), 'wgResourceLoaderMaxQueryLength' => $conf->get('ResourceLoaderMaxQueryLength'), 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces, 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass(Title::legalChars()), 'wgResourceLoaderStorageVersion' => $conf->get('ResourceLoaderStorageVersion'), 'wgResourceLoaderStorageEnabled' => $conf->get('ResourceLoaderStorageEnabled'), 'wgResourceLoaderLegacyModules' => self::getLegacyModules(), 'wgForeignUploadTargets' => $conf->get('ForeignUploadTargets'), 'wgEnableUploads' => $conf->get('EnableUploads'));
Hooks::run('ResourceLoaderGetConfigVars', array(&$vars));
$this->configVars[$hash] = $vars;
return $this->configVars[$hash];
}
示例4: getArticleMetadataFromTitle
/**
* Parse title and return article metadata
* @param string $title
* @return array article metadata (type, namespace, page_title, product, manual, topic, base_version)
*/
public static function getArticleMetadataFromTitle($title)
{
$meta = array();
if (preg_match('/^' . PONYDOCS_DOCUMENTATION_NAMESPACE_NAME . ':(([' . PONYDOCS_PRODUCT_LEGALCHARS . ']*):([' . PONYDOCS_PRODUCTMANUAL_LEGALCHARS . ']*):([' . Title::legalChars() . ']*):([' . PONYDOCS_PRODUCTVERSION_LEGALCHARS . ']*))/i', $title, $match)) {
// matched topic regex
$meta['type'] = self::ARTICLE_TYPE_TOPIC;
$meta['namespace'] = PONYDOCS_DOCUMENTATION_NAMESPACE_NAME;
$meta['title'] = $title;
$meta['page_title'] = $match[1];
$meta['product'] = $match[2];
$meta['manual'] = $match[3];
$meta['topic'] = $match[4];
$meta['base_version'] = $match[5];
} elseif (preg_match('/' . PONYDOCS_DOCUMENTATION_NAMESPACE_NAME . ':(([' . PONYDOCS_PRODUCT_LEGALCHARS . ']*):([' . PONYDOCS_PRODUCTMANUAL_LEGALCHARS . ']*)TOC([' . PONYDOCS_PRODUCTVERSION_LEGALCHARS . ']*))/i', $title, $match)) {
// matched TOC regex
$meta['type'] = self::ARTICLE_TYPE_TOC;
$meta['namespace'] = PONYDOCS_DOCUMENTATION_NAMESPACE_NAME;
$meta['title'] = $title;
$meta['page_title'] = $match[1];
$meta['product'] = $match[2];
$meta['manual'] = $match[3];
$meta['base_version'] = $match[4];
} else {
// no match
$meta['type'] = self::ARTICLE_TYPE_OTHER;
}
return $meta;
}
示例5: parseNext
public function parseNext( $text, WikiObjectModelCollection $parentObj, $offset = 0 ) {
$text = substr( $text, $offset );
$r = preg_match( '/^(\{\{\{([^{|}]+))([|}])/', $text, $m );
if ( $r ) {
if ( !preg_match( '/[^' . Title::legalChars() . ']/', trim( $m[2] ) ) )
// if(!preg_match(Title::getTitleInvalidRegex(), trim($m[2])))
return array( 'len' => ( $m[3] == '|' ) ? strlen( $m[0] ) : strlen( $m[1] ), 'obj' => new WOMTemplateFieldHolderModel( trim( $m[2] ) ) );
}
return null;
}
示例6: testLegalChars
function testLegalChars()
{
$titlechars = Title::legalChars();
foreach (range(1, 255) as $num) {
$chr = chr($num);
if (strpos("#[]{}<>|", $chr) !== false || preg_match("/[\\x00-\\x1f\\x7f]/", $chr)) {
$this->assertFalse((bool) preg_match("/[{$titlechars}]/", $chr), "chr({$num}) = {$chr} is not a valid titlechar");
} else {
$this->assertTrue((bool) preg_match("/[{$titlechars}]/", $chr), "chr({$num}) = {$chr} is a valid titlechar");
}
}
}
示例7: wikiLinksCheck
/**
* Checks if the translation uses links that are discouraged. Valid links are
* those that link to Special: or {{ns:special}}: or project pages trough
* MediaWiki messages like {{MediaWiki:helppage-url}}:. Also links in the
* definition are allowed.
*
* @param $messages \array Iterable list of TMessage objects.
* @param $code \string Language code of the translations.
* @param $warnings \array Array where warnings are appended to.
*/
protected function wikiLinksCheck( $messages, $code, &$warnings ) {
$tc = Title::legalChars() . '#%{}';
foreach ( $messages as $message ) {
$key = $message->key();
$definition = $message->definition();
$translation = $message->translation();
$subcheck = 'extra';
$matches = $links = array();
preg_match_all( "/\[\[([{$tc}]+)(\\|(.+?))?]]/sDu", $translation, $matches );
for ( $i = 0; $i < count( $matches[0] ); $i++ ) {
$backMatch = preg_quote( $matches[1][$i], '/' );
if ( preg_match( "/\[\[$backMatch/", $definition ) ) {
continue;
}
$links[] = "[[{$matches[1][$i]}{$matches[2][$i]}]]";
}
if ( count( $links ) ) {
$warnings[$key][] = array(
array( 'links', $subcheck, $key, $code ),
'translate-checks-links',
array( 'PARAMS', $links ),
array( 'COUNT', count( $links ) ),
);
}
$subcheck = 'missing';
$matches = $links = array();
preg_match_all( "/\[\[([{$tc}]+)(\\|(.+?))?]]/sDu", $definition, $matches );
for ( $i = 0; $i < count( $matches[0] ); $i++ ) {
$backMatch = preg_quote( $matches[1][$i], '/' );
if ( preg_match( "/\[\[$backMatch/", $translation ) ) {
continue;
}
$links[] = "[[{$matches[1][$i]}{$matches[2][$i]}]]";
}
if ( count( $links ) ) {
$warnings[$key][] = array(
array( 'links', $subcheck, $key, $code ),
'translate-checks-links-missing',
array( 'PARAMS', $links ),
array( 'COUNT', count( $links ) ),
);
}
}
}
示例8: getTitleInvalidRegex
/**
* Returns a simple regex that will match on characters and sequences invalid in titles.
* Note that this doesn't pick up many things that could be wrong with titles, but that
* replacing this regex with something valid will make many titles valid.
*
* @return String regex string
*/
static function getTitleInvalidRegex()
{
static $rxTc = false;
if (!$rxTc) {
# Matching titles will be held as illegal.
$rxTc = '/' . '[^' . Title::legalChars() . ']' . '|%[0-9A-Fa-f]{2}' . '|&[A-Za-z0-9\\x80-\\xff]+;' . '|&#[0-9]+;' . '|&#x[0-9A-Fa-f]+;' . '/S';
}
return $rxTc;
}
示例9: secureAndSplit
/**
* Secure and split - main initialisation function for this object
*
* Assumes that mDbkeyform has been set, and is urldecoded
* and uses underscores, but not otherwise munged. This function
* removes illegal characters, splits off the interwiki and
* namespace prefixes, sets the other forms, and canonicalizes
* everything.
* @return bool true on success
*/
private function secureAndSplit()
{
global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
# Initialisation
static $rxTc = false;
if (!$rxTc) {
# Matching titles will be held as illegal.
$rxTc = '/' . '[^' . Title::legalChars() . ']' . '|%[0-9A-Fa-f]{2}' . '|&[A-Za-z0-9\\x80-\\xff]+;' . '|&#[0-9]+;' . '|&#x[0-9A-Fa-f]+;' . '/S';
}
$this->mInterwiki = $this->mFragment = '';
$this->mNamespace = $this->mDefaultNamespace;
# Usually NS_MAIN
$dbkey = $this->mDbkeyform;
# Strip Unicode bidi override characters.
# Sometimes they slip into cut-n-pasted page titles, where the
# override chars get included in list displays.
$dbkey = str_replace("", '', $dbkey);
// 200E LEFT-TO-RIGHT MARK
$dbkey = str_replace("", '', $dbkey);
// 200F RIGHT-TO-LEFT MARK
# Clean up whitespace
#
// XXCHANGED don't replace _ with - screws up namespaces
$dbkey = preg_replace('/[ ]+/', '-', $this->mDbkeyform);
$dbkey = trim($dbkey, '-');
if ('' == $dbkey) {
return false;
}
if (false !== strpos($dbkey, UTF8_REPLACEMENT)) {
# Contained illegal UTF-8 sequences or forbidden Unicode chars.
return false;
}
$this->mDbkeyform = $dbkey;
# Initial colon indicates main namespace rather than specified default
# but should not create invalid {ns,title} pairs such as {0,Project:Foo}
if (':' == $dbkey[0]) {
$this->mNamespace = NS_MAIN;
$dbkey = substr($dbkey, 1);
# remove the colon but continue processing
$dbkey = trim($dbkey, '-');
# remove any subsequent whitespace
}
# Namespace or interwiki prefix
$firstPass = true;
do {
$m = array();
if (preg_match("/^(.+?)_*:_*(.*)\$/S", $dbkey, $m)) {
$p = $m[1];
if ($ns = $wgContLang->getNsIndex($p)) {
# Ordinary namespace
$dbkey = $m[2];
$this->mNamespace = $ns;
} elseif ($this->getInterwikiLink($p)) {
if (!$firstPass) {
# Can't make a local interwiki link to an interwiki link.
# That's just crazy!
return false;
}
# Interwiki link
$dbkey = $m[2];
$this->mInterwiki = $wgContLang->lc($p);
# Redundant interwiki prefix to the local wiki
if (0 == strcasecmp($this->mInterwiki, $wgLocalInterwiki)) {
if ($dbkey == '') {
# Can't have an empty self-link
return false;
}
$this->mInterwiki = '';
$firstPass = false;
# Do another namespace split...
continue;
}
# If there's an initial colon after the interwiki, that also
# resets the default namespace
if ($dbkey !== '' && $dbkey[0] == ':') {
$this->mNamespace = NS_MAIN;
$dbkey = substr($dbkey, 1);
}
}
# If there's no recognized interwiki or namespace,
# then let the colon expression be part of the title.
}
break;
} while (true);
# We already know that some pages won't be in the database!
#
if ('' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace) {
$this->mArticleID = 0;
}
$fragment = strstr($dbkey, '#');
//.........这里部分代码省略.........
示例10: wfIFI_handleUpload
function wfIFI_handleUpload($f, $import)
{
global $wgRequest, $wgUser, $wgOut, $wgTmpDirectory;
global $wgIFI_GetOriginal, $wgIFI_CreditsTemplate, $wgIFI_AppendRandomNumber;
# Check token, to preven Cross Site Request Forgeries
$token = $wgRequest->getVal('token');
if (!$wgUser->matchEditToken($token)) {
$wgOut->addWikitext(wfMsg('sessionfailure'));
return false;
}
$id = $wgRequest->getVal('id');
$ititle = $wgRequest->getVal('ititle');
$owner = $wgRequest->getVal('owner');
$name = $wgRequest->getVal('name');
if ($wgIFI_GetOriginal) {
// get URL of original :1
$sizes = $f->photos_getSizes($id);
$original = '';
foreach ($sizes as $size) {
if ($size['label'] == 'Original') {
$original = $size['source'];
$import = $size['source'];
} else {
if ($size['label'] == 'Large') {
$large = $size['source'];
}
}
}
//somtimes Large is returned but no Original!
if ($original == '' && $large != '') {
$import = $large;
}
}
if (!preg_match('/^http:\\/\\/farm[0-9]+\\.static\\.flickr\\.com\\/.*\\.(jpg|gif|png)$/', $import, $matches)) {
$wgOut->showErrorPage('error', 'importfreeimages_invalidurl', array(wfEscapeWikiText($import)));
return true;
}
$fileext = '.' . $matches[1];
// store the contents of the file
$pageContents = file_get_contents($import);
$tempname = tempnam($wgTmpDirectory, 'flickr');
$r = fopen($tempname, 'wb');
if ($r === FALSE) {
# Could not open temporary file to write in
$wgOut->errorPage('upload-file-error', 'upload-file-error-text');
return true;
}
$size = fwrite($r, $pageContents);
fclose($r);
$info = $f->photos_getInfo($id);
$name_wiki = wfEscapeWikiText($name);
if (!empty($wgIFI_CreditsTemplate)) {
$owner_wiki = wfEscapeWikiText($owner);
$id_wiki = wfEscapeWikiText($id);
$caption = "{{" . $wgIFI_CreditsTemplate . intval($info['license']) . "|1={$id_wiki}|2={$owner_wiki}|3={$name_wiki}}}";
} else {
// TODO: this is totally wrong: The whole message should be configurable, we shouldn't include arbitrary templates
// additionally, the license information is not correct (we are not guaranteed to get "CC by 2.0" images only)
$caption = wfMsgForContent('importfreeimages_filefromflickr', $ititle, "http://www.flickr.com/people/" . urlencode($owner) . " " . $name_wiki) . " <nowiki>{$import}</nowiki>. {{CC by 2.0}} ";
$caption = trim($caption);
}
if (!class_exists("UploadForm")) {
require_once 'includes/SpecialUpload.php';
}
$u = new UploadForm($wgRequest);
// TODO: we should use FauxRequest here instead of accessing member variables.
// But FauxRequest doesn't yet allow us to pass files around
$u->mTempPath = $tempname;
$u->mFileSize = $size;
$u->mComment = $caption;
$u->mRemoveTempFile = true;
$u->mIgnoreWarning = true;
$filename = $ititle . ($wgIFI_AppendRandomNumber ? "-" . rand(0, 9999) : "") . $fileext;
$filename = preg_replace('/ +/', ' ', $filename);
/**
* Filter out illegal characters, and try to make a legible name
* out of it. We'll strip some silently that Title would die on.
* This is taken from SpecialUpload::internalProcessUploads()
*/
$filename = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $filename);
$nt = Title::makeTitleSafe(NS_IMAGE, $filename);
if (is_null($nt)) {
$wgOut->showErrorPage('error', 'illegalfilename', array(wfEscapeWikiText($filename)));
return false;
}
$u->mSrcName = $filename;
if ($nt->getArticleID() > 0) {
$sk = $wgUser->getSkin();
$dlink = $sk->makeKnownLinkObj($t);
$warning = '<li>' . wfMsgExt('fileexists', '', $dlink) . '</li>';
// use our own upload warning as we dont have a 'reupload' feature
wfIFI_uploadWarning($u, $warning);
return true;
} elseif (!$nt->userCan('create')) {
$wgOut->showPermissionsErrorPage($nt->getUserPermissionsErrors('create', $wgUser));
return false;
} else {
$u->execute();
return true;
}
//.........这里部分代码省略.........
示例11: wfStripIllegalFilenameChars
/**
* Replace all invalid characters with '-'.
* Additional characters can be defined in $wgIllegalFileChars (see T22489).
* By default, $wgIllegalFileChars includes ':', '/', '\'.
*
* @param string $name Filename to process
* @return string
*/
function wfStripIllegalFilenameChars($name)
{
global $wgIllegalFileChars;
$illegalFileChars = $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '';
$name = preg_replace("/[^" . Title::legalChars() . "]" . $illegalFileChars . "/", '-', $name);
// $wgIllegalFileChars may not include '/' and '\', so we still need to do this
$name = wfBaseName($name);
return $name;
}
示例12: processUpload
/**
* Really do the upload
* Checks are made in SpecialUpload::execute()
* @access private
*/
function processUpload()
{
global $wgUser, $wgOut, $wgLang, $wgContLang;
global $wgUploadDirectory;
global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
/**
* If there was no filename or a zero size given, give up quick.
*/
if (trim($this->mOname) == '' || empty($this->mUploadSize)) {
return $this->mainUploadForm('<li>' . wfMsg('emptyfile') . '</li>');
}
# Chop off any directories in the given filename
if ($this->mDestFile) {
$basename = basename($this->mDestFile);
} else {
$basename = basename($this->mOname);
}
/**
* We'll want to blacklist against *any* 'extension', and use
* only the final one for the whitelist.
*/
list($partname, $ext) = $this->splitExtensions($basename);
if (count($ext)) {
$finalExt = $ext[count($ext) - 1];
} else {
$finalExt = '';
}
$fullExt = implode('.', $ext);
if (strlen($partname) < 3) {
$this->mainUploadForm(wfMsg('minlength'));
return;
}
/**
* Filter out illegal characters, and try to make a legible name
* out of it. We'll strip some silently that Title would die on.
*/
$filtered = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $basename);
$nt = Title::newFromText($filtered);
if (is_null($nt)) {
return $this->uploadError(wfMsg('illegalfilename', htmlspecialchars($filtered)));
}
$nt =& Title::makeTitle(NS_IMAGE, $nt->getDBkey());
$this->mUploadSaveName = $nt->getDBkey();
/**
* If the image is protected, non-sysop users won't be able
* to modify it by uploading a new revision.
*/
if (!$nt->userCanEdit()) {
return $this->uploadError(wfMsg('protectedpage'));
}
/* Don't allow users to override the blacklist (check file extension) */
global $wgStrictFileExtensions;
global $wgFileExtensions, $wgFileBlacklist;
if ($this->checkFileExtensionList($ext, $wgFileBlacklist) || $wgStrictFileExtensions && !$this->checkFileExtension($finalExt, $wgFileExtensions)) {
return $this->uploadError(wfMsg('badfiletype', htmlspecialchars($fullExt)));
}
/**
* Look at the contents of the file; if we can recognize the
* type but it's corrupt or data of the wrong type, we should
* probably not accept it.
*/
if (!$this->mStashed) {
$veri = $this->verify($this->mUploadTempName, $finalExt);
if ($veri !== true) {
//it's a wiki error...
return $this->uploadError($veri->toString());
}
}
/**
* Check for non-fatal conditions
*/
if (!$this->mIgnoreWarning) {
$warning = '';
if ($this->mUploadSaveName != ucfirst($filtered)) {
$warning .= '<li>' . wfMsg('badfilename', htmlspecialchars($this->mUploadSaveName)) . '</li>';
}
global $wgCheckFileExtensions;
if ($wgCheckFileExtensions) {
if (!$this->checkFileExtension($finalExt, $wgFileExtensions)) {
$warning .= '<li>' . wfMsg('badfiletype', htmlspecialchars($fullExt)) . '</li>';
}
}
global $wgUploadSizeWarning;
if ($wgUploadSizeWarning && $this->mUploadSize > $wgUploadSizeWarning) {
# TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
# value, perhaps add GB,MB and KB suffixes?
$warning .= '<li>' . wfMsg('largefile', $wgUploadSizeWarning, $this->mUploadSize) . '</li>';
}
if ($this->mUploadSize == 0) {
$warning .= '<li>' . wfMsg('emptyfile') . '</li>';
}
if ($nt->getArticleID()) {
global $wgUser;
$sk = $wgUser->getSkin();
$dlink = $sk->makeKnownLinkObj($nt);
//.........这里部分代码省略.........
示例13: processUpload
/** I BORROWED THIS FUNCTION FROM SpecialUpload.php!! CHECK FOR EACH VERSION OF MEDIAWIKI, IF
* THIS FUNCTION STILL MAKES SENSE!
*
*/
function processUpload()
{
global $wgUser, $wgUploadDirectory, $wgRequest;
$fname = "AnyWikiDraw_body::processUpload";
// Retrieve form fields
$drawingName = $wgRequest->getText('DrawingName');
$drawingWidth = $wgRequest->getText('DrawingWidth');
$drawingHeight = $wgRequest->getText('DrawingHeight');
$drawingTempFile = $wgRequest->getFileTempName('DrawingData');
$drawingFileSize = $wgRequest->getFileSize('DrawingData');
$drawingUploadError = $wgRequest->getUploadError('DrawingData');
$renderedTempFile = $wgRequest->getFileTempName('RenderedImageData');
$renderedFileSize = $wgRequest->getFileSize('RenderedImageData');
$renderedUploadError = $wgRequest->getUploadError('RenderedImageData');
$imageMapTempFile = $wgRequest->getFileTempName('ImageMapData');
$imageMapFileSize = $wgRequest->getFileSize('ImageMapData');
$imageMapUploadError = $wgRequest->getUploadError('ImageMapData');
$uploadSummary = $wgRequest->getText('UploadSummary');
// validate image dimension
if (!is_numeric($drawingWidth) || $drawingWidth < 1) {
$drawingWidth = null;
}
if (!is_numeric($drawingHeight) || $drawingHeight < 1) {
$drawingHeight = null;
}
# If there was no filename or no image data, give up quickly.
if (strlen($drawingName) == 0 || $drawingFileSize == 0) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' received bad request [DrawingName=' . $drawingName . ']' . '[fileSize(DrawingData)=' . $drawingFileSize . ']');
header('HTTP/1.0 400 Bad Request');
exit("\n\n" + '<html><body>DrawingName and DrawingData must be supplied.</body></html>');
}
// Verify filename
# Chop off any directories in the given filename.
$drawingName = wfBaseName($drawingName);
$imageExtension = substr(strrchr($drawingName, '.'), 1);
# Only allow filenames with known extensions
$allowedExtensions = array('svg', 'svgz', 'png', 'jpg');
if (!in_array($imageExtension, $allowedExtensions)) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' Received bad image extension [DrawingName=' . $drawingName . ']');
header('HTTP/1.0 400 Bad Request');
exit("\n\n" + '<html><body>DrawingName must have one of the following extensions: ' . implode(',', $allowedExtensions) . '.</body></html>');
}
/**
* Filter out illegal characters, and try to make a legible name
* out of it. We'll strip some silently that Title would die on.
*/
$filtered = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $drawingName);
$nt = Title::newFromText($filtered);
if (is_null($nt)) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' Received bad image name [DrawingName=' . $drawingName . ']');
header('HTTP/1.0 400 Bad Request');
exit("\n\n" + '<html><body>DrawingName must contain legible characters only.</body></html>');
}
$nt =& Title::makeTitle(NS_IMAGE, $nt->getDBkey());
$uploadSaveName = $nt->getDBkey();
/**
* If the image is protected, non-sysop users won't be able
* to modify it by uploading a new revision.
*/
if (!$nt->userCanEdit()) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' image is protected [DrawingName=' . $drawingName . ']');
header('HTTP/1.0 403 Forbidden');
exit("\n\n" + '<html><body>You are not allowed to edit this image.</body></html>');
}
/**
* In some cases we may forbid overwriting of existing files.
*/
if (!$this->userCanOverwrite($uploadSaveName)) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' image may not be overwritten [DrawingName=' . $drawingName . ']');
header('HTTP/1.0 403 Forbidden');
exit("\n\n" + '<html><body>You are not allowed to overwrite this image.</body></html>');
}
/** Check if the image directory is writeable, this is a common mistake */
if (!is_writeable($wgUploadDirectory)) {
header('HTTP/1.0 403 Forbidden');
exit("\n\n" + '<html><body>The upload directory on the server is read only.</body></html>');
}
/**
* Upload the file into the temp directory, so that we can scrutinize its content
*/
$archive = wfImageArchiveDir($uploadSaveName, 'temp');
/**
* Look at the contents of the file; if we can recognize the
* type but it's corrupt or data of the wrong type, we should
* probably not accept it.
*/
$veri = $this->verify($drawingTempFile, $imageExtension);
if ($veri !== true) {
wfDebug('[client ' . $_SERVER["REMOTE_ADDR"] . ']' . '[user ' . $wgUser->getName() . '] ' . $fname . ' image failed verification [DrawingName=' . $drawingName . '][DrawingTempFile=' . $drawingTempFile . ']');
unlink($drawingTempFile);
header('HTTP/1.0 400 Bad Request');
exit("\n\n" + '<html><body>The image data is corrupt.</body></html>');
}
/**
* Provide an opportunity for extensions to add further checks
*/
//.........这里部分代码省略.........
示例14: replaceInternalLinks2
/**
* Process [[ ]] wikilinks (RIL)
* @return LinkHolderArray
*
* @private
*/
function replaceInternalLinks2(&$s)
{
global $wgContLang;
wfProfileIn(__METHOD__);
wfProfileIn(__METHOD__ . '-setup');
static $tc = FALSE, $e1, $e1_img;
# the % is needed to support urlencoded titles as well
if (!$tc) {
$tc = Title::legalChars() . '#%';
# Match a link having the form [[namespace:link|alternate]]trail
$e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
# Match cases where there is no "]]", which might still be images
$e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
}
$sk = $this->mOptions->getSkin();
$holders = new LinkHolderArray($this);
#split the entire text string on occurences of [[
$a = StringUtils::explode('[[', ' ' . $s);
#get the first element (all text up to first [[), and remove the space we added
$s = $a->current();
$a->next();
$line = $a->current();
# Workaround for broken ArrayIterator::next() that returns "void"
$s = substr($s, 1);
$useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
$e2 = null;
if ($useLinkPrefixExtension) {
# Match the end of a line for a word that's not followed by whitespace,
# e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
$e2 = wfMsgForContent('linkprefix');
}
if (is_null($this->mTitle)) {
wfProfileOut(__METHOD__ . '-setup');
wfProfileOut(__METHOD__);
throw new MWException(__METHOD__ . ": \$this->mTitle is null\n");
}
$nottalk = !$this->mTitle->isTalkPage();
if ($useLinkPrefixExtension) {
$m = array();
if (preg_match($e2, $s, $m)) {
$first_prefix = $m[2];
} else {
$first_prefix = false;
}
} else {
$prefix = '';
}
if ($wgContLang->hasVariants()) {
$selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
} else {
$selflink = array($this->mTitle->getPrefixedText());
}
$useSubpages = $this->areSubpagesAllowed();
wfProfileOut(__METHOD__ . '-setup');
# Loop for each link
for (; $line !== false && $line !== null; $a->next(), $line = $a->current()) {
# Check for excessive memory usage
if ($holders->isBig()) {
# Too big
# Do the existence check, replace the link holders and clear the array
$holders->replace($s);
$holders->clear();
}
if ($useLinkPrefixExtension) {
wfProfileIn(__METHOD__ . '-prefixhandling');
if (preg_match($e2, $s, $m)) {
$prefix = $m[2];
$s = $m[1];
} else {
$prefix = '';
}
# first link
if ($first_prefix) {
$prefix = $first_prefix;
$first_prefix = false;
}
wfProfileOut(__METHOD__ . '-prefixhandling');
}
$might_be_img = false;
wfProfileIn(__METHOD__ . "-e1");
if (preg_match($e1, $line, $m)) {
# page with normal text or alt
$text = $m[2];
# If we get a ] at the beginning of $m[3] that means we have a link that's something like:
# [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
# the real problem is with the $e1 regex
# See bug 1300.
#
# Still some problems for cases where the ] is meant to be outside punctuation,
# and no image is in sight. See bug 2095.
#
if ($text !== '' && substr($m[3], 0, 1) === ']' && strpos($text, '[') !== false) {
$text .= ']';
# so that replaceExternalLinks($text) works later
//.........这里部分代码省略.........
示例15: insertImage
/**
* This functions handle the third step of the WMU, image insertion
*
* @return bool|String
*/
function insertImage()
{
global $wgRequest, $wgUser, $wgContLang;
$type = $wgRequest->getVal('type');
$name = $wgRequest->getVal('name');
$mwname = $wgRequest->getVal('mwname');
$tempid = $wgRequest->getVal('tempid');
$gallery = $wgRequest->getVal('gallery', '');
$title_main = urldecode($wgRequest->getVal('article', ''));
$ns = $wgRequest->getVal('ns', '');
$link = urldecode($wgRequest->getVal('link', ''));
// Are we in the ck editor?
$ck = $wgRequest->getVal('ck');
$extraId = $wgRequest->getVal('extraId');
$newFile = true;
$file = null;
if ($name !== NULL) {
$name = urldecode($name);
if ($name == '') {
header('X-screen-type: error');
return WfMsg('wmu-warn3');
} else {
$name = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $name);
// did they give no extension at all when they changed the name?
$ext = explode('.', $name);
array_shift($ext);
if (count($ext)) {
$finalExt = $ext[count($ext) - 1];
} else {
$finalExt = '';
}
if ('' == $finalExt) {
header('X-screen-type: error');
return wfMsg('wmu-filetype-missing');
}
$title = Title::makeTitleSafe(NS_IMAGE, $name);
if (is_null($title)) {
header('X-screen-type: error');
return wfMsg('wmu-filetype-incorrect');
}
if ($title->exists()) {
if ($type == 'overwrite') {
$title = Title::newFromText($name, 6);
// is the target protected?
$permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
$permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
$permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser);
if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
header('X-screen-type: error');
return wfMsg('wmu-file-protected');
}
$file_name = new LocalFile($title, RepoGroup::singleton()->getLocalRepo());
$file_mwname = new FakeLocalFile(Title::newFromText($mwname, 6), RepoGroup::singleton()->getLocalRepo());
if (!empty($extraId)) {
$flickrResult = $this->getFlickrPhotoInfo($extraId);
$nsid = $flickrResult['owner']['nsid'];
// e.g. 49127042@N00
$username = $flickrResult['owner']['username'];
// e.g. bossa67
$license = $flickrResult['license'];
$caption = '{{MediaWiki:Flickr' . intval($license) . '|1=' . wfEscapeWikiText($extraId) . '|2=' . wfEscapeWikiText($nsid) . '|3=' . wfEscapeWikiText($username) . '}}';
} else {
$caption = '';
}
$file_name->upload($file_mwname->getPath(), '', $caption);
$file_mwname->delete('');
$this->tempFileClearInfo($tempid);
$newFile = false;
} else {
if ($type == 'existing') {
$file = wfFindFile(Title::newFromText($name, 6));
if (!empty($file)) {
header('X-screen-type: existing');
$props = array();
$props['file'] = $file;
$props['mwname'] = $name;
$props['default_caption'] = Wikia::getProps($file->getTitle()->getArticleID(), 'default_caption');
return $this->detailsPage($props);
} else {
header('X-screen-type: error');
return wfMsg('wmu-file-error');
}
} else {
header('X-screen-type: conflict');
$tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/');
// extensions check
list($partname, $ext) = UploadBase::splitExtensions($name);
if (count($ext)) {
$finalExt = $ext[count($ext) - 1];
} else {
$finalExt = '';
}
// for more than one "extension"
if (count($ext) > 1) {
for ($i = 0; $i < count($ext) - 1; $i++) {
//.........这里部分代码省略.........