示例#1
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);
 }
 /**
  * Return serialised results in specified format.
  * Implemented by subclasses.
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $html = '';
     $id = uniqid();
     // build an array of article IDs contained in the result set
     $objects = array();
     foreach ($res->getResults() as $key => $object) {
         $objects[] = array($object->getTitle()->getArticleId());
         $html .= $key . ': ' . $object->getSerialization() . "<br>\n";
     }
     // build an array of data about the printrequests
     $printrequests = array();
     foreach ($res->getPrintRequests() as $key => $printrequest) {
         $data = $printrequest->getData();
         if ($data instanceof SMWPropertyValue) {
             $name = $data->getDataItem()->getKey();
         } else {
             $name = null;
         }
         $printrequests[] = array($printrequest->getMode(), $printrequest->getLabel(), $name, $printrequest->getOutputFormat(), $printrequest->getParameters());
     }
     // write out results and query params into JS arrays
     // Define the srf_filtered_values array
     SMWOutputs::requireScript('srf_slideshow', Html::inlineScript('srf_slideshow = {};'));
     SMWOutputs::requireScript('srf_slideshow' . $id, Html::inlineScript('srf_slideshow["' . $id . '"] = ' . json_encode(array($objects, $this->params['template'], $this->params['delay'] * 1000, $this->params['height'], $this->params['width'], $this->params['nav controls'], $this->params['effect'], json_encode($printrequests))) . ';'));
     SMWOutputs::requireResource('ext.srf.slideshow');
     if ($this->params['nav controls']) {
         SMWOutputs::requireResource('jquery.ui.slider');
     }
     return Html::element('div', array('id' => $id, 'class' => 'srf-slideshow ' . $id . ' ' . $this->params['class']));
 }
示例#3
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;
 }
示例#4
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;
 }
示例#5
0
 /**
  * Get the serialization for a SMWQueryResult object.
  *
  * @since 1.7
  *
  * @param SMWQueryResult $result
  *
  * @return array
  */
 public static function getSerializedQueryResult(SMWQueryResult $queryResult)
 {
     $results = array();
     $printRequests = array();
     foreach ($queryResult->getPrintRequests() as $printRequest) {
         $printRequests[] = array('label' => $printRequest->getLabel(), 'typeid' => $printRequest->getTypeID(), 'mode' => $printRequest->getMode());
     }
     foreach ($queryResult->getResults() as $diWikiPage) {
         $result = array('printouts' => array());
         foreach ($queryResult->getPrintRequests() as $printRequest) {
             $resultAarray = new SMWResultArray($diWikiPage, $printRequest, $queryResult->getStore());
             if ($printRequest->getMode() === SMWPrintRequest::PRINT_THIS) {
                 $dataItems = $resultAarray->getContent();
                 $result += self::getSerialization(array_shift($dataItems));
             } else {
                 $result['printouts'][$printRequest->getLabel()] = array_map(array(__CLASS__, 'getSerialization'), $resultAarray->getContent());
             }
         }
         $results[$diWikiPage->getTitle()->getFullText()] = $result;
     }
     return array('printrequests' => $printRequests, 'results' => $results);
 }
示例#6
0
 public function getResultText(SMWQueryResult $results, $outputmode)
 {
     global $wgUser, $wgParser;
     $ig = new ImageGallery();
     $ig->setShowBytes(false);
     $ig->setShowFilename(false);
     $ig->setParser($wgParser);
     $ig->setCaption($this->mIntro);
     // set caption to IQ header
     if ($this->params['galleryformat'] == 'carousel') {
         static $carouselNr = 0;
         // Set attributes for jcarousel
         $dataAttribs = array('wrap' => 'both', 'vertical' => 'false', 'rtl' => 'false');
         // Use perrow parameter to determine the scroll sequence.
         if (empty($this->params['perrow'])) {
             $dataAttribs['scroll'] = 1;
             // default 1
         } else {
             $dataAttribs['scroll'] = $this->params['perrow'];
             $dataAttribs['visible'] = $this->params['perrow'];
         }
         $attribs = array('id' => 'carousel' . ++$carouselNr, 'class' => 'jcarousel jcarousel-skin-smw', 'style' => 'display:none;');
         foreach ($dataAttribs as $name => $value) {
             $attribs['data-' . $name] = $value;
         }
         $ig->setAttributes($attribs);
         // Load javascript module
         SMWOutputs::requireResource('ext.srf.jcarousel');
     }
     // In case galleryformat = carousel, perrow should not be set
     if ($this->params['perrow'] !== '' && $this->params['galleryformat'] !== 'carousel') {
         $ig->setPerRow($this->params['perrow']);
     }
     if ($this->params['widths'] !== '') {
         $ig->setWidths($this->params['widths']);
     }
     if ($this->params['heights'] !== '') {
         $ig->setHeights($this->params['heights']);
     }
     $printReqLabels = array();
     foreach ($results->getPrintRequests() as $printReq) {
         $printReqLabels[] = $printReq->getLabel();
     }
     if ($this->params['imageproperty'] !== '' && in_array($this->params['imageproperty'], $printReqLabels)) {
         $this->addImageProperties($results, $ig, $this->params['imageproperty'], $this->params['captionproperty']);
     } else {
         $this->addImagePages($results, $ig);
     }
     return array($ig->toHTML(), 'nowiki' => true, 'isHTML' => true);
 }
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
		global $smwgIQRunningNumber;
		
		$this->includeJS();

		$isEventline = 'eventline' == $this->mFormat;

		if ( !$isEventline && ( $this->m_tlstart == '' ) ) { // seek defaults
			foreach ( $res->getPrintRequests() as $pr ) {
				if ( ( $pr->getMode() == SMWPrintRequest::PRINT_PROP ) && ( $pr->getTypeID() == '_dat' ) ) {
					$dataValue = $pr->getData();
					
					$date_value = $dataValue->getDataItem()->getLabel();
					
					if ( ( $this->m_tlend == '' ) && ( $this->m_tlstart != '' ) &&
					     ( $this->m_tlstart != $date_value ) ) {
						$this->m_tlend = $date_value;
					} elseif ( ( $this->m_tlstart == '' ) && ( $this->m_tlend != $date_value ) ) {
						$this->m_tlstart = $date_value;
					}
				}
			}
		}

		// print header
		$link = $res->getQueryLink( wfMsgForContent( 'srf-timeline-allresults' ) );
		$result = "<div class=\"smwtimeline\" id=\"smwtimeline$smwgIQRunningNumber\" style=\"height: $this->m_tlsize\">";
		$result .= '<span class="smwtlcomment">' . wfMsgForContent( 'srf-timeline-nojs' ) . ' ' . $link->getText( $outputmode, $this->mLinker ) . '</span>'; // note for people without JavaScript

		foreach ( $this->m_tlbands as $band ) {
			$result .= '<span class="smwtlband" style="display:none;">' . htmlspecialchars( $band ) . '</span>';
			// just print any "band" given, the JavaScript will figure out what to make of it
		}

		// print all result rows		
		if ( ( $this->m_tlstart != '' ) || $isEventline ) {
			$result .= $this->getEventsHTML( $res, $outputmode, $isEventline );
		}
		// no further results displayed ...

		// print footer
		$result .= '</div>';
		
		// yes, our code can be viewed as HTML if requested, no more parsing needed
		$this->isHTML = $outputmode == SMW_OUTPUT_HTML;
		
		return $result;
	}	
示例#8
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;
 }
	public function getResultText( SMWQueryResult $results, $outputmode ) {
		global $wgUser, $wgParser;

		$ig = new ImageGallery();
		$ig->setShowBytes( false );
		$ig->setShowFilename( false );
		$ig->setParser( $wgParser );
		$ig->setCaption( $this->mIntro ); // set caption to IQ header

		if ( $this->m_params['perrow'] !== '' ) {
			$ig->setPerRow( $this->m_params['perrow'] );
		}

		if ( $this->m_params['widths'] !== '' ) {
			$ig->setWidths( $this->m_params['widths'] );
		}

		if ( $this->m_params['heights'] !== '' ) {
			$ig->setHeights( $this->m_params['heights'] );
		}

		$printReqLabels = array();

		foreach ( $results->getPrintRequests() as /* SMWPrintRequest */ $printReq ) {
			$printReqLabels[] = $printReq->getLabel();
		}

		if ( $this->m_params['imageproperty'] !== '' && in_array( $this->m_params['imageproperty'], $printReqLabels ) ) {
			$this->addImageProperties( $results, $ig, $this->m_params['imageproperty'], $this->m_params['captionproperty'] );
		}
		else {
			$this->addImagePages( $results, $ig );
		}

		return array( $ig->toHTML(), 'nowiki' => true, 'isHTML' => true );
	}
示例#10
0
 /**
  * @see SMWResultPrinter::getResultText
  *
  * @param $results SMWQueryResult
  * @param $fullParams array
  * @param $outputmode integer
  *
  * @return string
  */
 public function getResultText(SMWQueryResult $results, $outputmode)
 {
     $ig = new ImageGallery();
     $ig->setShowBytes(false);
     $ig->setShowFilename(false);
     $ig->setCaption($this->mIntro);
     // set caption to IQ header
     // No need for a special page to use the parser but for the "normal" page
     // view we have to ensure caption text is parsed correctly through the parser
     if (!$this->isSpecialPage()) {
         $ig->setParser($GLOBALS['wgParser']);
     }
     // Initialize
     static $statNr = 0;
     $html = '';
     $processing = '';
     if ($this->params['widget'] == 'carousel') {
         // Carousel widget
         $ig->setAttributes($this->getCarouselWidget());
     } elseif ($this->params['widget'] == 'slideshow') {
         // Slideshow widget
         $ig->setAttributes($this->getSlideshowWidget());
     } else {
         // Standard gallery attributes
         $attribs = array('id' => uniqid(), 'class' => $this->getImageOverlay());
         $ig->setAttributes($attribs);
     }
     // Only use redirects where the overlay option is not used and redirect
     // thumb images towards a different target
     if ($this->params['redirects'] !== '' && !$this->params['overlay']) {
         SMWOutputs::requireResource('ext.srf.gallery.redirect');
     }
     // For the carousel widget, the perrow option should not be set
     if ($this->params['perrow'] !== '' && $this->params['widget'] !== 'carousel') {
         $ig->setPerRow($this->params['perrow']);
     }
     if ($this->params['widths'] !== '') {
         $ig->setWidths($this->params['widths']);
     }
     if ($this->params['heights'] !== '') {
         $ig->setHeights($this->params['heights']);
     }
     $printReqLabels = array();
     $redirectType = '';
     /**
      * @var SMWPrintRequest $printReq
      */
     foreach ($results->getPrintRequests() as $printReq) {
         $printReqLabels[] = $printReq->getLabel();
         // Get redirect type
         if ($this->params['redirects'] === $printReq->getLabel()) {
             $redirectType = $printReq->getTypeID();
         }
     }
     if ($this->params['imageproperty'] !== '' && in_array($this->params['imageproperty'], $printReqLabels) || $this->params['redirects'] !== '' && in_array($this->params['redirects'], $printReqLabels)) {
         $this->addImageProperties($results, $ig, $this->params['imageproperty'], $this->params['captionproperty'], $this->params['redirects'], $outputmode);
     } else {
         $this->addImagePages($results, $ig);
     }
     // SRF Global settings
     SRFUtils::addGlobalJSVariables();
     // Display a processing image as long as the DOM is no ready
     if ($this->params['widget'] !== '') {
         $processing = SRFUtils::htmlProcessingElement();
     }
     // Beautify the class selector
     $class = $this->params['widget'] ? '-' . $this->params['widget'] . ' ' : '';
     $class = $this->params['redirects'] !== '' && $this->params['overlay'] === false ? $class . ' srf-redirect' . ' ' : $class;
     $class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class;
     // Separate content from result output
     if (!$ig->isEmpty()) {
         $attribs = array('class' => 'srf-gallery' . $class, 'align' => 'justify', 'data-redirect-type' => $redirectType);
         $html = Html::rawElement('div', $attribs, $processing . $ig->toHTML());
     }
     // If available, create a link that points to further results
     if ($this->linkFurtherResults($results)) {
         $html .= $this->getLink($results, SMW_OUTPUT_HTML)->getText(SMW_OUTPUT_HTML, $this->mLinker);
     }
     return array($html, 'nowiki' => true, 'isHTML' => true);
 }
 /**
  * Get the serialization for a SMWQueryResult object.
  *
  * @since 1.7
  *
  * @param SMWQueryResult $result
  *
  * @return array
  */
 public static function getSerializedQueryResult(QueryResult $queryResult)
 {
     $results = array();
     $printRequests = array();
     foreach ($queryResult->getPrintRequests() as $printRequest) {
         $printRequests[] = self::getSerializedPrintRequestFormat($printRequest);
     }
     /**
      * @var DIWikiPage $diWikiPage
      * @var PrintRequest $printRequest
      */
     foreach ($queryResult->getResults() as $diWikiPage) {
         if (!$diWikiPage->getTitle() instanceof Title) {
             continue;
         }
         $result = array('printouts' => array());
         foreach ($queryResult->getPrintRequests() as $printRequest) {
             $resultArray = new SMWResultArray($diWikiPage, $printRequest, $queryResult->getStore());
             if ($printRequest->getMode() === PrintRequest::PRINT_THIS) {
                 $dataItems = $resultArray->getContent();
                 $result += self::getSerialization(array_shift($dataItems), $printRequest);
             } elseif ($resultArray->getContent() !== array()) {
                 $values = array();
                 foreach ($resultArray->getContent() as $dataItem) {
                     $values[] = self::getSerialization($dataItem, $printRequest);
                 }
                 $result['printouts'][$printRequest->getLabel()] = $values;
             } else {
                 // For those objects that are empty return an empty array
                 // to keep the output consistent
                 $result['printouts'][$printRequest->getLabel()] = array();
             }
         }
         $results[$diWikiPage->getTitle()->getFullText()] = $result;
     }
     return array('printrequests' => $printRequests, 'results' => $results);
 }
示例#12
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;
 }
	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;
	}
示例#14
0
 /**
  * Compatibility layer for obsolete JSON format
  *
  * @since 1.8
  * @deprecated This method will be removed in 1.10
  *
  * @param SMWQueryResult $res
  * @param $outputmode integer
  *
  * @return string
  */
 private function getObsoleteJSON(SMWQueryResult $res, $outputmode)
 {
     wfDeprecated(__METHOD__, '1.8');
     $types = array('_wpg' => 'text', '_num' => 'number', '_dat' => 'date', '_geo' => 'text', '_str' => 'text');
     $itemstack = array();
     // contains Items for the items section
     $propertystack = array();
     // contains Properties for the property section
     // generate property section
     foreach ($res->getPrintRequests() as $pr) {
         if ($pr->getMode() != SMWPrintRequest::PRINT_THIS) {
             if (array_key_exists($pr->getTypeID(), $types)) {
                 $propertystack[] = '"' . str_replace(" ", "_", strtolower($pr->getLabel())) . '" : { "valueType": "' . $types[$pr->getTypeID()] . '" }';
             } else {
                 $propertystack[] = '"' . str_replace(" ", "_", strtolower($pr->getLabel())) . '" : { "valueType": "text" }';
             }
         }
     }
     $properties = "\"properties\": {\n\t\t" . implode(",\n\t\t", $propertystack) . "\n\t}";
     // generate items section
     while (($row = $res->getNext()) !== false) {
         $rowsubject = false;
         // the wiki page value that this row is about
         $valuestack = array();
         // contains Property-Value pairs to characterize an Item
         $addedLabel = false;
         foreach ($row as $field) {
             $pr = $field->getPrintRequest();
             if ($rowsubject === false && !$addedLabel) {
                 $valuestack[] = '"label": "' . $field->getResultSubject()->getTitle()->getFullText() . '"';
                 $addedLabel = true;
             }
             if ($pr->getMode() != SMWPrintRequest::PRINT_THIS) {
                 $values = array();
                 $jsonObject = array();
                 while (($dataValue = $field->getNextDataValue()) !== false) {
                     switch ($dataValue->getTypeID()) {
                         case '_geo':
                             $jsonObject[] = $dataValue->getDataItem()->getCoordinateSet();
                             $values[] = FormatJson::encode($dataValue->getDataItem()->getCoordinateSet());
                             break;
                         case '_num':
                             $jsonObject[] = $dataValue->getDataItem()->getNumber();
                             break;
                         case '_dat':
                             $jsonObject[] = $dataValue->getYear() . '-' . str_pad($dataValue->getMonth(), 2, '0', STR_PAD_LEFT) . '-' . str_pad($dataValue->getDay(), 2, '0', STR_PAD_LEFT) . ' ' . $dataValue->getTimeString();
                             break;
                         default:
                             $jsonObject[] = $dataValue->getShortText($outputmode, null);
                     }
                 }
                 if (!is_array($jsonObject) || count($jsonObject) > 0) {
                     $valuestack[] = '"' . str_replace(' ', '_', strtolower($pr->getLabel())) . '": ' . FormatJson::encode($jsonObject) . '';
                 }
             }
         }
         if ($rowsubject !== false) {
             // stuff in the page URI and some category data
             $valuestack[] = '"uri" : "' . $wgServer . $wgScriptPath . '/index.php?title=' . $rowsubject->getPrefixedText() . '"';
             $page_cats = smwfGetStore()->getPropertyValues($rowsubject, new SMWDIProperty('_INST'));
             // TODO: set limit to 1 here
             if (count($page_cats) > 0) {
                 $valuestack[] = '"type" : "' . reset($page_cats)->getShortHTMLText() . '"';
             }
         }
         // create property list of item
         $itemstack[] = "\t{\n\t\t\t" . implode(",\n\t\t\t", $valuestack) . "\n\t\t}";
     }
     $items = "\"items\": [\n\t" . implode(",\n\t", $itemstack) . "\n\t]";
     return "{\n\t" . $properties . ",\n\t" . $items . "\n}";
 }
示例#15
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     global $smwgIQRunningNumber, $wgSitename, $wgServer, $smwgRSSEnabled, $wgRequest;
     $result = '';
     if ($outputmode == SMW_OUTPUT_FILE) {
         // make RSS feed
         if (!$smwgRSSEnabled) {
             return '';
         }
         if ($this->m_title === '') {
             $this->m_title = $wgSitename;
         }
         if ($this->m_description === '') {
             $this->m_description = wfMsg('smw_rss_description', $wgSitename);
         }
         // cast printouts into "items"
         $items = array();
         $row = $res->getNext();
         while ($row !== false) {
             $creators = array();
             $dates = array();
             $wikipage = $row[0]->getNextDataValue();
             // get the object
             foreach ($row as $field) {
                 // for now we ignore everything but creator and date, later we may
                 // add more things like geolocs, categories, and even a generic
                 // mechanism to add whatever you want :)
                 $req = $field->getPrintRequest();
                 if (strtolower($req->getLabel()) == 'creator') {
                     while ($entry = $field->getNextDataValue()) {
                         $creators[] = $entry->getShortWikiText();
                     }
                 } elseif (strtolower($req->getLabel()) == 'date' && $req->getTypeID() == '_dat') {
                     while ($entry = $field->getNextDataValue()) {
                         $dates[] = $entry->getXMLSchemaDate();
                     }
                 }
             }
             if ($wikipage instanceof SMWWikiPageValue) {
                 // this should rarely fail, but better be carful
                 ///TODO: It would be more elegant to have type chekcs initially
                 $items[] = new SMWRSSItem($wikipage->getTitle(), $creators, $dates);
             }
             $row = $res->getNext();
         }
         $result .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
         $result .= "<rdf:RDF\n";
         $result .= "\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n";
         $result .= "\txmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n";
         $result .= "\txmlns:admin=\"http://webns.net/mvcb/\"\n";
         $result .= "\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n";
         $result .= "\txmlns=\"http://purl.org/rss/1.0/\">\n";
         $result .= "\t<channel rdf:about=\"" . str_replace('&', '&amp;', $wgRequest->getFullRequestURL()) . "\">\n";
         $result .= "\t\t<admin:generatorAgent rdf:resource=\"http://semantic-mediawiki.org/wiki/Special:URIResolver/Semantic_MediaWiki\"/>\n";
         $result .= "\t\t<title>" . smwfXMLContentEncode($this->m_title) . "</title>\n";
         $result .= "\t\t<link>{$wgServer}</link>\n";
         $result .= "\t\t<description>" . smwfXMLContentEncode($this->m_description) . "</description>\n";
         if (count($items) > 0) {
             $result .= "\t\t<items>\n";
             $result .= "\t\t\t<rdf:Seq>\n";
             foreach ($items as $item) {
                 $result .= "\t\t\t\t<rdf:li rdf:resource=\"" . $item->uri() . "\"/>\n";
             }
             $result .= "\t\t\t</rdf:Seq>\n";
             $result .= "\t\t</items>\n";
         }
         $result .= "\t</channel>\n";
         foreach ($items as $item) {
             $result .= $item->text();
         }
         $result .= '</rdf:RDF>';
     } else {
         // just make link to feed
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('smw_rss_link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('rss', 'format');
         if ($this->m_title !== '') {
             $link->setParameter($this->m_title, 'title');
         }
         if ($this->m_description !== '') {
             $link->setParameter($this->m_description, 'description');
         }
         if (array_key_exists('limit', $this->m_params)) {
             $link->setParameter($this->m_params['limit'], 'limit');
         } else {
             // use a reasonable deafult limit (10 is suggested by RSS)
             $link->setParameter(10, 'limit');
         }
         foreach ($res->getPrintRequests() as $printout) {
             // overwrite given "sort" parameter with printout of label "date"
             if ($printout->getMode() == SMWPrintRequest::PRINT_PROP && strtolower($printout->getLabel()) == "date" && $printout->getTypeID() == "_dat") {
                 $link->setParameter($printout->getData()->getWikiValue(), 'sort');
             }
         }
         $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
         SMWOutputs::requireHeadItem('rss' . $smwgIQRunningNumber, '<link rel="alternate" type="application/rss+xml" title="' . $this->m_title . '" href="' . $link->getURL() . '" />');
     }
     return $result;
 }
示例#16
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     global $smwgIQRunningNumber, $wgScriptPath, $wgGoogleMapsKey, $srfgScriptPath;
     if (defined('MW_SUPPORTS_RESOURCE_MODULES')) {
         SMWOutputs::requireHeadItem('exhibit-compat', Html::linkedScript("{$wgScriptPath}/common/wikibits.js"));
     }
     // //////////////////////////////
     // ///////REMOTE STUFF///////////
     // //////////////////////////////
     $remote = false;
     // in case the remote parameter is set, a link to the JSON export of the remote wiki is included in the header as data source for Exhibit
     // this section creates the link
     if (array_key_exists('remote', $this->m_params) && srfgExhibitRemote == true) {
         $remote = true;
         // fetch interwiki link
         $dbr =& wfGetDB(DB_SLAVE);
         $cl = $dbr->tableName('interwiki');
         $dbres = $dbr->select($cl, 'iw_url', "iw_prefix='" . $this->m_params['remote'] . "'", __METHOD__, array());
         $row = $dbr->fetchRow($dbres);
         $extlinkpattern = $row[iw_url];
         $dbr->freeResult($dbres);
         $newheader = '<link rel="exhibit/data" type="application/jsonp" href="';
         $link = $res->getQueryLink('JSON Link');
         $link->setParameter('json', 'format');
         if (array_key_exists('callback', $this->m_params)) {
             // check if a special name for the callback function is set, if not stick with 'callback'
             $callbackfunc = $this->m_params['callback'];
         } else {
             $callbackfunc = 'callback';
         }
         if (array_key_exists('limit', $this->m_params)) {
             $link->setParameter($this->m_params['limit'], 'limit');
         }
         $link->setParameter($callbackfunc, 'callback');
         $link = $link->getText(2, $this->mLinker);
         list($link, $trash) = explode('|', $link);
         $link = str_replace('[[:', '', $link);
         $newheader .= str_replace('$1', $link, $extlinkpattern);
         $newheader .= '" ex:jsonp-callback="' . $callbackfunc . '"';
         $newheader .= '/>';
         SMWOutputs::requireHeadItem('REMOTE', $newheader);
     }
     // the following variables indicate the use of special views
     // the variable's values define the way Exhibit is called
     $timeline = false;
     $map = false;
     /*The javascript file adopted from Wibbit uses a bunch of javascript variables in the header to store information about the Exhibit markup.
     	 The following code sequence creates these variables*/
     // prepare sources (the sources holds information about the table which contains the information)
     $colstack = array();
     foreach ($res->getPrintRequests() as $pr) {
         $colstack[] = $this->encodePropertyName($pr->getLabel()) . ':' . (array_key_exists($pr->getTypeID(), $this->m_types) ? $this->m_types[$pr->getTypeID()] : 'text');
     }
     array_shift($colstack);
     array_unshift($colstack, 'label');
     if (SRFExhibit::$exhibitRunningNumber == 0) {
         $sourcesrc = "var ex_sources = { source" . ($smwgIQRunningNumber - 1) . ": { id:  'querytable" . $smwgIQRunningNumber . "' , columns: '" . implode(',', $colstack) . "'.split(','), hideTable: '1', type: 'Item', label: 'Item', pluralLabel: 'Items' } };";
     } else {
         $sourcesrc = "sources.source" . $smwgIQRunningNumber . " =  { id:  'querytable" . $smwgIQRunningNumber . "' , columns: '" . implode(',', $colstack) . "'.split(','), hideTable: '1', type: 'Item', label: 'Item', pluralLabel: 'Items' };";
     }
     $sourcesrc = "<script type=\"text/javascript\">" . $sourcesrc . "</script>";
     // prepare facets
     $facetcounter = 0;
     if (array_key_exists('facets', $this->m_params)) {
         $facets = explode(',', $this->m_params['facets']);
         $facetstack = array();
         $params = array('height');
         $facparams = array();
         foreach ($params as $param) {
             if (array_key_exists($param, $this->m_params)) {
                 $facparams[] = 'ex:' . $param . '="' . $this->encodePropertyName($this->m_params[$param]) . '" ';
             }
         }
         foreach ($facets as $facet) {
             $facet = trim($facet);
             $fieldcounter = 0;
             if (strtolower($facet) == "search") {
                 // special facet (text search)
                 $facetstack[] = ' facet' . $facetcounter++ . ': { position : "right", innerHTML: \'ex:role="facet" ex:showMissing="false" ex:facetClass="TextSearch" ex:facetLabel="' . $facet . '"\'}';
             } else {
                 // usual facet
                 foreach ($res->getPrintRequests() as $pr) {
                     if ($this->encodePropertyName($pr->getLabel()) == $this->encodePropertyName($facet)) {
                         switch ($pr->getTypeID()) {
                             case '_num':
                                 $facetstack[] = ' facet' . $facetcounter++ . ': { position : "right", innerHTML: \'ex:role="facet" ex:showMissing="false" ex:expression=".' . $this->encodePropertyName($facet) . '" ex:facetLabel="' . $facet . '" ex:facetClass="Slider"\'}';
                                 break;
                             default:
                                 $facetstack[] = ' facet' . $facetcounter++ . ': { position : "right", innerHTML: \'ex:role="facet" ex:showMissing="false" ' . implode(" ", $facparams) . ' ex:expression=".' . $this->encodePropertyName($facet) . '" ex:facetLabel="' . $facet . '"\'}';
                         }
                     }
                 }
             }
             $fieldcounter++;
         }
         $facetstring = implode(',', $facetstack);
     } else {
         $facetstring = '';
     }
     $facetsrc = "var ex_facets = {" . $facetstring . " };";
     // prepare views
     $stylesrc = '';
     $viewcounter = 0;
     if (array_key_exists('views', $this->m_params)) {
         $views = explode(',', $this->m_params['views']);
     } else {
         $views[] = 'tiles';
     }
     foreach ($views as $view) {
         switch (trim($view)) {
             case 'tabular':
                 // table view (the columns are automatically defined by the selected properties)
                 $thstack = array();
                 foreach ($res->getPrintRequests() as $pr) {
                     $thstack[] = "." . $this->encodePropertyName($pr->getLabel());
                 }
                 array_shift($thstack);
                 array_unshift($thstack, '.label');
                 $stylesrc = 'var myStyler = function(table, database) {table.className=\'smwtable\';};';
                 // assign SMWtable CSS to Exhibit tabular view
                 $viewstack[] = 'ex:role=\'view\' ex:viewClass=\'Tabular\' ex:showSummary=\'false\' ex:sortAscending=\'true\' ex:tableStyler=\'myStyler\'  ex:label=\'Table\' ex:columns=\'' . implode(',', $thstack) . '\' ex:sortAscending=\'false\'';
                 break;
             case 'timeline':
                 // timeline view
                 $timeline = true;
                 $exparams = array('start', 'end', 'proxy', 'colorkey');
                 // parameters expecting an Exhibit graph expression
                 $usparams = array('timelineheight', 'topbandheight', 'bottombandheight', 'bottombandunit', 'topbandunit');
                 // parametes expecting a textual or numeric value
                 $tlparams = array();
                 foreach ($exparams as $param) {
                     if (array_key_exists($param, $this->m_params)) {
                         $tlparams[] = 'ex:' . $param . '=\'.' . $this->encodePropertyName($this->m_params[$param]) . '\' ';
                     }
                 }
                 foreach ($usparams as $param) {
                     if (array_key_exists($param, $this->m_params)) {
                         $tlparams[] = 'ex:' . $param . '=\'' . $this->encodePropertyName($this->m_params[$param]) . '\' ';
                     }
                 }
                 if (!array_key_exists('start', $this->m_params)) {
                     // find out if a start and/or end date is specified
                     $dates = array();
                     foreach ($res->getPrintRequests() as $pr) {
                         if ($pr->getTypeID() == '_dat') {
                             $dates[] = $pr;
                             if (sizeof($dates) > 2) {
                                 break;
                             }
                         }
                     }
                     if (sizeof($dates) == 1) {
                         $tlparams[] = 'ex:start=\'.' . $this->encodePropertyName($dates[0]->getLabel()) . '\' ';
                     } elseif (sizeof($dates) == 2) {
                         $tlparams[] = 'ex:start=\'.' . $this->encodePropertyName($dates[0]->getLabel()) . '\' ';
                         $tlparams[] = 'ex:end=\'.' . $this->encodePropertyName($dates[1]->getLabel()) . '\' ';
                     }
                 }
                 $viewstack[] = 'ex:role=\'view\' ex:viewClass=\'Timeline\' ex:label=\'Timeline\' ex:showSummary=\'false\' ' . implode(" ", $tlparams);
                 break;
             case 'map':
                 // map view
                 if (isset($wgGoogleMapsKey)) {
                     $map = true;
                     $exparams = array('latlng', 'colorkey');
                     $usparams = array('type', 'center', 'zoom', 'size', 'scalecontrol', 'overviewcontrol', 'mapheight');
                     $mapparams = array();
                     foreach ($exparams as $param) {
                         if (array_key_exists($param, $this->m_params)) {
                             $mapparams[] = 'ex:' . $param . '=\'.' . $this->encodePropertyName($this->m_params[$param]) . '\' ';
                         }
                     }
                     foreach ($usparams as $param) {
                         if (array_key_exists($param, $this->m_params)) {
                             $mapparams[] = 'ex:' . $param . '=\'' . $this->encodePropertyName($this->m_params[$param]) . '\' ';
                         }
                     }
                     if (!array_key_exists('start', $this->m_params) && !array_key_exists('end', $this->m_params)) {
                         // find out if a geographic coordinate is available
                         foreach ($res->getPrintRequests() as $pr) {
                             if ($pr->getTypeID() == '_geo') {
                                 $mapparams[] = 'ex:latlng=\'.' . $this->encodePropertyName($pr->getLabel()) . '\' ';
                                 break;
                             }
                         }
                     }
                     $viewstack[] .= 'ex:role=\'view\' ex:viewClass=\'Map\' ex:showSummary=\'false\' ex:label=\'Map\' ' . implode(" ", $mapparams);
                 }
                 break;
             default:
             case 'tiles':
                 // tile view
                 $sortstring = '';
                 if (array_key_exists('sort', $this->m_params)) {
                     $sortfields = explode(",", $this->m_params['sort']);
                     foreach ($sortfields as $field) {
                         $sortkeys[] = "." . $this->encodePropertyName(trim($field));
                     }
                     $sortstring = 'ex:orders=\'' . implode(",", $sortkeys) . '\' ';
                     if (array_key_exists('order', $this->m_params)) {
                         $sortstring .= ' ex:directions=\'' . $this->encodePropertyName($this->m_params['order']) . '\'';
                     }
                     if (array_key_exists('grouped', $this->m_params)) {
                         $sortstring .= ' ex:grouped=\'' . $this->encodePropertyName($this->m_params['grouped']) . '\'';
                     }
                 }
                 $viewstack[] = 'ex:role=\'view\' ex:showSummary=\'false\' ' . $sortstring;
                 break;
         }
     }
     $viewsrc = 'var ex_views = "' . implode("/", $viewstack) . '".split(\'/\');;';
     // prepare automatic lenses
     global $wgParser;
     $lenscounter = 0;
     $linkcounter = 0;
     $imagecounter = 0;
     if (array_key_exists('lens', $this->m_params)) {
         // a customized lens is specified via the lens parameter within the query
         $lenstitle = Title::newFromText("Template:" . $this->m_params['lens']);
         $lensarticle = new Article($lenstitle);
         $lenswikitext = $lensarticle->getContent();
         if (preg_match_all("/[\\[][\\[][Ii][m][a][g][e][:][{][{][{][1-9A-z\\-[:space:]]*[}][}][}][\\]][\\]]/u", $lenswikitext, $matches)) {
             foreach ($matches as $match) {
                 foreach ($match as $value) {
                     $strippedvalue = trim(substr($value, 8), "[[{}]]");
                     $lenswikitext = str_replace($value, '<div class="inlines" id="imagecontent' . $imagecounter . '">' . $this->encodePropertyName(strtolower(str_replace("\n", "", $strippedvalue))) . '</div>', $lenswikitext);
                     $imagecounter++;
                 }
             }
         }
         if (preg_match_all("/[\\[][\\[][{][{][{][1-9A-z\\-[:space:]]*[}][}][}][\\]][\\]]/u", $lenswikitext, $matches)) {
             foreach ($matches as $match) {
                 foreach ($match as $value) {
                     $strippedvalue = trim($value, "[[{}]]");
                     $lenswikitext = str_replace($value, '<div class="inlines" id="linkcontent' . $linkcounter . '">' . $this->encodePropertyName(strtolower(str_replace("\n", "", $strippedvalue))) . '</div>', $lenswikitext);
                     $linkcounter++;
                 }
             }
         }
         if (preg_match_all("/[{][{][{][1-9A-z\\:\\|\\/\\=\\-[:space:]]*[}][}][}]/u", $lenswikitext, $matches)) {
             foreach ($matches as $match) {
                 foreach ($match as $value) {
                     $strippedvalue = trim($value, "{}");
                     $lenswikitext = str_replace($value, '<div class="inlines" id="lenscontent' . $lenscounter . '">' . $this->encodePropertyName(strtolower(str_replace("\n", "", $strippedvalue))) . '</div>', $lenswikitext);
                     $lenscounter++;
                 }
             }
         }
         $lenshtml = $wgParser->internalParse($lenswikitext);
         // $wgParser->parse($lenswikitext, $lenstitle, new ParserOptions(), true, true)->getText();
         $lenssrc = "var ex_lens = '" . str_replace("\n", "", $lenshtml) . "';ex_lenscounter =" . $lenscounter . ";ex_linkcounter=" . $linkcounter . ";ex_imagecounter=" . $imagecounter . ";";
     } else {
         // generic lens (creates links to further content (property-pages, pages about values)
         foreach ($res->getPrintRequests() as $pr) {
             if ($remote) {
                 $wikiurl = str_replace("\$1", "", $extlinkpattern);
             } else {
                 $wikiurl = $wgScriptPath . "/index.php?title=";
             }
             if ($pr->getTypeID() == '_wpg') {
                 $prefix = '';
                 if ($pr->getLabel() == 'Category') {
                     $prefix = "Category:";
                 }
                 $lensstack[] = '<tr ex:if-exists=".' . $this->encodePropertyName($pr->getLabel()) . '"><td width="20%">' . $pr->getText(0, $this->mLinker) . '</td><td width="80%" ex:content=".' . $this->encodePropertyName($pr->getLabel()) . '"><a ex:href-subcontent="' . $wikiurl . $prefix . '{{urlencval(value)}}"><div ex:content="value" class="name"></div></a></td></tr>';
             } else {
                 $lensstack[] = '<tr ex:if-exists=".' . $this->encodePropertyName($pr->getLabel()) . '"><td width="20%">' . $pr->getText(0, $this->mLinker) . '</td><td width="80%"><div ex:content=".' . $this->encodePropertyName($pr->getLabel()) . '" class="name"></div></td></tr>';
             }
         }
         array_shift($lensstack);
         $lenssrc = 'var ex_lens = \'<table width=100% cellpadding=3><tr><th class="head" align=left bgcolor="#DDDDDD"><a ex:href-subcontent="' . $wikiurl . $this->determineNamespace(clone $res) . '{{urlenc(.label)}}" class="linkhead"><div ex:content=".label" class="name"></div></a></th></tr></table><table width="100%" cellpadding=3>' . implode("", $lensstack) . '</table>\'; ex_lenscounter = 0; ex_linkcounter=0; ex_imagecounter=0;';
     }
     if ($remote) {
         $varremote = 'true';
     } else {
         $varremote = 'false';
     }
     // Handling special formats like date
     $formatssrc = 'var formats =\'\'';
     if (array_key_exists('date', $this->m_params)) {
         $formatssrc = 'var formats = \'ex:formats="date { mode:' . $this->m_params['date'] . '; show:date }"\';';
     }
     // create a URL pointing to the corresponding JSON feed
     $label = '';
     $JSONlink = $res->getQueryLink($label);
     if ($this->getSearchLabel(SMW_OUTPUT_WIKI) != '') {
         // used as a file name
         $link->setParameter($this->getSearchLabel(SMW_OUTPUT_WIKI), 'searchlabel');
     }
     if (array_key_exists('limit', $this->m_params)) {
         $JSONlink->setParameter(htmlspecialchars($this->m_params['limit']), 'limit');
     }
     $JSONlink->setParameter('json', 'format');
     $stringtoedit = explode("|", $JSONlink->getText($outputmode, $this->mLinker));
     $stringtoedit = substr($stringtoedit[0], 3);
     $JSONlinksrc = "var JSONlink = '" . $stringtoedit . "';";
     // create script header with variables containing the Exhibit markup
     $headervars = "<script type='text/javascript'>\n\t\t\t" . $facetsrc . "\n\t\t\t" . $viewsrc . "\n\t\t\t" . $lenssrc . "\n\t\t\t" . $stylesrc . "\n\t\t\t" . $formatssrc . "\n\t\t\t" . $JSONlinksrc . "\n\t\t\t var remote=" . $varremote . ";</script>";
     // To run Exhibit some links to the scripts of the API need to be included in the header
     $ExhibitScriptSrc1 = '<script type="text/javascript" src="' . $srfgScriptPath . '/Exhibit/exhibit/exhibit-api.js?autoCreate=false&safe=true&bundle=false';
     if ($timeline) {
         $ExhibitScriptSrc1 .= '&views=timeline';
     }
     if ($map) {
         $ExhibitScriptSrc1 .= '&gmapkey=' . $wgGoogleMapsKey;
     }
     $ExhibitScriptSrc1 .= '"></script>';
     $ExhibitScriptSrc2 = '<script type="text/javascript" src="' . $srfgScriptPath . '/Exhibit/SRF_Exhibit.js"></script>';
     $CSSSrc = '<link rel="stylesheet" type="text/css" href="' . $srfgScriptPath . '/Exhibit/SRF_Exhibit.css"></link>';
     SMWOutputs::requireHeadItem('CSS', $CSSSrc);
     // include CSS
     SMWOutputs::requireHeadItem('EXHIBIT1', $ExhibitScriptSrc1);
     // include Exhibit API
     SMWOutputs::requireHeadItem('EXHIBIT2', $ExhibitScriptSrc2);
     // includes javascript overwriting the Exhibit start-up functions
     SMWOutputs::requireHeadItem('SOURCES' . $smwgIQRunningNumber, $sourcesrc);
     // include sources variable
     SMWOutputs::requireHeadItem('VIEWSFACETS', $headervars);
     // include views and facets variable
     if (!$remote) {
         // print input table
         // print header
         if ('broadtable' == $this->mFormat) {
             $widthpara = ' width="100%"';
         } else {
             $widthpara = '';
         }
         $result = "<table style=\"display:none\" class=\"smwtable\" id=\"querytable" . $smwgIQRunningNumber . "\">\n";
         if ($this->mShowHeaders) {
             // building headers
             $result .= "\t<tr>\n";
             foreach ($res->getPrintRequests() as $pr) {
                 if ($pr->getText($outputmode, $this->getLinker(0)) == '') {
                     $headerlabel = "Name";
                 } else {
                     $headerlabel = $pr->getText($outputmode, $this->getLinker(0));
                 }
                 $result .= "\t\t<th>" . $headerlabel . "</th>\n";
             }
             $result .= "\t</tr>\n";
         }
         // print all result rows
         while ($row = $res->getNext()) {
             $result .= "\t<tr>\n";
             foreach ($row as $field) {
                 $result .= "\t\t<td>";
                 $textstack = array();
                 while (($object = $field->getNextDataValue()) !== false) {
                     switch ($object->getTypeID()) {
                         case '_wpg':
                             $textstack[] = $object->getLongText($outputmode, $this->getLinker(0));
                             break;
                         case '_geo':
                             $c = $object->getDBKeys();
                             $textstack[] = $c[0] . "," . $c[1];
                             break;
                         case '_num':
                             if (method_exists($object, 'getValueKey')) {
                                 $textstack[] = $object->getValueKey($outputmode, $this->getLinker(0));
                             } else {
                                 $textstack[] = $object->getNumericValue($outputmode, $this->getLinker(0));
                             }
                             break;
                         case '_dat':
                             $textstack[] = $object->getYear() . "-" . str_pad($object->getMonth(), 2, '0', STR_PAD_LEFT) . "-" . str_pad($object->getDay(), 2, '0', STR_PAD_LEFT) . " " . $object->getTimeString();
                             break;
                         case '_ema':
                             $textstack[] = $object->getShortWikiText($this->getLinker(0));
                             break;
                         case '_tel':
                         case '_anu':
                         case '_uri':
                             $textstack[] = $object->getWikiValue();
                             break;
                         case '__sin':
                             $tmp = $object->getShortText($outputmode, null);
                             if (strpos($tmp, ":")) {
                                 $tmp = explode(":", $tmp, 2);
                                 $tmp = $tmp[1];
                             }
                             $textstack[] = $tmp;
                             break;
                         case '_txt':
                         case '_cod':
                         case '_str':
                             $textstack[] = $object->getWikiValue();
                             break;
                         default:
                             $textstack[] = $object->getLongHTMLText($this->getLinker(0));
                     }
                 }
                 if ($textstack != null) {
                     $result .= implode(';', $textstack) . "</td>\n";
                 } else {
                     $result .= "</td>\n";
                 }
             }
             $result .= "\t</tr>\n";
         }
         $result .= "</table>\n";
     }
     if (SRFExhibit::$exhibitRunningNumber == 0) {
         $result .= "<div id=\"exhibitLocation\"></div>";
     }
     // print placeholder (just print it one time)
     $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
     // yes, our code can be viewed as HTML if requested, no more parsing needed
     SRFExhibit::$exhibitRunningNumber++;
     return $result;
 }
示例#17
0
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     global $wgServer, $wgScriptPath;
     if ($outputmode == SMW_OUTPUT_FILE) {
         // create detached JSON file
         $itemstack = array();
         // contains Items for the items section
         $propertystack = array();
         // contains Properties for the property section
         // generate property section
         foreach ($res->getPrintRequests() as $pr) {
             if ($pr->getMode() != SMWPrintRequest::PRINT_THIS) {
                 if (array_key_exists($pr->getTypeID(), $this->types)) {
                     $propertystack[] = '"' . str_replace(" ", "_", strtolower($pr->getLabel())) . '" : { "valueType": "' . $this->types[$pr->getTypeID()] . '" }';
                 } else {
                     $propertystack[] = '"' . str_replace(" ", "_", strtolower($pr->getLabel())) . '" : { "valueType": "text" }';
                 }
             }
         }
         $properties = "\"properties\": {\n\t\t" . implode(",\n\t\t", $propertystack) . "\n\t}";
         // generate items section
         while (($row = $res->getNext()) !== false) {
             $rowsubject = false;
             // the wiki page value that this row is about
             $valuestack = array();
             // contains Property-Value pairs to characterize an Item
             $addedLabel = false;
             foreach ($row as $field) {
                 $pr = $field->getPrintRequest();
                 if ($rowsubject === false && !$addedLabel) {
                     $valuestack[] = '"label": "' . $field->getResultSubject()->getTitle()->getFullText() . '"';
                     $addedLabel = true;
                 }
                 if ($pr->getMode() != SMWPrintRequest::PRINT_THIS) {
                     $values = array();
                     $jsonObject = array();
                     while (($dataValue = $field->getNextDataValue()) !== false) {
                         switch ($dataValue->getTypeID()) {
                             case '_geo':
                                 $jsonObject[] = $dataValue->getDataItem()->getCoordinateSet();
                                 $values[] = FormatJson::encode($dataValue->getDataItem()->getCoordinateSet());
                                 break;
                             case '_num':
                                 $jsonObject[] = $dataValue->getDataItem()->getNumber();
                                 break;
                             case '_dat':
                                 $jsonObject[] = $dataValue->getYear() . '-' . str_pad($dataValue->getMonth(), 2, '0', STR_PAD_LEFT) . '-' . str_pad($dataValue->getDay(), 2, '0', STR_PAD_LEFT) . ' ' . $dataValue->getTimeString();
                                 break;
                             default:
                                 $jsonObject[] = $dataValue->getShortText($outputmode, null);
                         }
                     }
                     if (!is_array($jsonObject) || count($jsonObject) > 0) {
                         $valuestack[] = '"' . str_replace(' ', '_', strtolower($pr->getLabel())) . '": ' . FormatJson::encode($jsonObject) . '';
                     }
                 }
             }
             if ($rowsubject !== false) {
                 // stuff in the page URI and some category data
                 $valuestack[] = '"uri" : "' . $wgServer . $wgScriptPath . '/index.php?title=' . $rowsubject->getPrefixedText() . '"';
                 $page_cats = smwfGetStore()->getPropertyValues($rowsubject, new SMWDIProperty('_INST'));
                 // TODO: set limit to 1 here
                 if (count($page_cats) > 0) {
                     $valuestack[] = '"type" : "' . reset($page_cats)->getShortHTMLText() . '"';
                 }
             }
             // create property list of item
             $itemstack[] = "\t{\n\t\t\t" . implode(",\n\t\t\t", $valuestack) . "\n\t\t}";
         }
         $items = "\"items\": [\n\t" . implode(",\n\t", $itemstack) . "\n\t]";
         // check whether a callback function is required
         if (array_key_exists('callback', $this->params)) {
             $result = htmlspecialchars($this->params['callback']) . "({\n\t" . $properties . ",\n\t" . $items . "\n})";
         } else {
             $result = "{\n\t" . $properties . ",\n\t" . $items . "\n}";
         }
     } else {
         // just create a link that points to the JSON file
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('smw_json_link');
         }
         $link = $res->getQueryLink($label);
         if (array_key_exists('callback', $this->params)) {
             $link->setParameter(htmlspecialchars($this->params['callback']), 'callback');
         }
         if ($this->getSearchLabel(SMW_OUTPUT_WIKI) !== '') {
             // used as a file name
             $link->setParameter($this->getSearchLabel(SMW_OUTPUT_WIKI), 'searchlabel');
         }
         if (array_key_exists('limit', $this->params)) {
             $link->setParameter(htmlspecialchars($this->params['limit']), 'limit');
         }
         $link->setParameter('json', 'format');
         $result = $link->getText($outputmode, $this->mLinker);
         // yes, our code can be viewed as HTML if requested, no more parsing needed
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
     }
     return $result;
 }
	protected function getResultText( SMWQueryResult $res, $outputmode ) {
		global $smwgIQRunningNumber, $wgUploadDirectory, $wgUploadPath, $wgTitle, $wgScriptPath, $srfgPloticusPath, $srfgEnvSettings;

		$this->isHTML = true;
		$this->outputmode = SMW_OUTPUT_HTML;

		// check parameters
		$validformats = array( 'svg', 'svgz', 'swf', 'png', 'gif', 'jpeg', 'drawdump', 'drawdumpa', 'eps', 'ps' );
		if ( !in_array( $this->m_imageformat, $validformats ) )
		    return ( '<p classid="srfperror">ERROR: ' . $this->m_imageformat . ' is not a supported imageformat.<br />Valid imageformats are: ' .
			    implode( ', ', $validformats ) . '</p>' );

		if ( empty( $this->m_ploticusparams ) )
		    return ( '<p classid="srfperror">ERROR: <em>ploticusparams</em> required.</p>' );

		if ( empty( $srfgPloticusPath ) )
		    return ( '<p classid="srfperror">ERROR: Set $srfgPloticusPath in LocalSettings.php (e.g. $srfgPloticusPath=/usr/bin/pl).</p>' );

		if ( !file_exists( $srfgPloticusPath ) )
		    return ( '<p classid=""srfperror">ERROR: Could not find ploticus in <em>' . $srfgPloticusPath . '</em></p>' );

		// remove potentially dangerous keywords
		// this is an extended check, JUST IN CASE, even though we're invoking ploticus with the noshell security parameter
		// we also remove line endings - this is done for readability so the user can specify the prefab
		// params over several lines rather than one long command line
		$searches = array( '/`/m', '/system/im', '/shell/im', "/\s*?\n/m" );
		$replaces = array( '', '', '', ' ' );
		$sanitized_ploticusparams = preg_replace( $searches, $replaces, $this->m_ploticusparams );

		// Create the ploticus data directory if it doesn't exist
		// create sharded directory structure for data partitioning/scalability purposes
		$ploticusDir = $wgUploadDirectory . '/ploticus/';
		if ( !is_dir( $ploticusDir ) ) {
			mkdir( $ploticusDir, 0777 );
			for ( $idx = 0; $idx < 16; $idx++ )
				mkdir( $ploticusDir . dechex( $idx ), 0777 );
		}

		// create result csv file that we pass on to ploticus
		$tmpFile = tempnam( $ploticusDir, 'srf-' );
		if ( ( $fhandle = fopen( $tmpFile, 'w' ) ) === false )
			return ( '<p class="srfperror">ERROR: Cannot create data file - ' . $tmpFile . '.  Check permissions.</p>' );

		if ( $this->mShowHeaders ) {
			// create the header row
			$header_row = array();
			foreach ( $res->getPrintRequests() as $pr ) {
				$headertext = $pr->getLabel();
				$header_row[] = strtr( $headertext, " ,", "_|" ); // ploticus cant handle embedded spaces/commas for legends
			}
			if ( empty( $header_row[0] ) )
				$header_row[0] = "Article";
			fputcsv( $fhandle, $header_row );
		}
		// write the results
		while ( $row = $res->getNext() ) {
			 $row_items = array();
			 foreach ( $row as $field ) {
				 $growing = array();
				 
				 while ( ( $object = $field->getNextDataValue() ) !== false ) {
					 $text = Sanitizer::decodeCharReferences( $object->getXSDValue() );
					 // decode: CSV knows nothing of possible HTML entities
					 $growing[] = $text;
				 }
				 $row_items[] = implode( ',', $growing );
			 }
			 fputcsv( $fhandle, $row_items );
		}
		fclose( $fhandle );

		// we create a hash based on params
		// this is a great way to see if the params and/or the query result has changed
		$hashname = hash( 'md5', $wgTitle->getPrefixedDBkey() . $smwgIQRunningNumber . implode( ',', $this->m_params ) );
		if ( $this->m_liveupdating ) {
		    // only include contents of result csv in hash when liveupdating is on
		    // in this way, doing file_exists check against hash filename will fail when query result has changed
		    $hashname .= hash_file( 'md5', $tmpFile );
		}

		$orighash = $hashname;
		// modify hashname so files created with it will be stored in shard dir based on first char of hash
		$hashname = substr( $hashname, 0, 1 ) . '/' . $hashname;
		$dataFile = $ploticusDir . $hashname . '.csv';
		@unlink( $dataFile );
		@rename( $tmpFile, $dataFile );
		$dataURL = $wgUploadPath . '/ploticus/' . $hashname . '.csv';
		$srficonPath = $wgScriptPath . '/extensions/SemanticResultFormats/Ploticus/icons/';

		$graphFile = $ploticusDir . $hashname . '.' . $this->m_imageformat;
		$graphURL = $wgUploadPath . '/ploticus/' . $hashname . '.' . $this->m_imageformat;
		$errorFile = $ploticusDir . $hashname . '.err';
		$errorURL = $wgUploadPath . '/ploticus/' . $hashname . '.err';
		$mapFile = $ploticusDir . $hashname . '.map';
		$mapURL = $wgUploadPath . '/ploticus/' . $hashname . '.map';

		if ( ( $this->m_updatefrequency > 0 ) && file_exists( $graphFile ) ) {
			// get time graph was last generated. Also check to see if the
			// generated plot has expired per the updatefrequency and needs to be redrawn
		    $graphLastGenerated = filemtime( $graphFile );
		    $expireTime = $graphLastGenerated + $this->m_updatefrequency;
		    if ( $expireTime < time() ) {
			@unlink( $graphFile );
		    }
		}

		// check if previous plot generated with the same params and result data is available
		// we know this from the md5 hash.  This should eliminate
		// unneeded, CPU-intensive invocations of ploticus and minimize
		// the need to periodically clean-up graph, csv, and map files
		$errorData = '';
		if ( $this->m_debug || !file_exists( $graphFile ) ) {

			// we set $srfgEnvSettings if specified
			$commandline = empty( $srfgEnvSettings ) ? ' ' : $srfgEnvSettings . ' ';

			
		    // build the command line 
		    $commandline .= wfEscapeShellArg( $srfgPloticusPath ) .
			    ( $this->m_debug ? ' -debug':' ' ) .
			    ' -noshell ' . $sanitized_ploticusparams .
			    ( $this->mShowHeaders ? ' header=yes':' ' ) .
			    ' delim=comma data=' . wfEscapeShellArg( $dataFile ) .
			    ' -' . $this->m_imageformat;

		    if ( $this->m_imageformat == 'drawdump' || $this->m_imageformat == 'drawdumpa' ) {
			$commandline .= ' ' . wfEscapeShellArg( $ploticusDir .  '/' . $this->m_drawdumpoutput );
		    } else {
			$commandline .= ' -o ' . wfEscapeShellArg( $graphFile );
		    }

			// create the imagemap file if clickmap is specified for ploticus
			if ( strpos( $sanitized_ploticusparams, 'clickmap' ) ) {
				$commandline .= ' >' . wfEscapeShellArg( $mapFile );
			}

			// send errors to this file
			$commandline .= ' 2>' . wfEscapeShellArg( $errorFile );

			// Sanitize commandline
			$commandline = escapeshellcmd( $commandline );
			// Execute ploticus.
			wfShellExec( $commandline );
			$errorData = file_get_contents( $errorFile );
			if ( !$this->m_debug )
				@unlink( $errorFile );

			$graphLastGenerated = time(); // faster than doing filemtime

		}

		// Prepare output.  Put everything inside a table
		// PLOT ROW - colspan 3
		$rtnstr = '<table class="srfptable" id="srfptblid' . $smwgIQRunningNumber . '" cols="3"' .
			( empty( $this->m_tblwidth ) ? ' ' : ' width="' . $this->m_tblwidth . '" ' ) .
			( empty( $this->m_tblheight ) ? ' ' : ' height="' . $this->m_tblheight . '" ' ) .
			'><tr>';
		if ( !empty( $errorData ) && !$this->m_debug ) {
			// there was an error.  We do the not debug check since ploticus by default sends the debug trace to stderr too
			// so when debug is on, having a non-empty errorData does not necessarily indicate an error.
			$rtnstr .= '<td class="srfperror" colspan="3">Error processing ploticus data:</td></tr><tr><td class="srfperror" colspan="3" align="center">' .
				$errorData . '</td></tr>';
		} else {
			$rtnstr .= '<td class="srfpplot" colspan="3" align="center">';
			switch ( $this->m_imageformat ) {
				case 'svg':
				case 'svgz':
					$rtnstr .= '<object data="' . $graphURL . '"' .
						( empty( $this->m_width ) ? ' ' : ' width="' . $this->m_width . '" ' ) .
						( empty( $this->m_height ) ? ' ' : ' height="' . $this->m_height . '" ' ) .
						'type="image/svg+xml"><param name="src" value="' . $graphURL .
						'"> alt : <a href="' . $graphURL . '">Requires SVG capable browser</a></object>';
					break;
				case 'swf':
					$rtnstr .= '<object type="application/x-shockwave-flash" data="' . $graphURL . '"' .
						( empty( $this->m_width ) ? ' ' : ' width="' . $this->m_width . '" ' ) .
						( empty( $this->m_height ) ? ' ' : ' height="' . $this->m_height . '" ' ) .
						'><param name="movie" value="' . $graphURL .
						'"><param name="loop" value="false"><param name="SCALE" value="noborder"> alt : <a href="' . $graphURL .
						'">Requires Adobe Flash plugin</a></object>';
					break;
				case 'png':
				case 'gif':
				case 'jpeg':
					if ( strpos( $sanitized_ploticusparams, 'clickmap' ) ) {
						// we are using clickmaps, create HTML snippet to enable client-side imagemaps
						$mapData = file_get_contents( $mapFile );
						$rtnstr .= '<map name="' . $orighash . '">' . $mapData .
							'</map><img src="' . $graphURL . '" border="0" usemap="#' . $orighash . '">';
					} else {
					    $rtnstr .= '<img src="' . $graphURL . '" alt="' . $this->m_titletext . '" title="' .  $this->m_titletext . '">';
					}
					break;
				case 'eps':
				case 'ps':
					$rtnstr .= '<object type="application/postscript" data="' . $graphURL . '"' .
					( empty( $this->m_width ) ? ' ' : ' width="' . $this->m_width . '" ' ) .
					( empty( $this->m_height ) ? ' ' : ' height="' . $this->m_height . '" ' ) .
					'> alt : <a href="' . $graphURL . '">Requires PDF-capable browser</a></object>';
			}
			$rtnstr .= '</td></tr>';
		}
		// INFOROW - colspan 3
		$rtnstr .= '<tr><td class="srfpaction" width="33%" colspan="1">';

		// INFOROW - ACTIONS - col 1
		// if showcsv or debug is on, add link to data file (CSV)
		if ( $this->m_showcsv || $this->m_debug ) {
			$rtnstr .= '<a href="' . $dataURL . '" title="CSV file"><img src="' .
				$srficonPath . 'csv_16.png" alt="CSV file"></a>';
		} else {
		    @unlink( $dataFile ); // otherwise, clean it up
		}

		// if showimagelink is on, add link to open image in a new window
		if ( $this->m_showimagelink ) {
			$rtnstr .= ' <a href="' . $graphURL . '" target="_blank" title="Open image in new window"><img src="' .
				$srficonPath . 'barchart_16.png" alt="Open image in new window"></a>';
		}

		// if showrefresh is on, create link to force refresh
		if ( $this->m_showrefresh ) {
			global $wgArticlePath;
			$rtnstr .= ' <a href="' . $wgArticlePath . '?action=purge" title="Reload"><img src="' .
				$srficonPath . 'reload_16.png" alt="Reload"></a>';
		}

		// INFOROW - col 2
		// show titletext
		$rtnstr .= '</td><td class="srfptitle" width="33%" colspan="1" align="center">' . $this->m_titletext;

		// INFOROW - TIMESTAMP - col 3
		// if showtimestamp is on, add plot generation timestamp
		$rtnstr .= '</td><td class="srfptimestamp" width="33%" colspan="1" align="right">';
		if ( $this->m_showtimestamp ) {
			$rtnstr .= '<small> Generated: ' . date( 'Y-m-d h:i:s A', $graphLastGenerated ) . '</small>';
		}

		$rtnstr .= '</td></tr>';

		// DEBUGROW - colspan 3, only display when debug is on
		// Display ploticus cmdline
		if ( $this->m_debug ) {
			$rtnstr .= '<tr><td class="srfpdebug" align="center" colspan="3">DEBUG: PREFAB (<a href=" ' . $errorURL .
				'" target="_blank">Ploticus Trace</a>)</td></tr><tr><td class="srfpdebug" colspan="3">' .
				$commandline . '</td></tr>';
		}

		$rtnstr .= '</table>';

		return ( $rtnstr );
	}
示例#19
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 = explode(',', $filter);
             $filtersForPrintout = array_map('trim', $filtersForPrintout);
             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 = '';
     $viewHandlers = array();
     $viewElements = array();
     foreach ($this->mViews as $viewName) {
         if (array_key_exists($viewName, $this->mViewTypes)) {
             // generate unique id
             $viewid = uniqid();
             $view = new $this->mViewTypes[$viewName]($viewid, $result, $this->mParams, $this);
             $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-{$viewName} {$viewid}"), $view->getResultText());
             $viewHandlers[$viewName] = null;
             $viewElements[$viewName][] = $viewid;
         }
     }
     // wrap views in a div
     $viewHtml = Html::rawElement('div', array('class' => 'filtered-views'), $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) . ', "filterhandlers" : ' . json_encode($filterHandlers) . ', "filterdata" : ' . json_encode($filterData) . '}};'));
     SMWOutputs::requireResource('ext.srf.filtered');
     // wrap all in a div
     $html = Html::rawElement('div', array('class' => 'filtered ' . $id), $filterHtml . $viewHtml);
     return $html;
 }