Extension talk:RandomImage/Archive

From mediawiki.org
Latest comment: 5 years ago by Sauron~plwiki in topic For russian encoding

Method renderHook not loading[edit]

An email was sent to Rob Church, this is just to document the bug and provide a fix.

When installed and tested on MediaWiki 1.10.0, and 1.11.0, the extension would not render an imagebox and provided the following warning:

Warning:  call_user_func_array() [<a href='function.call-user-func-array'>function.call-user-func-array</a>]: Unable to call RandomImage::renderHook() in ${IP}/mediawiki-1.11.1/includes/Parser.php on line 626

The fault appears to be in the declaration of the renderHook method on line 48 of

If you modify;

	$wgparser->setHook( 'randomimage', 'RandomImage::renderHook' );

to;

	$wgParser->setHook( 'randomimage', array('RandomImage', 'renderHook'));

the method becomes accessible and the extension works. --Zven 01:55, 12 February 2008 (UTC)Reply

Empty captions[edit]

If the <randomcaption> is not used and there is no starting paragraph the image rendering will screw up the page. This seems to be because a caption defined as an empty character or spaces will get stripped out by the method removeMagnifier when it removes the div tags <div class="magnify">, in the process creating a div tag that looks like this;

<div class="thumbcaption"/>

This tag is malformed and depending on the content can cause the left side bar to screw up. Caption content is defined in the method getCaption in RandomImage.class.php;

protected function getCaption( $title ) {
		if( !$this->caption ) {
			if( $title->exists() ) {
				$text = Revision::newFromTitle( $title )->getText();
				if( preg_match( '!<randomcaption>(.*?)</randomcaption>!i', $text, $matches ) ) {
					$this->caption = $matches[1];
				} elseif( preg_match( "!^(.*?)\n!i", $text, $matches ) ) {
					$this->caption = $matches[1];
				} else {
					$this->caption = $text;
				}
			} else {
				$this->caption = ' ';
			}
		}
		return $this->caption;
	}

Instead of defining spaces as ' ', a UTF-8 character '&#32;' seems to work. I modified this function to

	protected function getCaption( $title ) {
		if( !$this->caption ) {
			if( $title->exists() ) {
				$text = Revision::newFromTitle( $title )->getText();
				if( preg_match( '!<randomcaption>(.*?)</randomcaption>!i', $text, $matches ) ) {
					$this->caption = $matches[1];
				} elseif( preg_match( "!^(.*?)\n!i", $text, $matches ) ) {
					$this->caption = $matches[1];
				} else {
				  if($text) {
				    $this->caption = $text;
				  } else {
				    $this->caption='&#32;';
				  }
				}
			} else {
				$this->caption = '&#32;';
			}
		}
		return $this->caption;
	}

which checks that the $text is not empty and sends the UTF-8 character instead of empty or spaces that get stripped forming a div tag like this;

<div class="thumbcaption"> </div>

--Zven 11:13, 12 February 2008 (UTC)Reply

Incorrectly used <randomimage> causes fatal errors[edit]

If someone puts <randomimage> in an article then that particular article/page can throw fatal errors, only revertable by manipulating the query string to provide &action=edit in a long form url request for that page. The problem seems to be in the method removeMagnifier in the file RandomImage.class.php when entities such as &nbsp; are present in the variable $html. A hack seems to be to use the DOMDocument::LoadHTML static method rather than DOMDocument::LoadXML at about line 118. This hack stops the fatal error, but the malformed tag does not work properly unless you close it by specifying <randomimage />--Zven 02:05, 19 February 2008 (UTC)Reply

Float='center' does not work[edit]

In README you mention 'center' as valid value for float. That's not right, it should be 'centre'.

RandomImage.class.php:                  if( in_array( $float, array( 'left', 'right', 'centre' ) ) )

-- Landa

Center contra centre[edit]

I think it must be center in the source since it sets the <class=tcenter>.

The README is correct but there is a bug in RandomImage.class.php.

So line 47 'centre' must be replaced by 'center'.

--Tomas 21:26, 29 April 2008 (UTC)Reply

All of these bug fixes are being incorporated into a patch on [1] --Zven 22:48, 21 May 2008 (UTC)Reply

Category Possible?[edit]

How it is possible to use only pictures from category: XYZ? The Command <randomimage choices="category:Titelscreen"></randomimage> Did not work.

No captions?[edit]

Is there a way to omit any caption and just have the image? 71.170.103.181 06:42, 15 December 2008 (UTC)Reply

I agree with this desire. It would be good if this could be used without the "thumb" styling and without a caption. Any help modifying to get this would be greatly appreciated.
--ViciousTheJester 12:31, 21 September 2010 (UTC)Reply

DOCTYPE/ Invalid HTML output[edit]

For some reason, this extension is adding its own doctype declaration, wrapping itself into a html/body tag and exporting unneeded comment data. I've tried to remove this but can't find where it's coming from - most likely the parse function. I just want it to output the div and image code. --75.158.70.23 10:33, 15 March 2009 (UTC)Reply

I confirm this bug! --66.131.178.187 13:15, 4 May 2009 (UTC)Reply
In use here, I confirm this bug. --Jlhenry 13:26, 4 May 2009 (UTC)Reply
Here is the answer I received from the developer of this extension:
Hmm. Well, I'm not really involved with MediaWiki development any 
more, and that includes extensions; I've no idea what changes have
been made since I last committed to RandomImage.

From the sound of it, it's possible that something's altered with
respect to the parser, or whatever other mechanism I was using to get
the damn thumbnail - I do recall that, at the time, the
Linker::makeImageLink() or whatever you're *supposed* to use to
produce images didn't work as it should have, and I resorted to using
a hack involving the parser and some manipulation of the resulting DOM
to extract the bits I was after - a hack pilfered from one of Tim
Starling's extensions, I think. If the output (and thus the DOM) have
changed in any way, or if some other detail of the XML library or
whatever have changed, then that would explain why it's now broken.

Honestly, I probably won't end up doing anything about it - I'm aware
that that's a bit of a cop-out, but as I say, I'm no longer involved
in the project in any meaningful way, and from what I can gather after
a bit of quick reading around, it seems as though that's not a real
problem; plenty of people appear to be submitting patches, and those
appear to be making it into the source code repository.

If you get really, really stuck, then I might take a look in more
detail, but I'm unlikely to be able to come up with a decent solution
if no-one else can - I haven't written anything in PHP for a while,
and I'm rusty. ;)

Hope this helps explain things, even if all it does is fill you with
the impression that I'm somewhat reluctant to rip off that band-aid
and get stuck in again.

Rob Church
I hope that this could help someone to find a fix. --Jlhenry 14:27, 4 May 2009 (UTC)Reply
This all <html></html> stuff is added by function removeMagnifier() (and DOM parser), I'm not aware of purpose in removing this small "magnify" image. Easiest way is to remove this function - so you can change
        public function render() {
                $title = $this->pickImage();
                if( $title instanceof Title && $this->imageExists( $title ) ) {
                        return $this->removeMagnifier(
                                $this->parser->recursiveTagParse(
                                        $this->buildMarkup( $title )
                                )
                        );
                }
                return '';
        }
to
        public function render() {
                $title = $this->pickImage();
                if( $title instanceof Title && $this->imageExists( $title ) ) {
                          return $this->parser->recursiveTagParse(
                                  $this->buildMarkup( $title )
                          );
                }
                return '';
        }

Sauron 13:30, 4 January 2010 (UTC)Reply

False russian encoding with MW 1.12[edit]

The string of the description of a picture in Russian, writes Extension in the spoilt kind. For example, Russian word "Ошибка" is written so: "Ошибка " --80.93.116.233 10:38, 12 April 2009 (UTC)Reply

Problem in French too. --66.131.178.187 21:00, 3 May 2009 (UTC)Reply

RandomImage in a category?[edit]

Could I use <randomimage> in order to show a random image taken from a defined category? --Airon90 15:25, 5 May 2009 (UTC)Reply

Possible article links?[edit]

Needing to see if it is possible to create a "link" for the random images when the choice option is utilized. For instance, I am needing anytime THIS choice is shown, it links to THIS page? Any information on process or even info on if this is possible (or in future versions) would be appreciated. --M1shawhan 22:36, 30 June 2009 (UTC)Reply

For russian encoding[edit]

	public function render() {
		$title = $this->pickImage();
		if( $title instanceof Title && $this->imageExists( $title ) ) {
			return //$this->removeMagnifier( 
				$this->parser->recursiveTagParse(
					base64_decode ($this->buildMarkup( $title ))
				//)
			);
		}
		return '';
	}

	protected function buildMarkup ( $title ) {
		$parts[] = $title->getPrefixedText();
		$parts[] = 'thumb';
		if( $this->width !== false )
			$parts[] = "{$this->width}px";
		if( $this->float )
			$parts[] = $this->float;
		$parts[] = $this->getCaption( $title );
		return ( base64_encode ('[[' . implode( '|', $parts ) . ']]'));
	}

Can anybody put this in svn?

Thanks a lot, this hack works for Chinese too! --Zhentg 05:56, 24 February 2010 (UTC)Reply

This fix takes care of otherwise broken German encoding as well. It still isn't a built-in. --87.163.43.117 21:45, 27 May 2011 (UTC)Reply

Good code. Who can update the Extension? Xfxncat 13:05, 21 June 2016 (UTC)Reply

This still works in recent (end of 2018) code - to fix local character encoding... Sauron~plwiki (talk) 22:52, 3 December 2018 (UTC)Reply

Possible to do w/o extension[edit]

I haven't used this particular extension, but in reading it over, I think that you can essentially achieve the same thing with a combination of Extension:VariablesExtension, Extension:ParserFunctions, and Extension:DynamicFunctions (which are 3 very common extensions that a lot of wikis use.) Here's the code:

{{#vardefine:randimage|{{#rand:1|2}}}}[[File:{{#switch:{{#var:randimage}}
|1=file1.jpg
|2=file2.jpg|thumb|{{#switch:{{#var:randimage}}
|1=File 1 caption
|2=File 2 caption}}]]

--Duke33 17:43, 4 January 2010 (UTC)Reply

Random image IN and NOT IN certain categories[edit]

Hi,

I have made some changes to allow select certain categories to which image should belong and to which it should now. So there are new tags

  • categories
  • nocategories

Here is example how it may look

<randomimage float="center" size="250" categories="Pictures|Nature" nocategories="Private"/>

Here is diff code

--- RandomImage.class.php	2010-10-18 15:14:57.879993513 +0200
+++ RandomImage.class.php.new	2010-10-23 18:00:11.539388048 +0200
@@ -15,6 +15,8 @@
 	private $caption = '';
 	
 	private $choices = array();
+	private $categories = array();
+	private $nocategories = array();
 	
 	/**
 	 * Constructor
@@ -51,6 +53,16 @@
 			if( count( $choices ) > 0 )
 				$this->choices = $choices;
 		}
+		if( isset( $options['categories'] ) ) {
+			$categories = explode( '|', $options['categories'] );
+			if( count( $categories ) > 0 )
+				$this->categories = $categories;
+		}
+		if( isset( $options['nocategories'] ) ) {
+			$nocategories = explode( '|', $options['nocategories'] );
+			if( count( $nocategories ) > 0 )
+				$this->nocategories = $nocategories;
+		}
 	}
 	
 	/**
@@ -184,8 +196,10 @@
 		wfProfileIn( __METHOD__ );
 		$dbr = wfGetDB( DB_SLAVE );
 		list( $table, $conds, $opts ) = $this->getExtraSelectOptions( $dbr );
+		list( $table2, $conds2 ) = $this->getCategoriesSelectOptions( $dbr );
+
 		$res = $dbr->select(
-			$table,
+			array_merge(array_values($table2),array_values($table)),
 			array(
 				'page_namespace',
 				'page_title',
@@ -194,7 +208,7 @@
 				'page_namespace' => NS_IMAGE,
 				'page_is_redirect' => 0,
 				'page_random > ' . $dbr->addQuotes( wfRandom() ),
-			) + $conds,
+			) + $conds + $conds2,
 			__METHOD__,
 			array(
 				'ORDER BY' => 'page_random',
@@ -209,6 +223,26 @@
 		}
 		return null;
 	}
+
+	protected function getCategoriesSelectOptions( $dbr ) {
+		$tables=array();
+		$conds=array();
+		if($this->categories || $this->nocategories){
+			$tables=array('categorylinks');
+			$conds=array(100=>'page_id=cl_from');
+		}
+		if($this->categories){
+			$conds+=array(
+					101=>"cl_to IN ('".implode("','",$this->categories)."')",
+				);
+		}
+		if($this->nocategories){
+			$conds+=array(
+201=>"page_id NOT IN (SELECT page_id FROM categorylinks, page WHERE page_namespace = '6' AND cl_from=page_id AND (cl_to IN ('".implode("','",$this->nocategories)."')))",
+				);
+		}
+		return array($tables,$conds);
+	}
 	
 	/**
 	 * Get various options for database selection
@@ -218,11 +252,14 @@
 	 */
 	protected function getExtraSelectOptions( $dbr ) {
 		global $wgRandomImageStrict;
+
 		if( $wgRandomImageStrict ) {
 			list( $image, $page ) = $dbr->tableNamesN( 'image', 'page' );
 			$ind = $dbr->useIndexClause( 'page_random' );
 			return array(
-				"{$page} {$ind} LEFT JOIN {$image} ON img_name = page_title",
+				array(
+					"{$page} {$ind} LEFT JOIN {$image} ON img_name = page_title",
+				),
 				array(
 					'img_major_mime' => 'image',
 				),
@@ -230,7 +267,7 @@
 			);
 		} else {
 			return array(
-				'page',
+				array('page'),
 				array(),
 				array(
 					'USE INDEX' => 'page_random',

This diff code can be downloaded here or you can download entire RandomImage.class.php
Please be aware that excluding images by nocategories tag can be quite expensive from database point of view (categories tag is not light either). Changes made (and somehow tested) on 1.16 Mediawiki and with wgRandomImageStrict enabled.
<Sauron 16:32, 23 October 2010 (UTC)>Reply

Joker possible?[edit]

Something like

choices="abc*"

for "all images whose name begins by abc".

DOMDocument::loadHTML[edit]

I use Random Image 1.4 on my private Mediawiki 1.18.2 with PHP 5.3.8 and see following error message:

Strict Standards: Non-static method DOMDocument::loadHTML() should not be called statically, assuming $this from incompatible context in [...]\extensions\RandomImage\RandomImage.class.php on line 114

Now I have changed a little in RandomImage.class.php and error message doesn't appear any more:

	protected function removeMagnifier( $html ) {
		//$doc = DOMDocument::loadHTML( $html );
		$doc = new DOMDocument();
		$doc->loadHTML( $html );
		$xpath = new DOMXPath( $doc );
		foreach( $xpath->query( '//div[@class="magnify"]' ) as $mag )
			$mag->parentNode->removeChild( $mag );
		return preg_replace( '!<\?xml[^?]*\?>!', '', $doc->saveXml() );
	}

Has anyone other ideas? --Netzschrauber (talk) 12:30, 1 May 2012 (UTC)Reply

@Netzschrauber: I've submitted a fix: https://gerrit.wikimedia.org/r/#/c/379197/ Sam Wilson 10:05, 20 September 2017 (UTC)Reply