r47074 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r47073‎ | r47074 | r47075 >
Date:09:06, 10 February 2009
Author:mkroetzsch
Status:deferred
Tags:
Comment:
initial version of JSON export format: this simple data export is the basis for embedding wiki-data into various other JavaScript
applications, e.g. into blogs via a Wordpress plugin (currently developed at MIT CSAIL) or via SMW extensions (based on the Exhibit result printer,
prototype available); code contributed by Fabian Howahl
Modified paths:
  • /trunk/extensions/SemanticMediaWiki/includes/SMW_GlobalFunctions.php (modified) (history)
  • /trunk/extensions/SemanticMediaWiki/includes/SMW_QP_JSONlink.php (added) (history)
  • /trunk/extensions/SemanticMediaWiki/includes/SMW_QueryProcessor.php (modified) (history)
  • /trunk/extensions/SemanticMediaWiki/includes/SMW_Settings.php (modified) (history)
  • /trunk/extensions/SemanticMediaWiki/languages/SMW_Messages.php (modified) (history)

Diff [purge]

Index: trunk/extensions/SemanticMediaWiki/includes/SMW_QP_JSONlink.php
@@ -0,0 +1,129 @@
 2+<?php
 3+/**
 4+ * Print links to JSON files representing query results.
 5+ * @file
 6+ * @ingroup SMWQuery
 7+ */
 8+
 9+/**
 10+ * Printer for creating a link to JSON files.
 11+ *
 12+ * @author Fabian Howahl
 13+ * @ingroup SMWQuery
 14+ */
 15+class SMWJSONResultPrinter extends SMWResultPrinter {
 16+ protected $types = array("_wpg" => "text", "_num" => "number", "_dat" => "date", "_geo" => "text", "_str" => "text");
 17+
 18+ public function getMimeType($res) {
 19+ return 'application/JSON';
 20+ }
 21+
 22+ public function getFileName($res) {
 23+ if ($this->getSearchLabel(SMW_OUTPUT_WIKI) != '') {
 24+ return str_replace(' ', '_',$this->getSearchLabel(SMW_OUTPUT_WIKI)) . '.json';
 25+ } else {
 26+ return 'result.json';
 27+ }
 28+ }
 29+
 30+ protected function getResultText($res, $outputmode) {
 31+ global $smwgIQRunningNumber, $wgSitename, $wgServer, $wgScriptPath;
 32+ $result = '';
 33+ if ($outputmode == SMW_OUTPUT_FILE) { // create detached JSON file
 34+ $itemstack = array(); //contains Items for the items section
 35+ $propertystack = array(); //contains Properties for the property section
 36+ //generate property section
 37+ foreach ($res->getPrintRequests() as $pr) {
 38+ if(array_key_exists($pr->getTypeID(), $this->types)){
 39+ $propertystack[] = '"'.str_replace(" ","_",strtolower($pr->getLabel())).'" : { valueType: "'.$this->types[$pr->getTypeID()].'" }';
 40+ }
 41+ else {
 42+ $propertystack[] = '"'.str_replace(" ","_",strtolower($pr->getLabel())).'" : { valueType: "text" }';
 43+ }
 44+ }
 45+ array_shift($propertystack); //drop first property
 46+ $properties ="properties: {\n\t\t".implode(",\n\t\t",$propertystack). "\n\t}";
 47+
 48+ //generate items section
 49+ $row = $res->getNext();
 50+ while ( $row !== false ) {
 51+ $valuestack = array(); //contains Property-Value pairs to characterize an Item
 52+ $count = 0; //counter
 53+ $prefixedtext = ''; //save label for uri specification
 54+ foreach ($row as $field) {
 55+ $req = $field->getPrintRequest();
 56+ if($count==0){
 57+ $values = '';
 58+ foreach($field->getContent() as $value){
 59+ $values = $value->getShortText($outputmode,NULL); //assign last value to label
 60+ $prefixedtext = $value->getPrefixedText();
 61+ }
 62+ $valuestack[] = 'label: "'.$values.'"';
 63+ } else {
 64+ $values = array();
 65+ $finalvalues = '';
 66+ while ( ($value = $field->getNextObject()) !== false ){
 67+ $finalvalues = '';
 68+ switch($value->getTypeID()){
 69+ case '_geo':
 70+ $values[] = '"'.$value->getXSDValue().'"';
 71+ break;
 72+ case '_num':
 73+ $values[] = $value->getNumericValue($outputmode,$this->getLinker(0));
 74+ break;
 75+ case '_dat':
 76+ $values[] = "\"".$value->getYear()."-".str_pad($value->getMonth(),2,'0',STR_PAD_LEFT)."-".str_pad($value->getDay(),2,'0',STR_PAD_LEFT)." ".$value->getTimeString()."\"";
 77+ break;
 78+ default:
 79+ $values[] = '"'.$value->getShortText($outputmode,NULL).'"';
 80+ }
 81+
 82+ if(sizeof($values)>1){
 83+ $finalvalues = "[".implode(",",$values)."]";
 84+ } else {
 85+ $finalvalues = $values[0];
 86+ }
 87+ }
 88+ if($finalvalues != '') $valuestack[] = '"'.str_replace(" ","_",strtolower($req->getLabel())).'": '.$finalvalues.'';
 89+ }
 90+ $count++;
 91+ }
 92+ $valuestack[] = '"uri" : "'.$wgServer.$wgScriptPath.'/index.php?title='.$prefixedtext.'"';
 93+ $itemstack[] = "\t{\n\t\t\t".implode(",\n\t\t\t",$valuestack)."\n\t\t}";
 94+ $row = $res->getNext();
 95+ }
 96+
 97+ $items = "items: [\n\t".implode(",\n\t",$itemstack)."\n\t]";
 98+
 99+ //check whether a callback function is required
 100+ if(array_key_exists('callback', $this->m_params)){
 101+ $result = htmlspecialchars($this->m_params['callback'])."({\n\t".$properties.",\n\t".$items."\n})";
 102+ } else {
 103+ $result = "{\n\t".$properties.",\n\t".$items."\n}";
 104+ }
 105+
 106+ } else { // just create a link that points to the JSON file
 107+ if ($this->getSearchLabel($outputmode)) {
 108+ $label = $this->getSearchLabel($outputmode);
 109+ } else {
 110+ wfLoadExtensionMessages('SemanticMediaWiki');
 111+ $label = wfMsgForContent('smw_json_link');
 112+ }
 113+ $link = $res->getQueryLink($label);
 114+ if(array_key_exists('callback', $this->m_params)) {
 115+ $link->setParameter(htmlspecialchars($this->m_params['callback']),'callback');
 116+ }
 117+ if(array_key_exists('limit', $this->m_params)) {
 118+ $link->setParameter(htmlspecialchars($this->m_params['limit']),'limit');
 119+ }
 120+ $link->setParameter('json','format');
 121+ $result = $link->getText($outputmode,$this->mLinker);
 122+ }
 123+
 124+ return $result;
 125+ }
 126+
 127+}
 128+
 129+
 130+
Property changes on: trunk/extensions/SemanticMediaWiki/includes/SMW_QP_JSONlink.php
___________________________________________________________________
Name: svn:eol-style
1131 + native
Index: trunk/extensions/SemanticMediaWiki/includes/SMW_QueryProcessor.php
@@ -56,7 +56,7 @@
5757 $querymode = SMWQuery::MODE_COUNT;
5858 } elseif ($format == 'debug') {
5959 $querymode = SMWQuery::MODE_DEBUG;
60 - } elseif (in_array($format, array('rss','icalendar','vcard','csv'))) {
 60+ } elseif (in_array($format, array('rss','icalendar','vcard','csv','json'))) {
6161 $querymode = SMWQuery::MODE_NONE;
6262 } else {
6363 $querymode = SMWQuery::MODE_INSTANCES;
Index: trunk/extensions/SemanticMediaWiki/includes/SMW_GlobalFunctions.php
@@ -125,6 +125,7 @@
126126 $wgAutoloadClasses['SMWiCalendarResultPrinter'] = $smwgIP . '/includes/SMW_QP_iCalendar.php';
127127 $wgAutoloadClasses['SMWvCardResultPrinter'] = $smwgIP . '/includes/SMW_QP_vCard.php';
128128 $wgAutoloadClasses['SMWCsvResultPrinter'] = $smwgIP . '/includes/SMW_QP_CSV.php';
 129+ $wgAutoloadClasses['SMWJSONResultPrinter'] = $smwgIP . '/includes/SMW_QP_JSONlink.php';
129130 //// datavalues
130131 $wgAutoloadClasses['SMWDataValueFactory'] = $smwgIP . '/includes/SMW_DataValueFactory.php';
131132 $wgAutoloadClasses['SMWDataValue'] = $smwgIP . '/includes/SMW_DataValue.php';
Index: trunk/extensions/SemanticMediaWiki/includes/SMW_Settings.php
@@ -66,8 +66,8 @@
6767
6868 ###
6969 # This setting allows you to select in which cases you want to have a factbox
70 -# appear below an article. Note that the Magic Words __SHOWFACTBOX__ and
71 -# __HIDEFACTBOX__ can be used to control Factbox display for individual pages.
 70+# appear below an article. Note that the Magic Words __SHOWFACTBOX__ and
 71+# __HIDEFACTBOX__ can be used to control Factbox display for individual pages.
7272 # Other options for this setting include:
7373 ##
7474 //$smwgShowFactbox = SMW_FACTBOX_NONEMPTY; # show only those factboxes that have some content
@@ -104,7 +104,7 @@
105105 # values. This is due to limitations in the library PCRE that PHP uses for
106106 # pattern matching. The provoked PHP crashes will prevent requests from being
107107 # completed -- usually clients will receive server errors ("invalid response")
108 -# or be offered to download "index.php". It might be okay to enable this if
 108+# or be offered to download "index.php". It might be okay to enable this if
109109 # such problems are not observed in your wiki.
110110 ##
111111 $smwgLinksInValues = false;
@@ -240,7 +240,8 @@
241241 'rss' => 'SMWRSSResultPrinter',
242242 'icalendar' => 'SMWiCalendarResultPrinter',
243243 'vcard' => 'SMWvCardResultPrinter',
244 - 'csv' => 'SMWCsvResultPrinter'
 244+ 'csv' => 'SMWCsvResultPrinter',
 245+ 'json' => 'SMWJSONResultPrinter'
245246 );
246247 ##
247248
@@ -269,10 +270,10 @@
270271 // OWL Full or rather nice OWL DL.
271272 // Can be overriden in the RDF export class.
272273 // global $smwgNamespace; // The Namespace of exported URIs.
273 -// $smwgNamespace = "http://example.org/id/"; // Will be set automatically if
 274+// $smwgNamespace = "http://example.org/id/"; // Will be set automatically if
274275 // nothing is given, but in order to make pretty URIs you will need to set this
275276 // to something nice and adapt your Apache configuration appropriately. This is
276 -// done, e.g., on semanticweb.org, where URIs are of the form
 277+// done, e.g., on semanticweb.org, where URIs are of the form
277278 // http://semanticweb.org/id/FOAF
278279 ##
279280
Index: trunk/extensions/SemanticMediaWiki/languages/SMW_Messages.php
@@ -36,6 +36,8 @@
3737 'smw_rss_link' => 'RSS',
3838 // Link to CSV feeds
3939 'smw_csv_link' => 'CSV',
 40+ // Link to JSON feeds
 41+ 'smw_json_link' => 'JSON',
4042
4143 // Link to iCalendar and vCard files
4244 'smw_icalendar_link' => 'iCalendar',
@@ -579,7 +581,7 @@
580582 'smw_smwadmin_updatestarted' => 'عملية تحديث جديدة لتحديث بيانات سيمانتيك بدأت.
581583 كل البيانات المخزنة ستتم إعادة بنائها أو إصلاحها عند الحاجة.
582584 أنت يمكنك متابعة تطور التحديث على هذه الصفحة الخاصة.',
583 - 'smw_smwadmin_updatenotstarted' => 'يوجد بالفعل عملية تحديث جارية
 585+ 'smw_smwadmin_updatenotstarted' => 'يوجد بالفعل عملية تحديث جارية
584586 <br>لا تنشئ واحدة أخرى
585587 <br />',
586588 'smw_smwadmin_updatestopped' => 'كل عمليات التحديث الموجودة تم إيقافها',
@@ -792,7 +794,7 @@
793795 'smw_smwadmin_updatestarted' => 'عملية تحديث جديدة لتحديث بيانات سيمانتيك بدأت.
794796 كل البيانات المخزنة ستتم إعادة بنائها أو إصلاحها عند الحاجة.
795797 أنت يمكنك متابعة تطور التحديث على هذه الصفحة الخاصة.',
796 - 'smw_smwadmin_updatenotstarted' => 'يوجد بالفعل عملية تحديث جارية
 798+ 'smw_smwadmin_updatenotstarted' => 'يوجد بالفعل عملية تحديث جارية
797799 <br>لا تنشئ واحدة أخرى
798800 <br />',
799801 'smw_smwadmin_updatestopped' => 'كل عمليات التحديث الموجودة تم إيقافها',
@@ -1792,8 +1794,8 @@
17931795 'smw_types_docu' => 'Les types de données suivants peuvent être assignées aux attributs. Chaque type de données a sa propre page, dans laquelle peuvent figurer des informations plus précises.',
17941796 'smw_typeunits' => 'Unités de mesure de type « $1 » : $2',
17951797 'semanticstatistics' => 'Statistiques sémantiques',
1796 - 'smw_semstats_text' => 'Ce wiki contient <b>$1</b> valeurs de propriété pour un total de <b>$2</b> <a href="$3">propriétés</a> différentes.
1797 -<b>$4</b> propriétés ont leur propre page, et le type de données voulu est spécifié pour <b>$5</b> de celles-ci.
 1798+ 'smw_semstats_text' => 'Ce wiki contient <b>$1</b> valeurs de propriété pour un total de <b>$2</b> <a href="$3">propriétés</a> différentes.
 1799+<b>$4</b> propriétés ont leur propre page, et le type de données voulu est spécifié pour <b>$5</b> de celles-ci.
17981800 Certaines des propriétés existantes peuvent faire être <a href="$6">inutilisées</a>. Les propriétés qui n\'ont pas encore de page se trouvent dans la <a href="$7">liste des propriétés demandées</a>.',
17991801 'flawedattributes' => 'Attributs défectueux',
18001802 'smw_fattributes' => "Les pages ci-dessous ont un attribut qui n'est pas défini correctement. Le nombre d'attributs incorrects est donné entre les parenthèses.",

Status & tagging log