Example #1
0
 /**
  * @static
  * @param string $action
  * @param Article $article
  * @return bool
  * @throws UserBlockedError
  * @throws PermissionsError
  */
 static function onPowerDelete($action, $article)
 {
     global $wgOut, $wgUser, $wgRequest;
     if ($action !== 'powerdelete') {
         return true;
     }
     if (!$wgUser->isAllowed('delete') || !$wgUser->isAllowed('powerdelete')) {
         throw new PermissionsError('powerdelete');
     }
     if ($wgUser->isBlocked()) {
         throw new UserBlockedError($wgUser->mBlock);
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return false;
     }
     $reason = $wgRequest->getText('reason');
     $title = $article->getTitle();
     $file = $title->getNamespace() == NS_IMAGE ? wfLocalFile($title) : false;
     if ($file) {
         $oldimage = null;
         FileDeleteForm::doDelete($title, $file, $oldimage, $reason, false);
     } else {
         $article->doDelete($reason);
     }
     // this is stupid, but otherwise, WikiPage::doUpdateRestrictions complains about passing by reference
     $false = false;
     $article->doUpdateRestrictions(array('create' => 'sysop'), array('create' => 'infinity'), $false, $reason, $wgUser);
     return false;
 }
	/**
	 * Run a thumbnail job on a given PDF file.
	 * @return bool true
	 */
	public function run() {
		if ( !isset( $this->params['page'] ) ) {
			wfDebugLog('thumbnails', 'A page for thumbnails job of ' . $this->title->getText() . ' was not specified! That should never happen!');
			return true; // no page set? that should never happen
		}

		$file = wfLocalFile( $this->title ); // we just want a local file
		if ( !$file ) {
			return true; // Just silently fail, perhaps the file was already deleted, don't bother
		}

		switch ($this->params['jobtype']) {
			case self::BIG_THUMB:
				global $wgImageLimits;
				// Ignore user preferences, do default thumbnails
				// everything here shamelessy copied and reused from includes/ImagePage.php
				$sizeSel = User::getDefaultOption( 'imagesize' );

				// The user offset might still be incorrect, specially if
				// $wgImageLimits got changed (see bug #8858).
				if ( !isset( $wgImageLimits[$sizeSel] ) ) {
					// Default to the first offset in $wgImageLimits
					$sizeSel = 0;
				}
				$max = $wgImageLimits[$sizeSel];
				$maxWidth = $max[0];
				$maxHeight = $max[1];
				
				$width_orig = $file->getWidth( $this->params['page'] );
				$width = $width_orig;
				$height_orig = $file->getHeight( $this->params['page'] );
				$height = $height_orig;
				if ( $width > $maxWidth || $height > $maxHeight ) {
					# Calculate the thumbnail size.
					# First case, the limiting factor is the width, not the height.
					if ( $width / $height >= $maxWidth / $maxHeight ) {
						$height = round( $height * $maxWidth / $width );
						$width = $maxWidth;
						# Note that $height <= $maxHeight now.
					} else {
						$newwidth = floor( $width * $maxHeight / $height );
						$height = round( $height * $newwidth / $width );
						$width = $newwidth;
						# Note that $height <= $maxHeight now, but might not be identical
						# because of rounding.
					}
					$transformParams = array( 'page' => $this->params['page'], 'width' => $width );
					$file->transform( $transformParams );
				}
				break;

			case self::SMALL_THUMB:
				global $wgUser;
				$sk = $wgUser->getSkin();
				$sk->makeThumbLinkObj( $this->title, $file, '', '', 'none', array( 'page' => $this->params['page'] ) );
				break;
		}

		return true;
	}
Example #3
0
 protected function setUp()
 {
     parent::setUp();
     $this->setMwGlobals(array('wgEnableUploads' => true, 'wgAllowCopyUploads' => true));
     if (wfLocalFile('UploadFromUrlTest.png')->exists()) {
         $this->deleteFile('UploadFromUrlTest.png');
     }
 }
 public function build()
 {
     $this->file = wfLocalFile($this->title);
     if ($this->file && $this->file->exists()) {
         $this->fileText();
     }
     return $this->doc;
 }
Example #5
0
 public function doDBUpdates()
 {
     $method = $this->getOption('method', 'normal');
     $file = $this->getOption('file');
     $t = -microtime(true);
     $dbw = wfGetDB(DB_MASTER);
     if ($file) {
         $res = $dbw->select('image', array('img_name'), array('img_name' => $file), __METHOD__);
         if (!$res) {
             $this->error("No such file: {$file}", true);
             return false;
         }
         $this->output("Populating img_sha1 field for specified files\n");
     } else {
         $res = $dbw->select('image', array('img_name'), array('img_sha1' => ''), __METHOD__);
         $this->output("Populating img_sha1 field\n");
     }
     $imageTable = $dbw->tableName('image');
     if ($method == 'pipe') {
         // @todo FIXME: Kill this and replace with a second unbuffered DB connection.
         global $wgDBuser, $wgDBserver, $wgDBpassword, $wgDBname;
         $cmd = 'mysql -u' . wfEscapeShellArg($wgDBuser) . ' -h' . wfEscapeShellArg($wgDBserver) . ' -p' . wfEscapeShellArg($wgDBpassword, $wgDBname);
         $this->output("Using pipe method\n");
         $pipe = popen($cmd, 'w');
     }
     $numRows = $res->numRows();
     $i = 0;
     foreach ($res as $row) {
         if ($i % $this->mBatchSize == 0) {
             $this->output(sprintf("Done %d of %d, %5.3f%%  \r", $i, $numRows, $i / $numRows * 100));
             wfWaitForSlaves();
         }
         $file = wfLocalFile($row->img_name);
         if (!$file) {
             continue;
         }
         $sha1 = $file->getRepo()->getFileSha1($file->getPath());
         if (strval($sha1) !== '') {
             $sql = "UPDATE {$imageTable} SET img_sha1=" . $dbw->addQuotes($sha1) . " WHERE img_name=" . $dbw->addQuotes($row->img_name);
             if ($method == 'pipe') {
                 fwrite($pipe, "{$sql};\n");
             } else {
                 $dbw->query($sql, __METHOD__);
             }
         }
         $i++;
     }
     if ($method == 'pipe') {
         fflush($pipe);
         pclose($pipe);
     }
     $t += microtime(true);
     $this->output(sprintf("\nDone %d files in %.1f seconds\n", $numRows, $t));
     return !$file;
     // we only updated *some* files, don't log
 }
Example #6
0
 public function setUp()
 {
     global $wgEnableUploads, $wgAllowCopyUploads;
     parent::setUp();
     $wgEnableUploads = true;
     $wgAllowCopyUploads = true;
     wfSetupSession();
     if (wfLocalFile('UploadFromUrlTest.png')->exists()) {
         $this->deleteFile('UploadFromUrlTest.png');
     }
 }
Example #7
0
 public function execute()
 {
     $method = $this->getOption('method', 'normal');
     $file = $this->getOption('file');
     $t = -microtime(true);
     $dbw = wfGetDB(DB_MASTER);
     if ($file) {
         $res = $dbw->selectRow('image', array('img_name'), array('img_name' => $dbw->addQuotes($file)), __METHOD__);
         if (!$res) {
             $this->error("No such file: {$file}", true);
             return;
         }
     } else {
         $res = $dbw->select('image', array('img_name'), array('img_sha1' => ''), __METHOD__);
     }
     $imageTable = $dbw->tableName('image');
     $oldimageTable = $dbw->tableName('oldimage');
     $batch = array();
     if ($method == 'pipe') {
         // @fixme kill this and replace with a second unbuffered DB connection.
         global $wgDBuser, $wgDBserver, $wgDBpassword, $wgDBname;
         $cmd = 'mysql -u' . wfEscapeShellArg($wgDBuser) . ' -h' . wfEscapeShellArg($wgDBserver) . ' -p' . wfEscapeShellArg($wgDBpassword, $wgDBname);
         $this->output("Using pipe method\n");
         $pipe = popen($cmd, 'w');
     }
     $numRows = $res->numRows();
     $i = 0;
     foreach ($res as $row) {
         if ($i % 100 == 0) {
             $this->output(sprintf("Done %d of %d, %5.3f%%  \r", $i, $numRows, $i / $numRows * 100));
             wfWaitForSlaves(5);
         }
         $file = wfLocalFile($row->img_name);
         if (!$file) {
             continue;
         }
         $sha1 = File::sha1Base36($file->getPath());
         if (strval($sha1) !== '') {
             $sql = "UPDATE {$imageTable} SET img_sha1=" . $dbw->addQuotes($sha1) . " WHERE img_name=" . $dbw->addQuotes($row->img_name);
             if ($method == 'pipe') {
                 fwrite($pipe, "{$sql};\n");
             } else {
                 $dbw->query($sql, __METHOD__);
             }
         }
         $i++;
     }
     if ($method == 'pipe') {
         fflush($pipe);
         pclose($pipe);
     }
     $t += microtime(true);
     $this->output(sprintf("\nDone %d files in %.1f seconds\n", $numRows, $t));
 }
    /**
     * Output the information for the external editor
     */
    public function execute()
    {
        global $wgContLang, $wgScript, $wgScriptPath, $wgCanonicalServer;
        $this->getOutput()->disable();
        $response = $this->getRequest()->response();
        $response->header('Content-type: application/x-external-editor; charset=utf-8');
        $response->header('Cache-control: no-cache');
        $special = $wgContLang->getNsText(NS_SPECIAL);
        # $type can be "Edit text", "Edit file" or "Diff text" at the moment
        # See the protocol specifications at [[m:Help:External editors/Tech]] for
        # details.
        if (count($this->urls)) {
            $urls = $this->urls;
            $type = "Diff text";
        } elseif ($this->getRequest()->getVal('mode') == 'file') {
            $type = "Edit file";
            $image = wfLocalFile($this->getTitle());
            if ($image) {
                $urls = array('File' => array('Extension' => $image->getExtension(), 'URL' => $image->getCanonicalURL()));
            } else {
                $urls = array();
            }
        } else {
            $type = "Edit text";
            # *.wiki file extension is used by some editors for syntax
            # highlighting, so we follow that convention
            $urls = array('File' => array('Extension' => 'wiki', 'URL' => $this->getTitle()->getCanonicalURL(array('action' => 'edit', 'internaledit' => 'true'))));
        }
        $files = '';
        foreach ($urls as $key => $vars) {
            $files .= "\n[{$key}]\n";
            foreach ($vars as $varname => $varval) {
                $files .= "{$varname}={$varval}\n";
            }
        }
        $url = $this->getTitle()->getFullURL($this->getRequest()->appendQueryValue('internaledit', 1, true));
        $control = <<<CONTROL
; You're seeing this file because you're using Mediawiki's External Editor feature.
; This is probably because you selected use external editor in your preferences.
; To edit normally, either disable that preference or go to the URL:
; {$url}
; See http://www.mediawiki.org/wiki/Manual:External_editors for details.
[Process]
Type={$type}
Engine=MediaWiki
Script={$wgCanonicalServer}{$wgScript}
Server={$wgCanonicalServer}
Path={$wgScriptPath}
Special namespace={$special}
{$files}
CONTROL;
        echo $control;
    }
Example #9
0
 function __construct($title, $time = false)
 {
     parent::__construct($title);
     $this->img = wfFindFile($this->mTitle, $time);
     if (!$this->img) {
         $this->img = wfLocalFile($this->mTitle);
         $this->current = $this->img;
     } else {
         $this->current = $time ? wfLocalFile($this->mTitle) : $this->img;
     }
     $this->repo = $this->img->repo;
 }
Example #10
0
 /**
  * Return the URL of an image, provided its name.
  *
  * Backwards-compatibility for extensions.
  * Note that fromSharedDirectory will only use the shared path for files
  * that actually exist there now, and will return local paths otherwise.
  *
  * @param string $name	Name of the image, without the leading "Image:"
  * @param boolean $fromSharedDirectory	Should this be in $wgSharedUploadPath?
  * @return string URL of $name image
  * @deprecated
  */
 static function imageUrl($name, $fromSharedDirectory = false)
 {
     wfDeprecated(__METHOD__);
     $image = null;
     if ($fromSharedDirectory) {
         $image = wfFindFile($name);
     }
     if (!$image) {
         $image = wfLocalFile($name);
     }
     return $image->getUrl();
 }
function axMultiEditImageUpload()
{
    global $wgRequest;
    $res = array();
    $postfix = $wgRequest->getVal('num');
    $infix = '';
    if ($wgRequest->getVal('infix') != '') {
        $infix = $wgRequest->getVal('infix');
    }
    // do the real upload
    $uploadform = new CreatePageImageUploadForm($wgRequest);
    $uploadform->mTempPath = $wgRequest->getFileTempName('wp' . $infix . 'UploadFile' . $postfix);
    $uploadform->mFileSize = $wgRequest->getFileSize('wp' . $infix . 'UploadFile' . $postfix);
    $uploadform->mSrcName = $wgRequest->getFileName('wp' . $infix . 'UploadFile' . $postfix);
    $uploadform->CurlError = $wgRequest->getUploadError('wp' . $infix . 'UploadFile' . $postfix);
    $uploadform->mLastTimestamp = $wgRequest->getText('wp' . $infix . 'LastTimestamp' . $postfix);
    $par_name = $wgRequest->getText('wp' . $infix . 'ParName' . $postfix);
    $file_ext = explode('.', $uploadform->mSrcName);
    $file_ext = @$file_ext[1];
    $uploadform->mParameterExt = $file_ext;
    if ($infix == '') {
        $uploadform->mDesiredDestName = $wgRequest->getText('Createtitle') . ' ' . trim($par_name);
    } else {
        $uploadform->mDesiredDestName = $wgRequest->getText('Createtitle');
    }
    $uploadform->mSessionKey = false;
    $uploadform->mStashed = false;
    $uploadform->mRemoveTempFile = false;
    // some of the values are fixed, we have no need to add them to the form itself
    $uploadform->mIgnoreWarning = 1;
    $uploadform->mUploadDescription = wfMsg('createpage-uploaded-from');
    $uploadform->mWatchthis = 1;
    $uploadedfile = $uploadform->execute();
    if ($uploadedfile['error'] == 0) {
        $imageobj = wfLocalFile($uploadedfile['timestamp']);
        $imageurl = $imageobj->createThumb(60);
        $res = array('error' => 0, 'msg' => $uploadedfile['msg'], 'url' => $imageurl, 'timestamp' => $uploadedfile['timestamp'], 'num' => $postfix);
    } else {
        if ($uploadedfile['once']) {
            #if ( !$error_once ) {
            $res = array('error' => 1, 'msg' => $uploadedfile['msg'], 'num' => $postfix);
            #}
            $error_once = true;
        } else {
            $res = array('error' => 1, 'msg' => $uploadedfile['msg'], 'num' => $postfix);
        }
    }
    $text = json_encode($res);
    $ar = new AjaxResponse($text);
    $ar->setContentType('text/html; charset=utf-8');
    return $ar;
}
Example #12
0
	/**
	 * @return bool
	 */
	protected function loadFile() {
		if ( $this->mFileLoaded ) {
			return true;
		}
		$this->mFileLoaded = true;

		$this->mFile = wfFindFile( $this->mTitle );
		if ( !$this->mFile ) {
			$this->mFile = wfLocalFile( $this->mTitle ); // always a File
		}
		$this->mRepo = $this->mFile->getRepo();
		return true;
	}
	function upload( $title, $path ) {
		echo "$title seems not to be present in the wiki. Trying to upload from $path.\n";
		$image = wfLocalFile( $title );
		$archive = $image->publish( $path );
		$image->recordUpload( $archive->value, "Test file used for PagedTiffHandler unit test", "No license" );
		if( !$archive->isGood() )
		{
			echo "Something went wrong. Please manually upload $path\n";
			return false;
		} else {
			echo "Upload was successful.\n";
			return $image;
		}
	}
	private function doRecreate($all) {
		global $wgExIndexMIMETypes, $wgExIndexOnHTTP;
		$dbw = wfGetDB( DB_MASTER );

		$tbl_pag = $dbw->tableName( 'page' );
		$tbl_idx = $dbw->tableName( 'searchindex' );
		
		$searchWhere = $all ? '' : ' AND NOT EXISTS (SELECT null FROM '.$tbl_idx.' WHERE si_page=p.page_id AND si_url IS NOT null)';
		$result = $dbw->query('SELECT p.page_id FROM '.$tbl_pag.' p WHERE p.page_namespace = '.NS_FILE.$searchWhere );
		$this->output( $result->numRows()." file(s) found\n" );
		
		$syncIdx = false;
		$countDone = 0;
		$countSkipped = 0;

		while (($row = $result->fetchObject()) !== false) {
			$titleObj = Title::newFromID($row->page_id);
			$file = wfLocalFile($titleObj->getText());

			if (in_array( $file->getMimeType(), $wgExIndexMIMETypes )) {
				$url = $wgExIndexOnHTTP ? preg_replace( '/^https:/i', 'http:', $file->getFullUrl() ) : $file->getFullUrl();
				$dbw->update('searchindex',
					array( 'si_url' => $url ), 
					array( 'si_page' => $row->page_id ),
					'SearchIndexUpdate:update' );
				$syncIdx = true;
			} else {
				$countSkipped++;
			}
			$countDone++;
		}
		
		if ( $syncIdx ) {
			$this->output( "Syncing index... " );
			$index = $dbw->getProperty('mTablePrefix')."si_url_idx";
			$dbw->query( "CALL ctx_ddl.sync_index('$index')" );
			$this->output( "Done\n" );
		}
		
		$this->output("Finished ($countDone processed" );
		if ( $countSkipped > 0 ) {
			$this->output(", $countSkipped skipped " );
		}
		$this->output(")\n" );
	}
Example #15
0
    function edit()
    {
        global $wgOut, $wgScript, $wgScriptPath, $wgServer, $wgLang;
        $wgOut->disable();
        $name = $this->mTitle->getText();
        $pos = strrpos($name, ".") + 1;
        header("Content-type: application/x-external-editor; charset=" . $this->mCharset);
        header("Cache-control: no-cache");
        # $type can be "Edit text", "Edit file" or "Diff text" at the moment
        # See the protocol specifications at [[m:Help:External editors/Tech]] for
        # details.
        if (!isset($this->mMode)) {
            $type = "Edit text";
            $url = $this->mTitle->getFullURL("action=edit&internaledit=true");
            # *.wiki file extension is used by some editors for syntax
            # highlighting, so we follow that convention
            $extension = "wiki";
        } elseif ($this->mMode == "file") {
            $type = "Edit file";
            $image = wfLocalFile($this->mTitle);
            $url = $image->getFullURL();
            $extension = substr($name, $pos);
        }
        $special = $wgLang->getNsText(NS_SPECIAL);
        $control = <<<CONTROL
; You're seeing this file because you're using Mediawiki's External Editor
; feature. This is probably because you selected use external editor
; in your preferences. To edit normally, either disable that preference
; or go to the URL {$url} .
; See http://www.mediawiki.org/wiki/Manual:External_editors for details.
[Process]
Type={$type}
Engine=MediaWiki
Script={$wgServer}{$wgScript}
Server={$wgServer}
Path={$wgScriptPath}
Special namespace={$special}

[File]
Extension={$extension}
URL={$url}
CONTROL;
        echo $control;
    }
function doJobLoop(){
	global $wgJobTypeConfig, $wahJobDelay, $wahRunOnce, $wahStatusOutput;

	//look for jobs (sleep for $wahJobDelay if none found)
	$job = WahJobManager :: getNewJob(false, 'Internal');
	if(!$job && $wahRunOnce == false){
		if($wahStatusOutput)
			print "no jobs found waiting $wahJobDelay \n";
		sleep($wahJobDelay);
		return doJobLoop();
	}elseif(!$job  && $wahRunOnce == true){
		if($wahStatusOutput)
			print "no job found \n";
		return ;
	}

	$jobSet = WahJobManager ::getJobSetById( $job->job_set_id );
	$jobDetails = FormatJson::decode( $job->job_json ) ;

	//get the title (so we can access the source file)
	$fTitle = Title::newFromText( $job->title, $job->ns );
	$file = wfLocalFile( $fTitle );
	$thumbPath = $file->getThumbPath( $jobSet->set_encodekey );
	//make sure the directory is ready:
	wfMkdirParents( $thumbPath, null, __METHOD__ );

	$destTarget = $thumbPath . '.ogg';
	//issue the encoding command
	if($wahStatusOutput) print "Running Encode Command...\n";
	wahDoEncode($file->getPath(), $destTarget, $jobDetails->encodeSettings );

	//once done with encode update the status:
	WahJobManager :: updateJobDone($job);
	//update set done (if only one item in the set)
	$wjm = WahJobManager::newFromSet( $jobSet );
	$percDone = $wjm->getDonePerc();
	if( $percDone == 1 ){
		WahJobManager :: updateSetDone( $jobSet );
	}else{
		if($wahStatusOutput)
			print "job not complete? (might be mixing chunkDuration types?) ";
	}
}
Example #17
0
 /**
  * Validate the user parameters and set $this->archiveName and $this->file.
  * Throws an error if validation fails
  */
 protected function validateParameters()
 {
     // Validate the input title
     $title = Title::makeTitleSafe(NS_FILE, $this->params['filename']);
     if (is_null($title)) {
         $this->dieUsageMsg(array('invalidtitle', $this->params['filename']));
     }
     // Check if the file really exists
     $this->file = wfLocalFile($title);
     if (!$this->file->exists()) {
         $this->dieUsageMsg('notanarticle');
     }
     // Check if the archivename is valid for this file
     $this->archiveName = $this->params['archivename'];
     $oldFile = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName($title, $this->archiveName);
     if (!$oldFile->exists()) {
         $this->dieUsageMsg('filerevert-badversion');
     }
 }
Example #18
0
 protected function loadFile()
 {
     if ($this->fileLoaded) {
         return true;
     }
     $this->fileLoaded = true;
     $this->displayImg = $this->img = false;
     wfRunHooks('ImagePageFindFile', array($this, &$this->img, &$this->displayImg));
     if (!$this->img) {
         $this->img = wfFindFile($this->mTitle);
         if (!$this->img) {
             $this->img = wfLocalFile($this->mTitle);
         }
     }
     if (!$this->displayImg) {
         $this->displayImg = $this->img;
     }
     $this->repo = $this->img->getRepo();
 }
Example #19
0
	protected function loadFile() {
		if ( $this->fileLoaded ) {
			return;
		}
		$this->fileLoaded = true;

		$this->displayImg = $img = false;
		wfRunHooks( 'ImagePageFindFile', array( $this, &$img, &$this->displayImg ) );
		if ( !$img ) { // not set by hook?
			$img = wfFindFile( $this->getTitle() );
			if ( !$img ) {
				$img = wfLocalFile( $this->getTitle() );
			}
		}
		$this->mPage->setFile( $img );
		if ( !$this->displayImg ) { // not set by hook?
			$this->displayImg = $img;
		}
		$this->repo = $img->getRepo();
	}
Example #20
0
 /**
  * @return bool
  */
 protected function loadFile()
 {
     if ($this->mFileLoaded) {
         return true;
     }
     $this->mFileLoaded = true;
     $this->mFile = false;
     if (!$this->mFile) {
         $this->mFile = wfFindFile($this->mTitle);
         /** Wikia change start (@author Garth Webb) */
         wfRunHooks('WikiFilePageCheckFile', [&$this->mFile]);
         /** Wikia change end */
         if (!$this->mFile) {
             $this->mFile = wfLocalFile($this->mTitle);
             // always a File
         }
     }
     $this->mRepo = $this->mFile->getRepo();
     return true;
 }
Example #21
0
    function edit()
    {
        global $wgOut, $wgScript, $wgScriptPath, $wgServer, $wgLang;
        $wgOut->disable();
        $name = $this->mTitle->getText();
        $pos = strrpos($name, ".") + 1;
        header("Content-type: application/x-external-editor; charset=" . $this->mCharset);
        header("Cache-control: no-cache");
        # $type can be "Edit text", "Edit file" or "Diff text" at the moment
        # See the protocol specifications at [[m:Help:External editors/Tech]] for
        # details.
        if (!isset($this->mMode)) {
            $type = "Edit text";
            $url = $this->mTitle->getFullURL("action=edit&internaledit=true");
            # *.wiki file extension is used by some editors for syntax
            # highlighting, so we follow that convention
            $extension = "wiki";
        } elseif ($this->mMode == "file") {
            $type = "Edit file";
            $image = wfLocalFile($this->mTitle);
            $url = $image->getFullURL();
            $extension = substr($name, $pos);
        }
        $special = $wgLang->getNsText(NS_SPECIAL);
        $control = <<<CONTROL
[Process]
Type={$type}
Engine=MediaWiki
Script={$wgServer}{$wgScript}
Server={$wgServer}
Path={$wgScriptPath}
Special namespace={$special}

[File]
Extension={$extension}
URL={$url}
CONTROL;
        echo $control;
    }
 public function execute()
 {
     if (!$this->hasOption('delete')) {
         $this->output("Use --delete to actually confirm this script\n");
     }
     $filekey = $this->getOption('filekey');
     $filename = $this->getOption('filename');
     if ($filekey === '*') {
         // all versions by name
         if (!strlen($filename)) {
             $this->error("Missing --filename parameter.", 1);
         }
         $afile = false;
     } else {
         // specified version
         $dbw = wfGetDB(DB_MASTER);
         $row = $dbw->selectRow('filearchive', '*', array('fa_storage_group' => 'deleted', 'fa_storage_key' => $filekey), __METHOD__);
         if (!$row) {
             $this->error("No deleted file exists with key '{$filekey}'.", 1);
         }
         $filename = $row->fa_name;
         $afile = ArchivedFile::newFromRow($row);
     }
     $file = wfLocalFile($filename);
     if ($file->exists()) {
         $this->error("File '{$filename}' is still a public file, use the delete form.\n", 1);
     }
     $this->output("Purging all thumbnails for file '{$filename}'...");
     $file->purgeCache();
     $file->purgeHistory();
     $this->output("done.\n");
     if ($afile instanceof ArchivedFile) {
         $this->scrubVersion($afile);
     } else {
         $this->output("Finding deleted versions of file '{$filename}'...\n");
         $this->scrubAllVersions($filename);
         $this->output("Done\n");
     }
 }
 public function run()
 {
     global $wgUploadThumbnailRenderMethod;
     $transformParams = $this->params['transformParams'];
     $file = wfLocalFile($this->title);
     $file->load(File::READ_LATEST);
     if ($file && $file->exists()) {
         if ($wgUploadThumbnailRenderMethod === 'jobqueue') {
             $thumb = $file->transform($transformParams, File::RENDER_NOW);
             if ($thumb && !$thumb->isError()) {
                 return true;
             } else {
                 $this->setLastError(__METHOD__ . ': thumbnail couln\'t be generated');
                 return false;
             }
         } elseif ($wgUploadThumbnailRenderMethod === 'http') {
             $thumbUrl = '';
             $status = $this->hitThumbUrl($file, $transformParams, $thumbUrl);
             wfDebug(__METHOD__ . ": received status {$status}\n");
             // 400 happens when requesting a size greater or equal than the original
             if ($status === 200 || $status === 301 || $status === 302 || $status === 400) {
                 return true;
             } elseif ($status) {
                 $this->setLastError(__METHOD__ . ': incorrect HTTP status ' . $status . ' when hitting ' . $thumbUrl);
                 return false;
             } else {
                 $this->setLastError(__METHOD__ . ': HTTP request failure');
                 return false;
             }
         } else {
             $this->setLastError(__METHOD__ . ': unknown thumbnail render method ' . $wgUploadThumbnailRenderMethod);
             return false;
         }
     } else {
         $this->setLastError(__METHOD__ . ': file doesn\'t exist');
         return false;
     }
 }
 public function run()
 {
     global $wgUploadThumbnailRenderMethod;
     $transformParams = $this->params['transformParams'];
     $file = wfLocalFile($this->title);
     $file->load(File::READ_LATEST);
     if ($file && $file->exists()) {
         if ($wgUploadThumbnailRenderMethod === 'jobqueue') {
             $thumb = $file->transform($transformParams, File::RENDER_NOW);
             if ($thumb && !$thumb->isError()) {
                 return true;
             } else {
                 $this->setLastError(__METHOD__ . ': thumbnail couln\'t be generated');
                 return false;
             }
         } elseif ($wgUploadThumbnailRenderMethod === 'http') {
             $status = $this->hitThumbUrl($file, $transformParams);
             wfDebug(__METHOD__ . ": received status {$status}\n");
             if ($status === 200 || $status === 301 || $status === 302) {
                 return true;
             } elseif ($status) {
                 // Note that this currently happens (500) when requesting sizes larger then or
                 // equal to the original, which is harmless.
                 $this->setLastError(__METHOD__ . ': incorrect HTTP status ' . $status);
                 return false;
             } else {
                 $this->setLastError(__METHOD__ . ': HTTP request failure');
                 return false;
             }
         } else {
             $this->setLastError(__METHOD__ . ': unknown thumbnail render method ' . $wgUploadThumbnailRenderMethod);
             return false;
         }
     } else {
         $this->setLastError(__METHOD__ . ': file doesn\'t exist');
         return false;
     }
 }
Example #25
0
 function expandPeople(&$parser)
 {
     global $wgUser;
     $cur = $wgUser->getName();
     $parser->disableCache();
     $dbr =& wfGetDB(DB_SLAVE);
     $res = $dbr->select($dbr->tableName('user'), 'user_name,user_real_name');
     while ($row = $dbr->fetchRow($res)) {
         $user = $row[0];
         $name = $row[1] ? $row[1] : $user;
         $text .= "== {$name} ==\n";
         $img = "{$user}.jpg";
         $text .= "<div class=\"people-username\">" . wfMsg('people-username', $user) . "</div>";
         if (wfLocalFile($img)->exists()) {
             $text .= "[[Image:{$user}.jpg|48px|left|link=User:{$user}]]";
         } else {
             $url = Title::newFromText('Upload', NS_SPECIAL)->getFullUrl("wpDestFile={$img}");
             $text .= "[[Image:Anon.png|48px|left|link={$url}]]";
             if ($cur == $user) {
                 $text .= "<div class=\"plainlinks\">[{$url} " . wfMsg('people-upload-image') . "]</div>\n\n";
             }
         }
         $title = Title::newFromText($user, NS_USER);
         if ($title->exists()) {
             $article = new Article($title);
             $text .= $article->getContent();
             if ($cur == $user) {
                 $url = $title->getFullUrl('action=edit');
                 $text .= "<span class=\"plainlinks\">[{$url} &#91;" . wfMsg('edit') . "&#93;]</span>";
             }
         } elseif ($cur == $user) {
             $text .= "[[User:{$user}|" . wfMsg('people-create-intro') . "]]\n";
         }
         $text .= "<div style=\"clear:both\"></div>\n";
     }
     $dbr->freeResult($res);
     return "<div id=\"people\">\n{$text}</div>";
 }
	public function update( $id, $title, $text ) {
		global $wgExIndexMIMETypes, $wgExIndexOnHTTP;

		parent::update( $id, $title, $text );

		$titleObj = Title::newFromID( $id );
		$file = wfLocalFile( $titleObj->getText() );
		if ( in_array( $file->getMimeType(), $wgExIndexMIMETypes ) ) {
			$dbw = wfGetDB(DB_MASTER);
			//$dbw->query("CALL CTXSYS.CTX_OUTPUT.START_LOG('wiki_ctx.log')"); //use for INTERNAL debuging ONLY!!!

			$url = $wgExIndexOnHTTP ? preg_replace( '/^https:/i', 'http:', $file->getFullUrl() ) : $file->getFullUrl();
			$dbw->update('searchindex',
				array( 'si_url' => $url ), 
				array( 'si_page' => $id ),
				'SearchIndexUpdate:update' );
			wfDebugLog( 'OracleTextSearch', 'Updated si_url for page ' . $id );

			$index = $dbw->getProperty('mTablePrefix')."si_url_idx";
			$dbw->query( "CALL ctx_ddl.sync_index('$index')" );
			wfDebugLog( 'OracleTextSearch', 'Synced index: '.$index);
		}
	}
Example #27
0
function copyImages($images)
{
    echo "Copying images to {$destdir}\n";
    global $destdir;
    $cmds = "";
    foreach ($images as $m) {
        $t = Title::makeTitle(NS_IMAGE, $m);
        $img = wfLocalFile($t, false);
        $path = $img->getPath();
        $d = preg_replace("@.*images/@", "", $img->getPath());
        $x = explode("/", $d);
        array_pop($x);
        $d = implode("/", $x);
        $thumb = preg_replace("@.*images/@", "", str_replace("/images/", "/images/thumb/", $img->getPath()));
        $thumb_dest = "thumb/{$d}";
        $cmds .= "mkdir -p \"{$destdir}/{$d}\";\ncp \"{$path}\"  \"{$destdir}/{$d}\"; \nmkdir -p \"{$destdir}/{$thumb_dest}\";\ncp -r \"./images/{$thumb}/\" \"{$destdir}/{$thumb_dest}\" \n";
        #shell_exec ($cmd);
    }
    $myFile = "copyimages.sh";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $cmds);
    fclose($fh);
}
Example #28
0
 function tagDownload($text, $argv, &$parser)
 {
     global $wgScriptPath, $egDownloadImages;
     $dir = preg_replace('|^.+(?=[/\\\\]extensions)|', $wgScriptPath, $egDownloadImages);
     preg_match_all('|^\\s*(.+?)\\s*(\\|(.+?))?\\s*$|m', $text, $links);
     $text = "<table class=\"gallery download-gallery\" cellspacing=\"0\" cellpadding=\"0\">\n";
     $cols = isset($argv['cols']) && is_numeric($argv['cols']) ? $argv['cols'] : 4;
     $row = "";
     foreach ($links[3] as $i => $link) {
         $page = $links[1][$i];
         $icon = glob("{$egDownloadImages}/default.*");
         $img = wfLocalFile(Title::newFromText($page)->getText());
         if ($src = $img && $img->exists() ? $img->getUrl() : false) {
             $ext = preg_match('|^.+\\.(.+?)$|', $src, $m) ? $m[1] : 'default';
             if (count($j = glob("{$egDownloadImages}/{$ext}.*")) > 0) {
                 $icon = $j;
             }
             $item = "<a href=\"{$src}\">{$link}</a>";
         } else {
             $item = "No file associated with <b>{$page}</b>";
         }
         $icon = "<img src=\"{$dir}/" . basename($icon[0]) . "\" width=\"128\" height=\"128\" alt=\"\" />";
         $icon = "<a class=\"image\" title=\"{$page}\" href=\"{$src}\">{$icon}</a>";
         $row .= "<td><div class=\"gallerybox\" style=\"width: 158px;\">\n";
         $row .= "<div class=\"thumb\" style=\"padding: 13px 0pt; width: 158px;\">\n";
         $row .= "<div style=\"margin-left: auto; margin-right: auto; width: 128px;\">\n";
         $row .= "{$icon}\n</div>\n</div>\n";
         $row .= "<div class=\"gallerytext\">{$item}</div></div></td>\n";
         if ($i % $cols == 3) {
             $text .= "<tr>\n{$row}</tr>\n";
             $row = "";
         }
     }
     $row = $row ? "<tr>\n{$row}</tr>\n" : "";
     $text .= "{$row}</table>\n";
     return $text;
 }
Example #29
0
 /**
  * Constructor
  */
 function __construct()
 {
     global $wgOut, $wgHooks, $wgParser, $wgJsMimeType, $wgExtensionAssetsPath, $wgResourceModules, $wgTreeViewImages, $wgTreeViewShowLines;
     // Add hooks
     $wgParser->setFunctionHook('tree', array($this, 'expandTree'));
     $wgParser->setFunctionHook('menu', array($this, 'expandMenu'));
     $wgParser->setFunctionHook('star', array($this, 'expandStar'));
     $wgHooks['ParserAfterTidy'][] = array($this, 'renderTreeAndMenu');
     // Update general tree paths and properties
     $this->baseDir = dirname(__FILE__);
     $this->baseUrl = $wgExtensionAssetsPath . '/' . basename(dirname(__FILE__));
     $this->useLines = $wgTreeViewShowLines ? 'true' : 'false';
     $this->uniq = uniqid($this->uniqname);
     // Convert image titles to file paths and store as JS to update dTree
     foreach ($wgTreeViewImages as $k => $v) {
         $image = wfLocalFile($v);
         $v = is_object($image) && $image->exists() ? $image->getURL() : $wgTreeViewImages[$k];
         $this->images .= "tree.icon['{$k}'] = '{$v}';";
     }
     // Set up JavaScript and CSS resources
     $wgResourceModules['ext.treeandmenu'] = array('scripts' => array('star.js'), 'styles' => array('treeandmenu.css'), 'localBasePath' => dirname(__FILE__), 'remoteExtPath' => basename(dirname(__FILE__)));
     $wgOut->addModules('ext.treeandmenu');
     $wgOut->addScript("<script type=\"{$wgJsMimeType}\">window.tamBaseUrl='{$this->baseUrl}';</script>");
 }
Example #30
0
 public function getDataForSearchIndex(WikiPage $page, ParserOutput $parserOutput, SearchEngine $engine)
 {
     $fields = [];
     $title = $page->getTitle();
     if (NS_FILE != $title->getNamespace()) {
         return [];
     }
     $file = wfLocalFile($title);
     if (!$file || !$file->exists()) {
         return [];
     }
     $handler = $file->getHandler();
     if ($handler) {
         $fields['file_text'] = $handler->getEntireText($file);
     }
     $fields['file_media_type'] = $file->getMediaType();
     $fields['file_mime'] = $file->getMimeType();
     $fields['file_size'] = $file->getSize();
     $fields['file_width'] = $file->getWidth();
     $fields['file_height'] = $file->getHeight();
     $fields['file_bits'] = $file->getBitDepth();
     $fields['file_resolution'] = (int) floor(sqrt($fields['file_width'] * $fields['file_height']));
     return $fields;
 }