public function testVerifyThatAfterSerializeToArrayResultNextCanBeUsed()
 {
     $query = $this->getMockBuilder('\\SMWQuery')->disableOriginalConstructor()->getMock();
     $store = $this->getMockBuilder('\\SMW\\Store')->disableOriginalConstructor()->getMockForAbstractClass();
     $printRequests = array();
     $results = array(new DIWikiPage('Foo', 0), new DIWikiPage('Bar', 0));
     $instance = new QueryResult($printRequests, $query, $results, $store);
     $instance->serializeToArray();
     $this->assertInternalType('array', $instance->getNext());
     $instance->getHash();
     $this->assertInternalType('array', $instance->getNext());
 }
示例#2
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $this->isHTML = true;
     $t = "";
     $n = "";
     // if there is only one column in the results then stop right away
     if ($res->getColumnCount() == 1) {
         return "";
     }
     // print all result rows
     $first = true;
     $max = 0;
     // the biggest value. needed for scaling
     while ($row = $res->getNext()) {
         $name = $row[0]->getNextDataValue()->getShortWikiText();
         foreach ($row as $field) {
             while (($object = $field->getNextDataValue()) !== false) {
                 // use numeric sortkey
                 if ($object->isNumeric()) {
                     $nr = $object->getDataItem()->getSortKey();
                     $max = max($max, $nr);
                     if ($first) {
                         $first = false;
                         $t .= $nr;
                         $n = $name;
                     } else {
                         $t = $nr . ',' . $t;
                         $n = $name . '|' . $n;
                     }
                 }
             }
         }
     }
     return '<img src="http://chart.apis.google.com/chart?cht=p3&chs=' . $this->m_width . 'x' . $this->m_height . '&chds=0,' . $max . '&chd=t:' . $t . '&chl=' . $n . '" width="' . $this->m_width . '" height="' . $this->m_height . '"  />';
 }
	/**
	 * Returns the query result in iCal.
	 * 
	 * @since 1.5.2
	 *  
	 * @param SMWQueryResult $res
	 * 
	 * @return string
	 */
	protected function getIcal( SMWQueryResult $res ) {
		$result = '';
		
		if ( $this->m_title == '' ) {
			global $wgSitename;
			$this->m_title = $wgSitename;
		}
		
		$result .= "BEGIN:VCALENDAR\r\n";
		$result .= "PRODID:-//SMW Project//Semantic Result Formats\r\n";
		$result .= "VERSION:2.0\r\n";
		$result .= "METHOD:PUBLISH\r\n";
		$result .= "X-WR-CALNAME:" . $this->m_title . "\r\n";
		
		if ( $this->m_description !== '' ) {
			$result .= "X-WR-CALDESC:" . $this->m_description . "\r\n";
		}
		
		// TODO: http://www.kanzaki.com/docs/ical/vtimezone.html
		// $result .= "BEGIN:VTIMEZONE\r\n";
		// $result .= "TZID:\r\n";

		$row = $res->getNext();
		while ( $row !== false ) {
			$result .= $this->getIcalForItem( $row );
			$row = $res->getNext();
		}
		
		// $result .= "END:VTIMEZONE\r\n";
		
		$result .= "END:VCALENDAR\r\n";

		return $result;
	}
示例#4
0
 /**
  * Returns the query result in DSV.
  * 
  * @since 1.6
  *  
  * @param SMWQueryResult $res
  * 
  * @return string
  */
 protected function getResultFileContents(SMWQueryResult $res)
 {
     $lines = array();
     if ($this->mShowHeaders) {
         $headerItems = array();
         foreach ($res->getPrintRequests() as $pr) {
             $headerItems[] = $pr->getLabel();
         }
         $lines[] = $this->getDSVLine($headerItems);
     }
     // Loop over the result objects (pages).
     while ($row = $res->getNext()) {
         $rowItems = array();
         // Loop over their fields (properties).
         foreach ($row as $field) {
             $itemSegments = array();
             // Loop over all values for the property.
             while (($object = $field->getNextDataValue()) !== false) {
                 $itemSegments[] = Sanitizer::decodeCharReferences($object->getWikiValue());
             }
             // Join all values into a single string, separating them with comma's.
             $rowItems[] = implode(',', $itemSegments);
         }
         $lines[] = $this->getDSVLine($rowItems);
     }
     return implode("\n", $lines);
 }
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     global $wgSitename;
     $result = '';
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make file
         if ($this->m_title == '') {
             $this->m_title = $wgSitename;
         }
         $items = array();
         while ($row = $res->getNext()) {
             $items[] = $this->getItemForResultRow($row)->text();
         }
         $result = implode('', $items);
     } else {
         // just make link to export
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMessage('srf_bibtex_link')->inContentLanguage()->text();
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('bibtex', 'format');
         if ($this->getSearchLabel(SMW_OUTPUT_WIKI) != '') {
             $link->setParameter($this->getSearchLabel(SMW_OUTPUT_WIKI), 'searchlabel');
         }
         $result .= $link->getText($outputmode, $this->mLinker);
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
     }
     return $result;
 }
示例#6
0
 /**
  * Returns an array with the numerical data
  *
  * @since 1.8
  *
  * @param SMWQueryResult $result
  * @param $outputMode
  *
  * @return array
  */
 protected function getResultData(SMWQueryResult $res, $outputMode)
 {
     $data = array();
     $data['series'] = array();
     while ($row = $res->getNext()) {
         // Loop over their fields (properties)
         $label = '';
         $i = 0;
         foreach ($row as $field) {
             $i++;
             $rowNumbers = array();
             // Grouping by subject (page object) or property
             if ($this->params['group'] === 'subject') {
                 $groupedBy = $field->getResultSubject()->getTitle()->getText();
             } else {
                 $groupedBy = $field->getPrintRequest()->getLabel();
             }
             // Property label
             $property = $field->getPrintRequest()->getLabel();
             // First column property typeid
             $i == 1 ? $data['fcolumntypeid'] = $field->getPrintRequest()->getTypeID() : '';
             // Loop over all values for the property.
             while (($object = $field->getNextDataValue()) !== false) {
                 if ($object->getDataItem()->getDIType() == SMWDataItem::TYPE_NUMBER) {
                     $number = $object->getNumber();
                     // Checking against the row and in case the first column is a numeric
                     // value it is handled as label with the remaining steps continue to work
                     // as it were a text label
                     // The first column container will not be part of the series container
                     if ($i == 1) {
                         $label = $number;
                         continue;
                     }
                     if ($label !== '' && $number >= $this->params['min']) {
                         // Reference array summarize all items per row
                         $rowNumbers += array('subject' => $label, 'value' => $number, 'property' => $property);
                         // Store plain numbers for simpler handling
                         $data['series'][$groupedBy][] = $number;
                     }
                 } elseif ($object->getDataItem()->getDIType() == SMWDataItem::TYPE_TIME) {
                     $label = $object->getShortWikiText();
                 } else {
                     $label = $object->getWikiValue();
                 }
             }
             // Only for array's with numbers
             if (count($rowNumbers) > 0) {
                 // For cases where mainlabel=- we assume that the subject should not be
                 // used as identifier and therefore we try to match the groupby
                 // with the first available text label
                 if ($this->params['mainlabel'] == '-' && $this->params['group'] === 'subject') {
                     $data[$this->params['group']][$label][] = $rowNumbers;
                 } else {
                     $data[$this->params['group']][$groupedBy][] = $rowNumbers;
                 }
             }
         }
     }
     return $data;
 }
示例#7
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make RDF file
         $serializer = $this->syntax == 'turtle' ? new SMWTurtleSerializer() : new SMWRDFXMLSerializer();
         $serializer->startSerialization();
         $serializer->serializeExpData(SMWExporter::getOntologyExpData(''));
         while ($row = $res->getNext()) {
             $subjectDi = reset($row)->getResultSubject();
             $data = SMWExporter::makeExportDataForSubject($subjectDi);
             foreach ($row as $resultarray) {
                 $printreq = $resultarray->getPrintRequest();
                 $property = null;
                 switch ($printreq->getMode()) {
                     case SMWPrintRequest::PRINT_PROP:
                         $property = $printreq->getData()->getDataItem();
                         break;
                     case SMWPrintRequest::PRINT_CATS:
                         $property = new SMWDIProperty('_TYPE');
                         break;
                     case SMWPrintRequest::PRINT_CCAT:
                         // not serialised right now
                         break;
                     case SMWPrintRequest::PRINT_THIS:
                         // ignored here (object is always included in export)
                         break;
                 }
                 if (!is_null($property)) {
                     SMWExporter::addPropertyValues($property, $resultarray->getContent(), $data, $subjectDi);
                 }
             }
             $serializer->serializeExpData($data);
         }
         $serializer->finishSerialization();
         return $serializer->flushContent();
     } else {
         // just make link to feed
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('smw_rdf_link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('rdf', 'format');
         $link->setParameter($this->syntax, 'syntax');
         if (array_key_exists('limit', $this->params)) {
             $link->setParameter($this->params['limit'], 'limit');
         } else {
             // use a reasonable default limit
             $link->setParameter(100, 'limit');
         }
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
         return $link->getText($outputmode, $this->mLinker);
     }
 }
示例#8
0
 /**
  * Gets a list of all numbers.
  * 
  * @since 1.6
  * 
  * @param SMWQueryResult $res
  * 
  * @return array
  */
 protected function getNumbers(SMWQueryResult $res)
 {
     $numbers = array();
     while ($row = $res->getNext()) {
         foreach ($row as $resultArray) {
             foreach ($resultArray->getContent() as $dataItem) {
                 self::addNumbersForDataItem($dataItem, $numbers);
             }
         }
     }
     return $numbers;
 }
示例#9
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $result = '';
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make CSV file
         $csv = fopen('php://temp', 'r+');
         if ($this->mShowHeaders) {
             $header_items = array();
             foreach ($res->getPrintRequests() as $pr) {
                 $header_items[] = $pr->getLabel();
             }
             fputcsv($csv, $header_items, $this->m_sep);
         }
         while ($row = $res->getNext()) {
             $row_items = array();
             foreach ($row as $field) {
                 $growing = array();
                 while (($object = $field->getNextDataValue()) !== false) {
                     $growing[] = Sanitizer::decodeCharReferences($object->getWikiValue());
                 }
                 $row_items[] = implode(',', $growing);
             }
             fputcsv($csv, $row_items, $this->m_sep);
         }
         rewind($csv);
         $result .= stream_get_contents($csv);
     } else {
         // just make link to feed
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('smw_csv_link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('csv', 'format');
         $link->setParameter($this->m_sep, 'sep');
         if (array_key_exists('mainlabel', $this->params) && $this->params['mainlabel'] !== false) {
             $link->setParameter($this->params['mainlabel'], 'mainlabel');
         }
         $link->setParameter($this->mShowHeaders ? 'show' : 'hide', 'headers');
         if (array_key_exists('limit', $this->params)) {
             $link->setParameter($this->params['limit'], 'limit');
         } else {
             // use a reasonable default limit
             $link->setParameter(100, 'limit');
         }
         $result .= $link->getText($outputmode, $this->mLinker);
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
     }
     return $result;
 }
示例#10
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $result = '';
     $columnClasses = array();
     if ($this->mShowHeaders != SMW_HEADERS_HIDE) {
         // building headers
         $headers = array();
         foreach ($res->getPrintRequests() as $pr) {
             $attribs = array();
             $columnClass = str_replace(array(' ', '_'), '-', $pr->getText(SMW_OUTPUT_WIKI));
             $attribs['class'] = $columnClass;
             // Also add this to the array of classes, for
             // use in displaying each row.
             $columnClasses[] = $columnClass;
             $text = $pr->getText($outputmode, $this->mShowHeaders == SMW_HEADERS_PLAIN ? null : $this->mLinker);
             $headers[] = Html::rawElement('th', $attribs, $text === '' ? '&nbsp;' : $text);
         }
         $headers = '<tr>' . implode("\n", $headers) . '</tr>';
         if ($outputmode == SMW_OUTPUT_HTML) {
             $headers = '<thead>' . $headers . '</thead>';
         }
         $headers = "\n{$headers}\n";
         $result .= $headers;
     }
     $tableRows = array();
     $rowNum = 1;
     while ($subject = $res->getNext()) {
         $tableRows[] = $this->getRowForSubject($subject, $outputmode, $columnClasses, $rowNum++);
     }
     $tableRows = implode("\n", $tableRows);
     if ($outputmode == SMW_OUTPUT_HTML) {
         $tableRows = '<tbody>' . $tableRows . '</tbody>';
     }
     $result .= $tableRows;
     // print further results footer
     if ($this->linkFurtherResults($res)) {
         $link = $res->getQueryLink();
         if ($this->getSearchLabel($outputmode)) {
             $link->setCaption($this->getSearchLabel($outputmode));
         }
         $result .= "\t<tr class=\"smwfooter\"><td class=\"sortbottom\" colspan=\"" . $res->getColumnCount() . '"> ' . $link->getText($outputmode, $this->mLinker) . "</td></tr>\n";
     }
     // Put the <table> tag around the whole thing
     $tableAttrs = array('class' => $this->mHTMLClass);
     if ($this->mFormat == 'broadtable') {
         $tableAttrs['width'] = '100%';
     }
     $result = Xml::tags('table', $tableAttrs, $result);
     $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
     // yes, our code can be viewed as HTML if requested, no more parsing needed
     return $result;
 }
示例#11
0
 /**
  * Returns an array with sortkeys for dates pointing to their source DataItems.
  *
  * @param SMWQueryResult $res
  *
  * @return array
  */
 protected function getSortKeys(SMWQueryResult $res)
 {
     $seconds = array();
     while ($row = $res->getNext()) {
         foreach ($row as $resultArray) {
             foreach ($resultArray->getContent() as $dataItem) {
                 if ($dataItem->getDIType() === SMWDataItem::TYPE_TIME) {
                     $seconds[$dataItem->getSortKey()] = $dataItem;
                 }
             }
         }
     }
     return $seconds;
 }
示例#12
0
 /**
  * @since 2.0
  *
  * @param  DataItem $expectedDataItem
  * @param  QueryResult $queryResult
  */
 public function assertThatDataItemIsSet(DataItem $expectedDataItem, QueryResult $queryResult)
 {
     $assertThatDataItemIsSet = false;
     $this->assertEmpty($queryResult->getErrors());
     while ($resultArray = $queryResult->getNext()) {
         foreach ($resultArray as $result) {
             while (($dataItem = $result->getNextDataItem()) !== false) {
                 $this->assertEquals($expectedDataItem, $dataItem);
                 $assertThatDataItemIsSet = true;
             }
         }
     }
     $this->assertTrue($assertThatDataItemIsSet, 'Asserts that the expected DataItem is set');
 }
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $result = '';
     if ($outputmode == SMW_OUTPUT_FILE) {
         $people = array();
         $row = $res->getNext();
         while ($row !== false) {
             $people[] = new PersonPageValues($row[0]->getResultSubject());
             $row = $res->getNext();
         }
         $printer = new Gedcom5FilePrinter();
         $printer->addPeople($people);
         $result = $printer->getFile();
     } else {
         // just make link
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('semanticgenealogy-gedcomexport-link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('gedcom5', 'format');
         if ($this->getSearchLabel(SMW_OUTPUT_WIKI) != '') {
             $link->setParameter($this->getSearchLabel(SMW_OUTPUT_WIKI), 'searchlabel');
         }
         if (array_key_exists('limit', $this->m_params)) {
             $link->setParameter($this->m_params['limit'], 'limit');
         } else {
             // use a reasonable default limit
             $link->setParameter(20, 'limit');
         }
         $result .= $link->getText($outputmode, $this->mLinker);
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
     }
     return $result;
 }
 /**
  * Returns an array with numerical data
  *
  * @since 1.8
  *
  * @param SMWQueryResult $result
  * @param $outputMode
  *
  * @return array
  */
 protected function getAggregatedTimeSeries(SMWQueryResult $result, $outputMode)
 {
     $values = array();
     $aggregatedValues = array();
     while ($row = $result->getNext()) {
         // Objects (pages)
         $timeStamp = '';
         $value = '';
         $series = array();
         foreach ($row as $field) {
             $value = array();
             $sum = array();
             $rowSum = array();
             // Group by subject (page object)  or property
             if ($this->params['group'] == 'subject') {
                 $group = $field->getResultSubject()->getTitle()->getText();
             } else {
                 $group = $field->getPrintRequest()->getLabel();
             }
             while (($dataValue = $field->getNextDataValue()) !== false) {
                 // Data values
                 // Find the timestamp
                 if ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_TIME) {
                     // We work with a timestamp, we have to use intval because DataItem
                     // returns a string but we want a numeric representation of the timestamp
                     $timeStamp = intval($dataValue->getDataItem()->getMwTimestamp());
                 }
                 // Find the values (numbers only)
                 if ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_NUMBER) {
                     $sum[] = $dataValue->getNumber();
                 }
             }
             // Aggegate individual values into a sum
             $rowSum = array_sum($sum);
             // Check the sum and threshold/min
             if ($timeStamp !== '' && $rowSum == true && $rowSum >= $this->params['min']) {
                 $series[$group] = array($timeStamp, $rowSum);
             }
         }
         $values[] = $series;
     }
     // Re-assign values according to their group
     foreach ($values as $key => $value) {
         foreach ($values[$key] as $row => $rowvalue) {
             $aggregatedValues[$row][] = $rowvalue;
         }
     }
     return $aggregatedValues;
 }
示例#15
0
 /**
  * Returns an array with the tags (keys) and the number of times they occur (values).
  *
  * @since 1.5.3
  *
  * @param SMWQueryResult $results
  * @param $outputmode
  *
  * @return array
  */
 protected function getTags(SMWQueryResult $results, $outputmode)
 {
     $tags = array();
     $excludetags = explode(';', $this->params['excludetags']);
     while ($row = $results->getNext()) {
         // Objects (pages)
         for ($i = 0, $n = count($row); $i < $n; $i++) {
             // SMWResultArray for a sinlge property
             /**
              * @var SMWDataValue $dataValue
              */
             while (($dataValue = $row[$i]->getNextDataValue()) !== false) {
                 // Data values
                 $isSubject = $row[$i]->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS;
                 // If the main object should not be included, skip it.
                 if ($i == 0 && !$this->params['includesubject'] && $isSubject) {
                     continue;
                 }
                 // Get the HTML for the tag content. Pages are linked, other stuff is just plaintext.
                 if ($dataValue->getTypeID() == '_wpg') {
                     $value = $dataValue->getTitle()->getText();
                     $html = $dataValue->getLongText($outputmode, $this->getLinker($isSubject));
                 } else {
                     $html = $dataValue->getShortText($outputmode, $this->getLinker(false));
                     $value = $html;
                 }
                 // Exclude tags from result set
                 if (in_array($value, $excludetags)) {
                     continue;
                 }
                 // Replace content with template inclusion
                 $html = $this->params['template'] !== '' ? $this->addTemplateOutput($value, $rownum) : $html;
                 if (!array_key_exists($value, $tags)) {
                     $tags[$value] = 0;
                     $this->tagsHtml[$value] = $html;
                     // Store the HTML separetely, so sorting can be done easily.
                 }
                 $tags[$value]++;
             }
         }
     }
     foreach ($tags as $name => $count) {
         if ($count < $this->params['mincount']) {
             unset($tags[$name]);
         }
     }
     return $tags;
 }
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
		$this->isHTML = true;

		$t = "";
		$n = "";

		// if there is only one column in the results then stop right away
		if ($res->getColumnCount() == 1) return "";

		// print all result rows
		$first = true;
		$count = 0; // How many bars will they be? Needed to calculate the height of the image
		$max = 0; // the biggest value. needed for scaling
		
		while ( $row = $res->getNext() ) {
			$name = $row[0]->getNextDataValue()->getShortWikiText();
			foreach ( $row as $field ) {
				while ( ( $object = $field->getNextDataValue() ) !== false ) {
					
					// use numeric sortkey
					if ( $object->isNumeric() ) {
						$nr = $object->getDataItem()->getSortKey();

						$count++;
						$max = max( $max, $nr );

						if ( $first ) {
							$first = false;
							$t .= $nr;
							$n = $name;
						} else {
							$t = $nr . ',' . $t;
							$n .= '|' . $name; // yes, this is correct, it needs to be the other way
						}
					}
				}
			}
		}
		
		$barwidth = 20; // width of each bar
		$bardistance = 4; // distance between two bars
		$height = $count * ( $barwidth + $bardistance ) + 15; // calculates the height of the image
		
		return 	'<img src="http://chart.apis.google.com/chart?cht=bhs&chbh=' . $barwidth . ',' . $bardistance . '&chs=' . $this->m_width . 'x' . $height . '&chds=0,' . $max . '&chd=t:' . $t . '&chxt=y&chxl=0:|' . $n . '" width="' . $this->m_width . '" height="' . $height . '" />';

	}
 /**
  * Returns an array with the tags (keys) and the number of times they occur (values).
  *
  * @since 1.7
  *
  * @param SMWQueryResult $results
  * @param $outputMode
  *
  * @return array
  */
 protected function getResultValues(SMWQueryResult $results, $outputMode)
 {
     $tags = array();
     /**
      * @var $row SMWResultArray Objects (pages)
      * @var $dataValue SMWDataValue
      *
      * @return array
      */
     while ($row = $results->getNext()) {
         // SMWResultArray for a sinlge property
         for ($i = 0, $n = count($row); $i < $n; $i++) {
             while (($dataValue = $row[$i]->getNextDataValue()) !== false) {
                 $isSubject = $row[$i]->getPrintRequest()->getMode() == SMWPrintRequest::PRINT_THIS;
                 // If the main object should not be included, skip it.
                 if ($i == 0 && !$this->params['includesubject'] && $isSubject) {
                     continue;
                 }
                 // Get the HTML for the tag content. Pages are linked, other stuff is just plaintext.
                 if ($dataValue->getTypeID() == '_wpg') {
                     $value = $dataValue->getTitle()->getText();
                     $html = $dataValue->getLongText($outputMode, $this->getLinker($isSubject));
                 } else {
                     $html = $dataValue->getShortText($outputMode, $this->getLinker(false));
                     $value = $html;
                 }
                 if (!array_key_exists($value, $tags)) {
                     $tags[$value] = 0;
                     $this->tagsHtml[$value] = $html;
                     // Store the HTML separetely, so sorting can be done easily.
                 }
                 $tags[$value]++;
             }
         }
     }
     foreach ($tags as $name => $count) {
         if ($count < $this->params['min']) {
             unset($tags[$name]);
         }
     }
     return $tags;
 }
示例#18
0
 /**
  * Adds in the pages from a new query result to the existing set of
  * pages - only pages that weren't in the set already get added.
  * 
  * @param SMWQueryResult $new_result
  */
 public function addResult(SMWQueryResult $newResult)
 {
     $existingPageNames = array();
     while ($row = $this->getNext()) {
         if ($row[0] instanceof SMWResultArray) {
             $content = $row[0]->getContent();
             $existingPageNames[] = $content[0]->getLongText(SMW_OUTPUT_WIKI);
         }
     }
     while (($row = $newResult->getNext()) !== false) {
         if (property_exists($newResult, 'display_options')) {
             $row[0]->display_options = $newResult->display_options;
         }
         $content = $row[0]->getContent();
         $pageName = $content[0]->getLongText(SMW_OUTPUT_WIKI);
         if (!in_array($pageName, $existingPageNames)) {
             $this->m_content[] = $row;
         }
     }
     reset($this->m_content);
 }
 /**
  * @since 2.0
  *
  * @param mixed $expected
  * @param QueryResult $queryResult
  * @param string $message
  */
 public function assertThatDataItemIsSet($expected, QueryResult $queryResult, $message = '')
 {
     $expected = is_array($expected) ? $expected : array($expected);
     if ($expected === array()) {
         return;
     }
     $errors = $queryResult->getErrors();
     $this->assertEmpty($errors, "Failed on {$message} with error(s): " . implode(',', $errors));
     while ($resultArray = $queryResult->getNext()) {
         foreach ($resultArray as $result) {
             while (($dataItem = $result->getNextDataItem()) !== false) {
                 foreach ($expected as $key => $exp) {
                     if ($exp->equals($dataItem)) {
                         unset($expected[$key]);
                     }
                 }
             }
         }
     }
     $this->assertEmpty($expected, "Failed on {$message} to match dataItems [ " . implode(', ', $expected) . ' ] against the expected results.');
 }
 /**
  * Extracts the data we need to build a networkdiag DSL from the
  * semantic result
  *
  * @param  SMWQueryResult $result Result of the query
  *
  * @return array                  Array of data to be fed to generateDiagCode()
  */
 protected function getResultData(SMWQueryResult $result)
 {
     $data = array();
     while ($rows = $result->getNext()) {
         foreach ($rows as $field) {
             $propertyLabel = $field->getPrintRequest()->getLabel();
             $server_name = $field->getResultSubject()->getTitle();
             $server_name = strtolower($server_name->getFullText());
             while (($dataValue = $field->getNextDataValue()) !== false) {
                 if ($propertyLabel === "ipv4") {
                     $ip_address = $dataValue->getWikiValue();
                     $data[$server_name]["ip_address"] = $ip_address;
                 } elseif ($propertyLabel === "fqdn") {
                     $fqdn = strtolower($dataValue->getWikiValue());
                     if (isset($this->params['domain'])) {
                         $fqdn = str_replace($this->params['domain'], '', $fqdn);
                     }
                     $domain_parts = explode('.', $fqdn);
                     $hostname = $domain_parts[0];
                     $group = '';
                     if (count($domain_parts) >= 1) {
                         $group = $domain_parts[1];
                         $node_host = sprintf('%s.%s', $hostname, $group);
                     }
                     $data[$server_name]["fqdn"] = $fqdn;
                     $data[$server_name]["node_host"] = !empty($group) ? $node_host : $hostname;
                     $data[$server_name]["group"] = $group;
                 }
             }
             // If a row does not have a value for the FQDN property label, it will not be returned
             // by $field->getNextDataValue()
             if (!isset($data[$server_name]["fqdn"])) {
                 $data[$server_name]["fqdn"] = $server_name;
                 $data[$server_name]["node_host"] = $server_name;
                 $data[$server_name]["group"] = $server_name;
             }
         }
     }
     return $data;
 }
示例#21
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     if (!is_callable('renderGraphviz')) {
         wfWarn('The SRF Graph printer needs the GraphViz extension to be installed.');
         return '';
     }
     global $wgGraphVizSettings;
     $this->isHTML = true;
     $graphInput = "digraph {$this->m_graphName} {";
     if ($this->m_graphSize != '') {
         $graphInput .= "size=\"{$this->m_graphSize}\";";
     }
     if ($this->m_nodeShape) {
         $graphInput .= "node [shape={$this->m_nodeShape}];";
     }
     $graphInput .= "rankdir={$this->m_rankdir};";
     while ($row = $res->getNext()) {
         $graphInput .= $this->getGVForItem($row, $outputmode);
     }
     $graphInput .= "}";
     // Calls renderGraphViz function from MediaWiki GraphViz extension
     $result = renderGraphviz($graphInput);
     if ($this->m_graphLegend && $this->m_graphColor) {
         $arrayCount = 0;
         $arraySize = count($this->m_graphColors);
         $result .= "<P>";
         foreach ($this->m_labelArray as $m_label) {
             if ($arrayCount >= $arraySize) {
                 $arrayCount = 0;
             }
             $color = $this->m_graphColors[$arrayCount];
             $result .= "<font color={$color}>{$color}: {$m_label} </font><br />";
             $arrayCount += 1;
         }
         $result .= "</P>";
     }
     return $result;
 }
示例#22
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $result = '';
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make CSV file
         $csv = fopen('php://temp', 'r+');
         $sep = str_replace('_', ' ', $this->params['sep']);
         if ($this->params['showsep']) {
             fputs($csv, "sep=" . $sep . "\n");
         }
         if ($this->mShowHeaders) {
             $header_items = array();
             foreach ($res->getPrintRequests() as $pr) {
                 $header_items[] = $pr->getLabel();
             }
             fputcsv($csv, $header_items, $sep);
         }
         while ($row = $res->getNext()) {
             $row_items = array();
             foreach ($row as $field) {
                 $growing = array();
                 while (($object = $field->getNextDataValue()) !== false) {
                     $growing[] = Sanitizer::decodeCharReferences($object->getWikiValue());
                 }
                 $row_items[] = implode(',', $growing);
             }
             fputcsv($csv, $row_items, $this->m_sep);
         }
         rewind($csv);
         $result .= stream_get_contents($csv);
     } else {
         // just make link to feed
         $result .= $this->getLink($res, $outputmode)->getText($outputmode, $this->mLinker);
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
     }
     return $result;
 }
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
		$print_fields = array();
		foreach ( $res->getPrintRequests() as $pr ) {
			$field_name = $pr->getText( $outputmode, $this->mLinker );
			// only print it if it's not already part of the
			// outline
			if ( ! in_array( $field_name, $this->mOutlineProperties ) ) {
				$print_fields[] = $field_name;
			}
		}

		// for each result row, create an array of the row itself
		// and all its sorted-on fields, and add it to the initial
		// 'tree'
		$outline_tree = new SRFOutlineTree();
		while ( $row = $res->getNext() ) {
			$item = new SRFOutlineItem( $row );
			foreach ( $row as $field ) {
				$first = true;
				$field_name = $field->getPrintRequest()->getText( SMW_OUTPUT_HTML );
				if ( in_array( $field_name, $this->mOutlineProperties ) ) {
					while ( ( $object = $field->getNextDataValue() ) !== false ) {
						$field_val = $object->getLongWikiText( $this->mLinker );
						$item->addFieldValue( $field_name, $field_val );
					}
				}
			}
			$outline_tree->addItem( $item );
		}

		// now, cycle through the outline properties, creating the
		// tree
		foreach ( $this->mOutlineProperties as $outline_prop ) {
			$outline_tree->addProperty( $outline_prop );
		}
		$result = $this->printTree( $outline_tree );

		// print further results footer
		if ( $this->linkFurtherResults( $res ) ) {
			$link = $res->getQueryLink();
			if ( $this->getSearchLabel( $outputmode ) ) {
				$link->setCaption( $this->getSearchLabel( $outputmode ) );
			}
			$link->setParameter( 'outline', 'format' );
			if ( array_key_exists( 'outlineproperties', $this->m_params ) ) {
				$link->setParameter( $this->m_params['outlineproperties'], 'outlineproperties' );
			}
			$result .= $link->getText( $outputmode, $this->mLinker ) . "\n";
		}
		return $result;
	}
示例#24
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     if ($this->mFormat == 'template' && $this->mTemplate == false) {
         $res->addErrors(array(wfMessage('smw_notemplategiven')->inContentLanguage()->text()));
         return '';
     }
     // Determine mark-up strings used around list items:
     if ($this->mFormat == 'ul' || $this->mFormat == 'ol') {
         $header = "<" . $this->mFormat . ">\n";
         $footer = "</" . $this->mFormat . ">\n";
         $rowstart = "\t<li>";
         $rowend = "</li>\n";
         $plainlist = false;
     } else {
         // "list" and "template" format
         $header = '';
         $footer = '';
         $rowstart = '';
         $rowend = '';
         $plainlist = true;
     }
     if ($this->mSep !== '') {
         // always respect custom separator
         $listsep = $this->mSep;
         $finallistsep = $listsep;
     } elseif ($this->mFormat == 'list') {
         // make default list ", , , and "
         // TODO: No default separator for "ul" and "ol" to not break
         // compatibility with SMW pre 1.7.1. But they really should have
         // default separators, i.e. the check should be for
         // $this->mFormat !== 'template'
         $listsep = ', ';
         $finallistsep = wfMessage('smw_finallistconjunct')->inContentLanguage()->text() . ' ';
     } else {
         // no default separators for format "template", "ul", "ol"
         $listsep = '';
         $finallistsep = '';
     }
     // Initialise more values
     $result = '';
     $column_width = 0;
     $rows_per_column = -1;
     // usually unnecessary
     $rows_in_cur_column = -1;
     // Set up floating divs, if there's more than one column
     if ($this->mColumns > 1) {
         $column_width = floor(100 / $this->mColumns);
         $result .= '<div style="float: left; width: ' . $column_width . '%">' . "\n";
         $rows_per_column = ceil($res->getCount() / $this->mColumns);
         $rows_in_cur_column = 0;
     }
     if ($header !== '') {
         $result .= $header;
     }
     if ($this->mIntroTemplate !== '') {
         $result .= "{{" . $this->mIntroTemplate . "}}";
     }
     // Now print each row
     $rownum = -1;
     while ($row = $res->getNext()) {
         $this->printRow($row, $rownum, $rows_in_cur_column, $rows_per_column, $this->mFormat, $plainlist, $header, $footer, $rowstart, $rowend, $result, $column_width, $res, $listsep, $finallistsep);
     }
     if ($this->mOutroTemplate !== '') {
         $result .= "{{" . $this->mOutroTemplate . "}}";
     }
     // Make label for finding further results
     if ($this->linkFurtherResults($res) && ($this->mFormat != 'ol' || $this->getSearchLabel(SMW_OUTPUT_WIKI))) {
         $this->showFurtherResults($result, $res, $rowstart, $rowend, $outputmode);
     }
     // Print footer
     if ($footer !== '') {
         $result .= $footer;
     }
     if ($this->mColumns > 1) {
         $result .= "</div>\n";
     }
     if ($this->mColumns > 1) {
         $result .= '<br style="clear: both" />' . "\n";
     }
     // Make sure that if the result set turns empty and if available display default
     if ($this->params['default'] !== '' && $result === '') {
         $result = $this->params['default'];
     }
     return $result;
 }
示例#25
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     global $wgContLang;
     // <H3> will generate TOC entries otherwise.  Probably need another way
     // to accomplish this -- user might still want TOC for other page content.
     $result = '__NOTOC__';
     $num = $res->getCount();
     $prev_first_char = "";
     $rows_per_column = ceil($num / $this->mNumColumns);
     // column width is a percentage
     $column_width = floor(100 / $this->mNumColumns);
     // Print all result rows:
     $rowindex = 0;
     $row = $res->getNext();
     while ($row !== false) {
         $nextrow = $res->getNext();
         // look ahead
         $content = $row[0]->getContent();
         $cur_first_char = $wgContLang->firstChar($content[0]->getDIType() == SMWDataItem::TYPE_WIKIPAGE ? $res->getStore()->getWikiPageSortKey($content[0]) : $content[0]->getSortKey());
         if ($rowindex % $rows_per_column == 0) {
             $result .= "\n\t\t\t<div style=\"float: left; width: {$column_width}%;\">\n";
             if ($cur_first_char == $prev_first_char) {
                 $result .= "\t\t\t\t<h3>{$cur_first_char} " . wfMessage('listingcontinuesabbrev')->text() . "</h3>\n\t\t\t\t<ul>\n";
             }
         }
         // if we're at a new first letter, end
         // the last list and start a new one
         if ($cur_first_char != $prev_first_char) {
             if ($rowindex % $rows_per_column > 0) {
                 $result .= "\t\t\t\t</ul>\n";
             }
             $result .= "\t\t\t\t<h3>{$cur_first_char}</h3>\n\t\t\t\t<ul>\n";
         }
         $prev_first_char = $cur_first_char;
         $result .= '<li>';
         $first_col = true;
         if ($this->mTemplate !== '') {
             // build template code
             $this->hasTemplates = true;
             $wikitext = $this->mUserParam ? "|userparam={$this->mUserParam}" : '';
             $i = 1;
             // explicitly number parameters for more robust parsing (values may contain "=")
             foreach ($row as $field) {
                 $wikitext .= '|' . $i++ . '=';
                 $first_value = true;
                 while (($text = $field->getNextText(SMW_OUTPUT_WIKI, $this->getLinker($first_col))) !== false) {
                     if ($first_value) {
                         $first_value = false;
                     } else {
                         $wikitext .= $this->mDelim . ' ';
                     }
                     $wikitext .= $text;
                 }
                 $first_col = false;
             }
             $wikitext .= "|#={$rowindex}";
             $result .= '{{' . $this->mTemplate . $wikitext . '}}';
             // str_replace('|', '&#x007C;', // encode '|' for use in templates (templates fail otherwise) -- this is not the place for doing this, since even DV-Wikitexts contain proper "|"!
         } else {
             // build simple list
             $first_col = true;
             $found_values = false;
             // has anything but the first column been printed?
             foreach ($row as $field) {
                 $first_value = true;
                 while (($text = $field->getNextText(SMW_OUTPUT_WIKI, $this->getLinker($first_col))) !== false) {
                     if (!$first_col && !$found_values) {
                         // first values after first column
                         $result .= ' (';
                         $found_values = true;
                     } elseif ($found_values || !$first_value) {
                         // any value after '(' or non-first values on first column
                         $result .= ', ';
                     }
                     if ($first_value) {
                         // first value in any column, print header
                         $first_value = false;
                         if ($this->mShowHeaders && $field->getPrintRequest()->getLabel() !== '') {
                             $result .= $field->getPrintRequest()->getText(SMW_OUTPUT_WIKI, $this->mLinker) . ' ';
                         }
                     }
                     $result .= $text;
                     // actual output value
                 }
                 $first_col = false;
             }
             if ($found_values) {
                 $result .= ')';
             }
         }
         $result .= '</li>';
         $row = $nextrow;
         // end list if we're at the end of the column
         // or the page
         if (($rowindex + 1) % $rows_per_column == 0 && $rowindex + 1 < $num) {
             $result .= "\t\t\t\t</ul>\n\t\t\t</div> <!-- end column -->";
         }
         $rowindex++;
     }
     // Make label for finding further results
     if ($this->linkFurtherResults($res)) {
         $result .= '<br /><li>' . $this->getLink($res, $outputmode)->getText(SMW_OUTPUT_WIKI, $this->mLinker) . '</li>';
     }
     $result .= "\t\t\t\t</ul>\n\t\t\t</div> <!-- end column -->";
     // clear all the CSS floats
     $result .= "\n" . '<br style="clear: both;"/>';
     return $result;
 }
 /**
  * (non-PHPdoc)
  * @see SMWResultPrinter::getResultText()
  *
  * @todo Split up megamoth
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $events = array();
     // Print all result rows.
     while ($row = $res->getNext()) {
         $dates = array();
         $title = $text = $color = '';
         if ($this->mTemplate != '') {
             // Build template code
             $this->hasTemplates = true;
             if ($this->mUserParam) {
                 $text = "|userparam={$this->mUserParam}";
             }
             foreach ($row as $i => $field) {
                 $pr = $field->getPrintRequest();
                 $text .= '|' . ($i + 1) . '=';
                 while (($object = $field->getNextDataValue()) !== false) {
                     if ($object->getTypeID() == '_dat') {
                         $text .= $object->getLongWikiText();
                         // use shorter "LongText" for wikipage
                     } elseif ($object->getTypeID() == '_wpg') {
                         // handling of "link=" param
                         if ($this->mLinkOthers) {
                             $text .= $object->getLongText($outputmode, null);
                         } else {
                             $text .= $object->getWikiValue();
                         }
                     } else {
                         $text .= $object->getShortText($outputmode, null);
                     }
                     if ($pr->getMode() == SMWPrintRequest::PRINT_PROP && $pr->getTypeID() == '_dat') {
                         $datePropLabel = $pr->getLabel();
                         if (!array_key_exists($datePropLabel, $dates)) {
                             $dates[$datePropLabel] = array();
                         }
                         $dates[$datePropLabel][] = $this->formatDateStr($object);
                     }
                 }
             }
         } else {
             // Build simple text.
             $numNonDateProperties = 0;
             // Cycle through a 'row', which is the page
             // name (the first field) plus all its
             // properties.
             foreach ($row as $i => $field) {
                 $pr = $field->getPrintRequest();
                 // A property can have more than one
                 // value - cycle through all the values
                 // for this property.
                 $textForProperty = '';
                 while (($object = $field->getNextDataValue()) !== false) {
                     if ($object->getTypeID() == '_dat') {
                         // Don't add date values to the display.
                         // use shorter "LongText" for wikipage
                     } elseif ($object->getTypeID() == '_wpg') {
                         if ($i == 0) {
                             $title = Title::newFromText($object->getShortWikiText(false));
                         } else {
                             $numNonDateProperties++;
                             // handling of "headers=" param
                             if ($this->mShowHeaders == SMW_HEADERS_SHOW) {
                                 $textForProperty .= $pr->getHTMLText(smwfGetLinker()) . ' ';
                             } elseif ($this->mShowHeaders == SMW_HEADERS_PLAIN) {
                                 $textForProperty .= $pr->getLabel() . ' ';
                             }
                             // If $this->mShowHeaders == SMW_HEADERS_HIDE,
                             //	print nothing.
                             // handling of "link=" param
                             if ($this->mLinkOthers) {
                                 $textForProperty .= $object->getLongText($outputmode, smwfGetLinker());
                             } else {
                                 $textForProperty .= $object->getWikiValue();
                             }
                         }
                     } else {
                         $numNonDateProperties++;
                         $textForProperty .= $pr->getHTMLText(smwfGetLinker()) . ' ' . $object->getShortText($outputmode, smwfGetLinker());
                     }
                     if ($pr->getMode() == SMWPrintRequest::PRINT_PROP && $pr->getTypeID() == '_dat') {
                         $datePropLabel = $pr->getLabel();
                         if (!array_key_exists($datePropLabel, $dates)) {
                             $dates[$datePropLabel] = array();
                         }
                         $dates[$datePropLabel][] = $this->formatDateStr($object);
                     }
                 }
                 // Add the text for this property to
                 // the main text, adding on parentheses
                 // or commas as needed.
                 if ($numNonDateProperties == 1) {
                     $text .= ' (';
                 } elseif ($numNonDateProperties > 1) {
                     $text .= ', ';
                 }
                 $text .= $textForProperty;
             }
             if ($numNonDateProperties > 0) {
                 $text .= ')';
             }
         }
         if (count($dates) > 0) {
             // Handle the 'color=' value, whether it came
             // from a compound query or a regular one.
             $resSubject = $field->getResultSubject();
             if (isset($resSubject->display_options) && is_array($resSubject->display_options)) {
                 if (array_key_exists('color', $resSubject->display_options)) {
                     $color = $resSubject->display_options['color'];
                 }
                 if (array_key_exists('colors', $resSubject->display_options)) {
                     $this->setColors($resSubject->display_options['colors']);
                 }
             }
             foreach ($dates as $label => $datesForLabel) {
                 foreach ($datesForLabel as $date) {
                     $curText = $text;
                     // If there's more than one
                     // label, i.e. more than one
                     // date property being displayed,
                     // show the name of the current
                     // property in parentheses.
                     if (count($dates) > 1) {
                         $curText = "({$label}) " . $curText;
                     }
                     $curColor = $color;
                     if (array_key_exists($label, $this->mColors)) {
                         $curColor = $this->mColors[$label];
                     }
                     $events[] = array($title, $curText, $date, $curColor);
                 }
             }
         }
     }
     $result = $this->displayCalendar($events);
     // Go back to the actual user's language, in case a different
     // language had been specified for this calendar.
     if (!is_null($this->mRealUserLang)) {
         global $wgLang;
         $wgLang = $this->mRealUserLang;
     }
     global $wgParser;
     if (is_null($wgParser->getTitle())) {
         return $result;
     } else {
         return array($result, 'noparse' => 'true', 'isHTML' => 'true');
     }
 }
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
		if ( ( $this->mFormat == 'template' ) && ( $this->mTemplate == false ) ) {
			$res->addErrors( array( wfMsgForContent( 'smw_notemplategiven' ) ) );
			return '';
		}
		
		// Determine mark-up strings used around list items:
		if ( ( $this->mFormat == 'ul' ) || ( $this->mFormat == 'ol' ) ) {
			$header = "<" . $this->mFormat . ">\n";
			$footer = "</" . $this->mFormat . ">\n";
			$rowstart = "\t<li>";
			$rowend = "</li>\n";
			$plainlist = false;
			$finallistsep = '';
			$listsep = '';
		} else { // "list" and "template" format
			$header = '';
			$footer = '';
			$rowstart = '';
			$rowend = '';
			$plainlist = true;
			
			if ( $this->mSep !== '' ) { // always respect custom separator
				$listsep = $this->mSep;
				$finallistsep = $listsep;
			} elseif ( $this->mFormat == 'list' )  {  // make default list ", , , and "
				$listsep = ', ';
				$finallistsep = wfMsgForContent( 'smw_finallistconjunct' ) . ' ';
			} else { // no default separators for format "template"
				$listsep = '';
				$finallistsep = '';
			}
		}
		
		// Initialise more values
		$result = '';
		$column_width = 0;
		$rows_per_column = -1; // usually unnecessary
		$rows_in_cur_column = -1;
		
		// Set up floating divs, if there's more than one column
		if ( $this->mColumns > 1 ) {
			$column_width = floor( 100 / $this->mColumns );
			$result .= '<div style="float: left; width: ' . $column_width . '%">' . "\n";
			$rows_per_column = ceil( $res->getCount() / $this->mColumns );
			$rows_in_cur_column = 0;
		}

		if ( $header !== '' ) {
			$result .= $header;
		} 
		
		if ( $this->mIntroTemplate !== '' ) {
			$result .= "{{" . $this->mIntroTemplate . "}}";
		}

		// Now print each row
		$rownum = -1;
		while ( $row = $res->getNext() ) {
			$this->printRow( $row, $rownum, $rows_in_cur_column,
				$rows_per_column, $this->mFormat, $plainlist,
				$header, $footer, $rowstart, $rowend, $result,
				$column_width, $res, $listsep, $finallistsep );
		}
		
		if ( $this->mOutroTemplate !== '' ) {
			$result .= "{{" . $this->mOutroTemplate . "}}";
		}
		
		// Make label for finding further results
		if ( $this->linkFurtherResults( $res ) && ( ( $this->mFormat != 'ol' ) || ( $this->getSearchLabel( SMW_OUTPUT_WIKI ) ) ) ) {
			$this->showFurtherResults( $result, $res, $rowstart, $rowend );
		}

		// Print footer
		if ( $footer !== '' ) {
			$result .= $footer;
		}
		
		if ( $this->mColumns > 1 ) {
			$result .= "</div>\n";
		}
		
		if ( $this->mColumns > 1 ) {
			$result .= '<br style="clear: both" />' . "\n";
		}

		return $result;
	}
示例#28
0
 /**
  * Returns an array with the numerical data in the query result.
  *
  * @since 1.7
  *
  * @param SMWQueryResult $res
  * @param $outputmode
  *
  * @return array label => value
  */
 protected function getNumericResults(SMWQueryResult $res, $outputmode)
 {
     $values = array();
     // print all result rows
     while ($row = $res->getNext()) {
         $dataValue = $row[0]->getNextDataValue();
         if ($dataValue !== false) {
             $name = $dataValue->getShortWikiText();
             foreach ($row as $field) {
                 while (($dataItem = $field->getNextDataItem()) !== false) {
                     $this->addNumbersForDataItem($dataItem, $values, $name);
                 }
             }
         }
     }
     return $values;
 }
示例#29
0
 /**
  * Return serialised results in specified format.
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     // collect the query results in an array
     $result = array();
     while ($row = $res->getNext()) {
         $result[uniqid()] = new SRF_Filtered_Item($row, $this);
     }
     $resourceModules = array();
     // prepare filter data for inclusion in HTML and  JS
     $filterHtml = '';
     $filterHandlers = array();
     $filterData = array();
     foreach ($res->getPrintRequests() as $printRequest) {
         $filter = $printRequest->getParameter('filter');
         if ($filter) {
             $filtersForPrintout = array_map('trim', explode(',', $filter));
             foreach ($filtersForPrintout as $filterName) {
                 if (array_key_exists($filterName, $this->mFilterTypes)) {
                     $filter = new $this->mFilterTypes[$filterName]($result, $printRequest, $this);
                     $resourceModules = $filter->getResourceModules();
                     if (is_array($resourceModules)) {
                         array_walk($resourceModules, 'SMWOutputs::requireResource');
                     } elseif (is_string($resourceModules)) {
                         SMWOutputs::requireResource($resourceModules);
                     }
                     $printRequestHash = md5($printRequest->getHash());
                     $filterHtml .= Html::rawElement('div', array('class' => "filtered-{$filterName} {$printRequestHash}"), $filter->getResultText());
                     $filterHandlers[$filterName] = null;
                     $filterData[$filterName][$printRequestHash] = $filter->getJsData();
                 }
             }
         }
     }
     // wrap filters in a div
     $filterHtml = Html::rawElement('div', array('class' => 'filtered-filters'), $filterHtml);
     // prepare view data for inclusion in HTML and  JS
     $viewHtml = '';
     $viewSelectorsHtml = '';
     $viewHandlers = array();
     $viewElements = array();
     // will contain the id of the html element to be used by the view
     $viewData = array();
     foreach ($this->mViews as $viewName) {
         // cut off the selector label (if one was specified) from the actual view name
         $viewnameComponents = explode('=', $viewName, 2);
         $viewName = trim($viewnameComponents[0]);
         if (array_key_exists($viewName, $this->mViewTypes)) {
             // generate unique id
             $viewid = uniqid();
             $view = new $this->mViewTypes[$viewName]($viewid, $result, $this->mParams, $this);
             if (count($viewnameComponents) > 1) {
                 // a selector label was specified in the wiki text
                 $viewSelectorLabel = trim($viewnameComponents[1]);
             } else {
                 // use the default selector label
                 $viewSelectorLabel = $view->getSelectorLabel();
             }
             $resourceModules = $view->getResourceModules();
             if (is_array($resourceModules)) {
                 array_walk($resourceModules, 'SMWOutputs::requireResource');
             } elseif (is_string($resourceModules)) {
                 SMWOutputs::requireResource($resourceModules);
             }
             $viewHtml .= Html::rawElement('div', array('class' => "filtered-view filtered-{$viewName} filtered-view-id{$viewid}"), $view->getResultText());
             $viewSelectorsHtml .= Html::rawElement('div', array('class' => "filtered-view-selector filtered-{$viewName} filtered-view-id{$viewid}"), $viewSelectorLabel);
             $viewHandlers[$viewName] = null;
             $viewElements[$viewName][] = $viewid;
             $viewData[$viewName] = $view->getJsData();
         }
     }
     // more than one view?
     if (count($viewData) > 1) {
         // wrap views in a div
         $viewHtml = Html::rawElement('div', array('class' => 'filtered-views', 'style' => 'display:none'), Html::rawElement('div', array('class' => 'filtered-views-selectors-container'), $viewSelectorsHtml) . Html::rawElement('div', array('class' => 'filtered-views-container'), $viewHtml));
     } else {
         // wrap views in a div
         $viewHtml = Html::rawElement('div', array('class' => 'filtered-views', 'style' => 'display:none'), Html::rawElement('div', array('class' => 'filtered-views-container'), $viewHtml));
     }
     // Define the srf_filtered_values array
     SMWOutputs::requireScript('srf_filtered_values', Html::inlineScript('srf_filtered_values = {};'));
     $resultAsArray = array();
     foreach ($result as $id => $value) {
         $resultAsArray[$id] = $value->getArrayRepresentation();
     }
     $id = uniqid();
     SMWOutputs::requireScript('srf_filtered_values' . $id, Html::inlineScript('srf_filtered_values["' . $id . '"] = { "values":' . json_encode($resultAsArray) . ', "data": {' . ' "viewhandlers" : ' . json_encode($viewHandlers) . ', "viewelements" : ' . json_encode($viewElements) . ', "viewdata" : ' . json_encode($viewData) . ', "filterhandlers" : ' . json_encode($filterHandlers) . ', "filterdata" : ' . json_encode($filterData) . ', "sorthandlers" : ' . json_encode(array()) . ', "sorterdata" : ' . json_encode(array()) . '}};'));
     SMWOutputs::requireResource('ext.srf.filtered');
     // wrap all in a div
     if ($this->mFiltersOnTop) {
         $html = Html::rawElement('div', array('class' => 'filtered ' . $id), $filterHtml . $viewHtml);
     } else {
         $html = Html::rawElement('div', array('class' => 'filtered ' . $id), $viewHtml . $filterHtml);
     }
     return $html;
 }
示例#30
0
 /**
  * Return serialised results in specified format.
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     if ($this->mTreeProp === null || $this->mTreeProp === '') {
         $res->addErrors(array(wfMessage('srf-noparentprop')->inContentLanguage()->text()));
         return '';
     }
     $store = $res->getStore();
     // first put everything in a list
     // elements appearing more than once will be inserted more than once,
     // but only one instance will be inserted with the hash
     // only this instance will be considered as a parent element in the tree
     $list = array();
     while ($row = $res->getNext()) {
         $hash = $row[0]->getResultSubject()->getSerialization();
         if (array_key_exists($hash, $list)) {
             $list[] = new SRFTreeElement($row);
         } else {
             $list[$hash] = new SRFTreeElement($row);
         }
     }
     // transfer the listelements into the tree
     // elements with more than one parent will be cloned for each parent
     $tree = array();
     foreach ($list as $hash => $listElem) {
         $parents = $store->getPropertyValues($listElem->mRow[0]->getResultSubject(), SMWDIProperty::newFromUserLabel($this->mTreeProp));
         // transfer element from list to tree
         foreach ($parents as $parent) {
             $parentPageHash = $parent->getSerialization();
             if ($hash !== null) {
                 if (array_key_exists($parentPageHash, $list)) {
                     $listElem->mParent = $parentPageHash;
                 }
                 $tree[$hash] = $listElem;
                 $hash = null;
             } else {
                 $treeElem = clone $listElem;
                 if (array_key_exists($parentPageHash, $list)) {
                     $treeElem->mParent = $parentPageHash;
                 } else {
                     $treeElem->mParent = null;
                 }
                 $tree[] = $treeElem;
             }
         }
     }
     foreach ($tree as $hash => $value) {
     }
     // build pointers from parants to children
     foreach ($tree as $hash => $treeElem) {
         if ($treeElem->mParent != null) {
             $tree[$treeElem->mParent]->mChildren[] = $treeElem;
         }
     }
     // remove children from toplevel
     foreach ($tree as $hash => $treeElem) {
         if ($treeElem->mParent != null) {
             unset($tree[$hash]);
         }
     }
     $result = '';
     $rownum = 0;
     foreach ($tree as $hash => $treeElem) {
         $this->printElement($result, $treeElem, $row);
     }
     return $result;
 }