|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * @see https://www.mediawiki.org/wiki/Extension:PageProperties |
| 5 | + * @author thomas-topway-it for KM-A |
| 6 | + */ |
| 7 | + |
| 8 | +namespace SMT; |
| 9 | + |
| 10 | +use Html; |
| 11 | +use OutputPage; |
| 12 | +use SpecialPage; |
| 13 | +use Title; |
| 14 | + |
| 15 | +class JsonLDSerializer { |
| 16 | + /** |
| 17 | + * @param Title $title |
| 18 | + * @param OutputPage $outputPage |
| 19 | + */ |
| 20 | + public function __construct( $title, $outputPage ) { |
| 21 | + if ( $this->isKnownArticle( $title ) ) { |
| 22 | + $this->setJsonLD( $title, $outputPage ); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @see https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/PageProperties/+/548d30609c512a79e202dfa7c02a298c66ca34fa/includes/PageProperties.php |
| 28 | + * @param Title $title |
| 29 | + * @return bool |
| 30 | + */ |
| 31 | + private function isKnownArticle( $title ) { |
| 32 | + return ( $title && $title->canExist() && $title->getArticleID() > 0 |
| 33 | + && $title->isKnown() ); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @see https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/PageProperties/+/548d30609c512a79e202dfa7c02a298c66ca34fa/includes/PageProperties.php |
| 38 | + * @param Title $title |
| 39 | + * @param OutputPage $outputPage |
| 40 | + * @return void |
| 41 | + */ |
| 42 | + public static function setJsonLD( $title, $outputPage ) { |
| 43 | + if ( !class_exists( '\EasyRdf\Graph' ) || !class_exists( '\ML\JsonLD\JsonLD' ) ) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + // @TODO use directly the function makeExportDataForSubject |
| 48 | + // SemanticMediawiki/includes/export/SMW_Exporter.php |
| 49 | + $export_rdf = SpecialPage::getTitleFor( 'ExportRDF' ); |
| 50 | + if ( $export_rdf->isKnown() ) { |
| 51 | + $export_url = $export_rdf->getFullURL( [ |
| 52 | + 'page' => $title->getFullText(), |
| 53 | + 'recursive' => '1', |
| 54 | + 'backlinks' => 0 |
| 55 | + ] ); |
| 56 | + |
| 57 | + try { |
| 58 | + $foaf = new \EasyRdf\Graph( $export_url ); |
| 59 | + $foaf->load(); |
| 60 | + |
| 61 | + $format = \EasyRdf\Format::getFormat( 'jsonld' ); |
| 62 | + $output = $foaf->serialise( $format, [ |
| 63 | + 'compact' => true, |
| 64 | + ] ); |
| 65 | + |
| 66 | + } catch ( Exception $e ) { |
| 67 | + self::$Logger->error( 'EasyRdf error: ' . $export_url ); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + // https://hotexamples.com/examples/-/EasyRdf_Graph/serialise/php-easyrdf_graph-serialise-method-examples.html |
| 72 | + if ( is_scalar( $output ) ) { |
| 73 | + $outputPage->addHeadItem( 'json-ld', Html::Element( |
| 74 | + 'script', [ 'type' => 'application/ld+json' ], $output |
| 75 | + ) |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments