/**
	 * Checks for existence of a DM.
	 * If $this->definingExpression is set, it will also check if the spelling 
	 * of the defining expression matches 
	 * 
	 * @param Boolean If true, checks beyond the dataset context and will
	 *                return the first match. Always searches current 
	 *                context first.
	 * @param Boolean Switch dataset context if match outside default is found.
	 *
	 * @return DataSet object in which the DM was found, or null.
	 *
	 */
	public function checkExistence( $searchAllDataSets = false, $switchContext = false ) {
		
		global $wdCurrentContext;
		$match = $this->checkExistenceInDataSet( $this->dataset );
		if ( !is_null( $match ) ) {
			$this->exists = true;
			return $match;
		} else {
			$this->exists = false;
			if ( !$searchAllDataSets ) return null;
		}
		// Continue search
		$datasets = wdGetDataSets();
		foreach ( $datasets as $currentSet ) {
			if ( $currentSet->getPrefix() != $this->dataset->getPrefix() ) {
				$match = $this->checkExistenceInDataSet( $currentSet );
				if ( !is_null( $match ) ) {
					$this->exists = true;
					if ( $switchContext ) {
						$wdCurrentContext = $match;
						$this->dataset = $match;
					}
					return $match;
				}
			}
		}
		$this->exists = false;
		return null;

	}
function &getDataSetsAssociatedByConcept( $dm, $dc ) {
	$map = getAssociatedByConcept( $dm, $dc );
	$sets = wdGetDataSets();
	$newSets = array();
	foreach ( $map as $map_dc => $map_dm ) {
		$dataset = $sets[$map_dc];
	#	$dataset->setDefinedMeaningId($map_dm);
		$newSets[$map_dc] = $dataset;
	}
	return $newSets;
}
<?php
# A very simple skeleton Wikidata script.

define( 'MEDIAWIKI', true );

require_once( "../../../../StartProfiler.php" );
require_once( "../../../../LocalSettings.php" );
require_once( "../../php-tools/ProgressBar.php" );
require_once( "Setup.php" );
require_once( "../Wikidata.php" );


global
$beginTime, $wgCommandLineMode;

$beginTime = time();
$wgCommandLineMode = true;
$dc = "uw";

/* insert code here */

$dataSets = wdGetDataSets();
var_dump( $dataSets );


$endTime = time();
echo( "\n\nTime elapsed: " . durationToString( $endTime - $beginTime ) );

?>
	public function execute() {
		$type = null;
		$expression = null;
		$dmid = null;
		$dataset = null;
		$languages = null;
		$explanguage = null;
		$deflanguage = null;
		$resplanguage = null;
		$sections = null;
		$format = null;
		$collection = null;
		$collection_id = null;
		$relation = null;
		$relleft = null;
		$relright = null;
		$translanguage = null;
		$deflanguage = null;
		
		// read the request parameters
		extract( $this->extractRequestParams() );
		
		$datasets = wdGetDataSets();
		if ( !isset( $datasets[$dataset] ) ) {
			$this->dieUsage( "Unknown data set: $dataset", 'unknown_dataset' );
		}
		
		// **********************************
		// create and configure the formatter
		// **********************************
		$printer = $this->getCustomPrinter();
		
		$printer->setFormat( $format );
		
		// Figure out what to output
		if ( $sections != null ) { // default is to show everything
			$printer->excludeAll();
			foreach ( $sections as $section ) {
				if ( $section == 'syntrans' ) {
					$printer->setIncludeSynTrans( true );
				}
				else if ( $section == 'syntransann' ) {
					$printer->setIncludeSynTransAnnotations( true );
				}
				else if ( $section == 'def' ) {
					$printer->setIncludeDefinitions( true );
				}
				else if ( $section == 'altdef' ) {
					$printer->setIncludeAltDefinitions( true );
				}
				else if ( $section == 'ann' ) {
					$printer->setIncludeAnnotations( true );
				}
				else if ( $section == 'classatt' ) {
					$printer->setIncludeClassAttributes( true );
				}
				else if ( $section == 'classmem' ) {
					$printer->setIncludeClassMembership( true );
				}
				else if ( $section == 'colmem' ) {
					$printer->setIncludeCollectionMembership( true );
				}
				else if ( $section == 'rel' ) {
					$printer->setIncludeRelations( true );
				}
				else {
					$printer->addErrorMessage( "Unknown section: $section" );
				}
				
			}
		}
		
		// Figure out which languages to output
		if ( $languages != null ) {
			// echo $languages;
			$langCodes = explode( '|', $languages );
			foreach ( $langCodes as $langCode ) {
				$langId = getLanguageIdForIso639_3( $langCode );
				if ( $langId != null ) {
					$printer->addOutputLanguageId( $langId );
				}
				else {
					$printer->addErrorMessage( $langCode . ' is not an ISO 639-3 language code.' );
				}
			}
		}
		
		// The response language
		global $wgRecordSetLanguage;
		$wgRecordSetLanguage = getLanguageIdForIso639_3( $resplanguage );
		
		// *************************
		// Handle the actual request
		// *************************
		if ( $type == 'definedmeaning' ) {
			$dmModel = new DefinedMeaningModel( $dmid, null, $datasets[$dataset] );
			$dmModel->loadRecord();
			$record = $dmModel->getRecord();
			$printer->addDefinedMeaningRecord( $record );
		}
		// *******************
		// QUERY BY EXPRESSION
		// *******************
		else if ( $type == 'expression' ) {
			$dmIds = array();
			if ( $explanguage == null ) {
				$dmIds = getExpressionMeaningIds( $expression, $dataset );
			}
			else {
				$srcLanguages = array();
				$srcLanguages[] = getLanguageIdForIso639_3( $explanguage );
				$dmIds = getExpressionMeaningIdsForLanguages( $expression, $srcLanguages, $dataset );
			}
			
			$uniqueDmIds = array();
			foreach ( $dmIds as $dmId ) {
				// Should we return duplicates? If Rintse is right, we should.
				if ( !$this->rintseIsRight && in_array( $dmId, $uniqueDmIds ) ) {
					continue;
				}
				$uniqueDmIds[] = $dmId;
				
				$dmModel = new DefinedMeaningModel( $dmId, null, $datasets[$dataset] );
				$dmModel->loadRecord();
				$record = $dmModel->getRecord();
				$printer->addDefinedMeaningRecord( $record );
			}
			
		}
		// **********************
		// RANDOM DEFINED MEANING
		// **********************
		// Why is this a section marked with a comment, rather than a proper function?
		else if ( $type == 'randomdm' or $type == 'dump' ) {
		 
			
			// I want all the allowed parameters for this type of query to work in combination. 
			// So a client can, for example, get a random defined meaning from the destiazione 
			// italia collection that has a definition and translation in spanish and that has 
			// a 'part of theme' relationship with some other defined meaning.  
			// We'll build one monster query for all these parameters. I've seen this take up
			// to one second on a development machine.

			$query =  "SELECT dm.defined_meaning_id " .
			          "FROM {$dataset}_defined_meaning dm ";
			
			// JOINS GO HERE 
			// dm must have a translation in given language
			if ( $translanguage != null ) {
				$query .= "INNER JOIN {$dataset}_syntrans st ON dm.defined_meaning_id=st.defined_meaning_id " .
			              "INNER JOIN {$dataset}_expression exp ON st.expression_id=exp.expression_id ";
			}
			
			// dm must have a definition in given language
			if ( $deflanguage != null ) {
				$query .= "INNER JOIN {$dataset}_translated_content tc ON dm.meaning_text_tcid=tc.translated_content_id ";
			}
			
			// dm must be part of given collection
			if ( $collection != null ) {
				$query .= "INNER JOIN {$dataset}_collection_contents col on dm.defined_meaning_id=col.member_mid ";
			}
					
			// dm must be related to another dm
			if ( $relation != null && ( $relleft != null || $relright != null ) ) {
				if ( $relright != null ) {
					$query .= "INNER JOIN {$dataset}_meaning_relations rel ON dm.defined_meaning_id=rel.meaning1_mid ";
				}
				else {
					$query .= "INNER JOIN {$dataset}_meaning_relations rel ON dm.defined_meaning_id=rel.meaning2_mid ";
				}
			}
			
			// WHERE CLAUSE GOES HERE
			$query .= "WHERE dm.remove_transaction_id is null ";
			
			// dm must have a translation in given language
			if ( $translanguage != null ) {
				$query .= "AND st.remove_transaction_id is null " .
			              "AND exp.remove_transaction_id is null " .
			              "AND exp.language_id=" . getLanguageIdForIso639_3( $translanguage ) . " ";
			}
			
			// dm must have a definition in given language
			if ( $deflanguage != null ) {
				$query .= "AND tc.remove_transaction_id is null " .
			              "AND tc.language_id=" . getLanguageIdForIso639_3( $deflanguage ) . " ";
			}
			
			// dm must be part of given collection
			if ( $collection != null ) {
				$query .= "AND col.remove_transaction_id is null " .
			              "AND col.collection_id=$collection ";
			}
			
			// dm must be related to another dm
			if ( $relation != null && ( $relleft != null || $relright != null ) ) {
				$query .= "AND rel.remove_transaction_id is null " .
			              "AND rel.relationtype_mid=$relation ";
				if ( $relright != null ) {
					$query .= "AND rel.meaning2_mid=$relright ";
				}
				else {
					$query .= "AND rel.meaning1_mid=$relleft ";
				}
			}
			
			// We may get doubles for multiple expressions or relations. Pretty trivial, but affects probability
			$query .= "GROUP BY dm.defined_meaning_id ";
			// pick one at random
			if ( $type == "randomdm" ) {
				$query .= "ORDER BY RAND() ";
			}

			# var_dump($dump_start, $dump_items);
			$query .= "LIMIT $dump_start, $dump_items";
			# echo $query;

			$dbr = wfGetDB( DB_SLAVE );
			$result = $dbr->query( $query );
			for ( $i = 0; $i < $dbr->numRows( $result ); $i++ ) {
				$row = $dbr->fetchRow( $result );
				$dmModel = new DefinedMeaningModel( $row[0], null, $datasets[$dataset] );
				$dmModel->loadRecord();
				$record = $dmModel->getRecord();
				$printer->addDefinedMeaningRecord( $record );
			}
			
		}
		else if ( $type == 'relation' ) {
			if ( $relation != null || $relleft != null || $relright != null ) {
				$related = 	getRelationDefinedMeanings( $relation, $relleft, $relright, $datasets[$dataset] );
				if ( count( $related ) > 0 ) {
					foreach ( $related as $dmId ) {
						$dmModel = new DefinedMeaningModel( $dmId, null, $datasets[$dataset] );
						$dmModel->loadRecord();
						$record = $dmModel->getRecord();
						$printer->addDefinedMeaningRecord( $record );
					}
				}
				else {
					$printer->addErrorMessage( "Your relations query did not return any results." );
				}
			}
			else {
				$printer->addErrorMessage( 'To get relations you must at least specify a left or right hand side dmid and optionally a relation type dmid.' );
			}
			
		} elseif ( $type == 'collection' ) {
			try {
				$printer->suppress_output();
				print $this->collection( $collection_id, $languages );
				# throw new Exception("bla");
			} catch ( Exception $exception ) {
				$printer->addErrorMessage( $exception->getTraceAsString() );
			}
		} elseif ( $type == 'translation' ) {
			try { # effin error handler suxx0rs. This way at least I see what I'm doing wrong
				$printer->suppress_output();	# this is prolly not the best solution ^^;;
				print $this->translation( $dmid, $languages );
			} catch ( Exception $exception ) {
				$printer->addErrorMessage( $exception->getTraceAsString() );
			}
		} elseif ( $type == 'listCollections' ) {
			try { # effin error handler suxx0rs. This way at least I see what I'm doing wrong
				$printer->suppress_output();	# this is prolly not the best solution ^^;;
				print $this->listCollections();
			} catch ( Exception $exception ) {
				$printer->addErrorMessage( $exception->getTraceAsString() );
			}

		}
		
	}
	protected function getDataSetPanel() {
		global $wgTitle, $wgUser;
		$dc = wdGetDataSetContext();
		$ow_datasets = wfMsgSc( "datasets" );
		$html = "<div class=\"dataset-panel\">"; ;
		$html .= "<table border=\"0\"><tr><th class=\"dataset-panel-heading\">$ow_datasets</th></tr>";
		$dataSets = wdGetDataSets();
		$sk = $wgUser->getSkin();
		foreach ( $dataSets as $dataset ) {
			$active = ( $dataset->getPrefix() == $dc->getPrefix() );
			$name = $dataset->fetchName();
			$prefix = $dataset->getPrefix();

			$class = $active ? 'dataset-panel-active' : 'dataset-panel-inactive';
			$slot = $active ? "$name" : $sk->makeLinkObj( $wgTitle, $name, "dataset=$prefix" );
			$html .= "<tr><td class=\"$class\">$slot</td></tr>";
		}
		$html .= "</table>";
		$html .= "</div>";
		return $html;
	}
	protected function list_sets() {
		global $wgOut;
		$wgOut->addWikiText( "<h2>" . wfMsgSc( "available contexts" ) . "</h2>" );
		$sets = wdGetDataSets();
		foreach ( $sets as $key => $set ) {
			$name = $set->fetchName();
			$wgOut->addWikiText( "$key => $name" );
		}
	}