GithubHelp home page GithubHelp logo
facebook-instant-articles-sdk-php

facebook / facebook-instant-articles-sdk-php Goto Github PK

View Code? Open in 1sVSCode Editor NEW
227.0 52.0 133.0 1.35 MB

The Facebook Instant Articles SDK for PHP provides a native interface for creating and publishing Instant Articles.

Home Page: https://instantarticles.fb.com/

License: Other

PHP 87.93% HTML 12.07%

facebook-instant-articles-sdk-php's Introduction

Facebook Instant Articles PHP SDK

CircleCI Latest Stable Version

The Facebook Instant Articles SDK for PHP provides a native interface for creating and publishing Instant Articles. The SDK enables developers to more easily integrate Instant Articles into content management systems and in turn enables journalist and publishers to easily publish Instant Articles.

The SDK consists of three components:

  • Elements: A domain-specific language for creating an Instant Articles structure that strictly follows the specification and can be automatically serialized into the subset of HTML5 markup used in the Instant Articles format. This language allows users to programmatically create Instant Articles that are guaranteed to be in compliance with the format.
  • Transformer: An engine for transforming any markup into an Instant Article structure in the DSL. The engine runs a set of rules on the markup that will specify the selection and transformation of elements output by the CMS into their Instant Articles counterparts. The transformer ships with a base set of rules for common elements (such as a basic paragraph or an image) that can be extended and customized by developers utilizing the SDK.
  • Client: A simple wrapper around the Instant Articles API, which can be used for publishing Instant Articles on Facebook. The client provides a CRUD interface for Instant Articles as well as a helper for authentication. The client depends on the main Facebook SDK for PHP as an interface to the Graph API and Facebook Login.

Quick Start

The Facebook Instant Articles PHP SDK can be installed with the Composer dependency manager by running this command on your project's root folder:

$ composer require facebook/facebook-instant-articles-sdk-php

After the installation, you can include the auto loader script in your source with:

require_once 'vendor/autoload.php';

Official Documentation

You can find examples on how to use the different components of this SDK to integrate it with your CMS in the Getting Started section of the documentation.

Contributing

Clone the repository

$ git clone https://github.com/facebook/facebook-instant-articles-sdk-php.git

Composer is a prerequisite for testing and developing. Install composer globally, then install project dependencies by running this command in the project's root directory:

$ composer install

To run the tests:

$ composer test

To fix and check for coding style issues:

$ composer cs

Extra lazy? Run

$ composer all

to fix and check for coding style issues, and run the tests.

If you change structure, paths, namespaces, etc., make sure you run the autoload generator:

$ composer dump-autoload

For us to accept contributions you will have to first sign the Contributor License Agreement. Please see CONTRIBUTING for details.


Testing with Docker

We have provide a Docker environment to ensure a consistent testing & development environment.

Use docker-compose run composer composer install to get started.

Troubleshooting

If you are encountering problems, the following tips may help in troubleshooting issues:

  • Warnings from the Transformer can be seen with $transformer->getWarnings() method.

  • If content is missing from your transformed article, more likely than not there isn't a Transformer Rule matching an element in your source markup. See how to configure appropriate rules for your content in the Transformer Rules documentation.

  • Set the threshold in the transformer Logger level to DEBUG to expose more details about the items processed by the Transformer. TransformerLog::setLevel(TransformerLog::DEBUG);

  • Refer to the existing tests of the Elements for examples of what is required of each and to potentially create your own tests (which can be run with $ composer test).

License

Please see the license file for more information.

Legal

facebook-instant-articles-sdk-php's People

Contributors

everton-rosario avatar diegoquinteiro avatar localheinz avatar simonengelhardt avatar mburak avatar pestevez avatar demoive avatar gemedet avatar dodozhang21 avatar vkama avatar despinoUY avatar scottrigby avatar timjacobi avatar alexander-schranz avatar jppgks avatar nataliemt avatar koconder avatar alucic avatar flarnie avatar carusogabriel avatar sakatam avatar m4olivei avatar dlackty avatar manishbisht avatar philipjohn avatar umbrella-kirill-starikov avatar elomar avatar alexmanno avatar aminnelson avatar tungvn avatar

Stargazers

David Joseph, Founder @ iA Labs avatar John Efemer avatar  avatar firman adetia putra avatar  avatar Mohamed Osman avatar  avatar Logic Systems avatar  avatar Keany Vy KHUN avatar Paulo Manso avatar Shoshana Wodinsky avatar Tbnoapi avatar Sinyaya Dynya avatar  avatar Tawan miyaemphak  avatar Madi avatar lilkypimp1 avatar Dani avatar john monti avatar @GOUAIC avatar Joe Adkins avatar VRanger avatar Iqbal Rifai avatar Ammar Faizi avatar  avatar HarishST avatar Kumar Bishojit Paul avatar Oleg Koval avatar NAING LYNN HTUN avatar  avatar Paweł Mikołajczuk avatar Gábor Mihálcz avatar Hlaing Tin Htun avatar Aung Kyaw Phyo avatar Jarosław Goszowski avatar Lloric Mayuga Garcia avatar Andrey Bolonin avatar Nguyen Van Nguyen avatar Volodymyr Kupriienko avatar Luis Miguel Alvarado avatar  avatar Marty McGuire avatar Jose María Hidalgo avatar Andy avatar  avatar Placinta Alex avatar Sekos Kone avatar waskito shidiq avatar Gopalakrishnan Anbumani avatar Ben Huang avatar Joshua Briefman avatar Gustavo Alfredo Marín Sáez avatar khristoff avatar Serhii Hulenko avatar TZU-YEN, CHANG avatar  avatar daniel avatar  avatar Chan Cheung Wai avatar Maina Wycliffe avatar Thierry Jarrige avatar Galt Khurelbaatar avatar Samrat Khan avatar Lars Schwarz avatar Kollan House avatar  avatar Ali Osman Yüksel avatar Glad Chinda avatar Jaya avatar Supreet avatar  avatar PEA avatar  avatar Aung Kyaw Soe Min avatar  avatar André Bose do Amaral avatar 王可森 avatar David Wu avatar  avatar jcteo avatar Edgars Ozolins avatar David Turner avatar wirawanprasetyo avatar  avatar Zak B. Elep avatar Antoine Imbert avatar Matias Solis de la Torre avatar fiicode avatar William Li avatar Andre LaMont avatar Jayasim Jayakumar avatar Rich Donn avatar Nashwan Doaqan avatar Taylor Johnson avatar Jérôme Tamarelle avatar Moazam avatar Benjamin Brandt avatar  avatar Canberk Çevik avatar

Watchers

Elomar Souza avatar Piyush avatar wirawanprasetyo avatar Makoto Sakata avatar Scott Bulua avatar Danny Froberg avatar  avatar Paulo Ávila avatar  avatar James Cloos avatar Matias Burak avatar facebook ink avatar Aaron Kushner avatar  avatar Tim Jacobi avatar Gisela avatar Yasser Mohammed avatar gpdimonderose avatar Olga Svistunova avatar Jaya avatar Chaipat avatar  avatar  avatar  avatar JUNO_OKYO avatar Julio Gaiotto avatar  avatar  avatar Wilman Bhigu avatar  avatar  avatar Facebook Whois Bot avatar Evgeniy Koval avatar Natália de Azevedo avatar 曹文忠 avatar Nitesh Manav avatar Huthayfa avatar fiicode avatar  avatar Saidov Nuriddin avatar Pablo Estevez avatar Vinicius Kamakura avatar Shoshana Wodinsky avatar  avatar  avatar  avatar  avatar @GOUAIC avatar  avatar Joe Adkins avatar Deep Ganatra avatar  avatar

facebook-instant-articles-sdk-php's Issues

RelatedArticles title should not render in footer

Facebook UI is reporting title attribute as not supported when being used on an related articles element in the footer (which is in line with the FBIA specs). If possible though, RelatedArticles element shouldn't render title attribute when in footer.

Trying to setup a transformer rule

Hi there,

I am embedding my own video player which is used as an iframe. The height attribute is being stripped from the video, so I am trying to setup a transformer rule to apply it.


{ "rules":[

{
     "class": "InteractiveRule",
     "selector": ".springboard-height",
     "properties" : {

       "interactive.height" : {     // Name of property
         "type" : "",
         "selector" : "",
         "attribute": ""
       }

     }
    }

]}

I'm not sure what the type/selector/attribute values should be for the properties. springboard-height is a class which is assigned to the video itself.

Any ideas?

How do you transform video title?

I don't understand how I can produce the following with video transform rule. How come there is no documentation on how to use the video rule? I didn't find any tests for it either.

<figure>
  <video>
    <source src="http://mydomain.com/path/to/video.mp4" type="video/mp4" />  
  </video>
  <figcaption class="op-vertical-below">
    <h1>Video 1 Title</h1>
  </figcaption>
  <cite>
    Attribution Source
  </cite>
</figure>

'v.1.5.0' is not found in composer while the tag `v.1.5.0' is invalid.

Could you update the tag v1.5.0 (now tagged as v.1.5.0)?

Steps required to reproduce the problem

If a composer package that dpends on SDK, it will define composer.json as:

{
    "require": {
        "facebook/facebook-instant-articles-sdk-php": "^1.5.0"
    }
}

And the developer hits composer install or composer update to install the latest version of SDK.

Expected Result

The dependency should be resolved and v1.5.0 should be installed. If developers use composer update, their composer.lock file should be updated.

Actual Result

composer update returns an error as follows:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package facebook/facebook-instant-articles-sdk-php ^1.5.0 exists as facebook/facebook-instant-articles-sdk-php[1.0.4, dev-alucic-article-interface, dev-block_warnings, dev-feature/fix-dev-mode-article-lookup, dev-hardcoded_getter, dev-issue-205, dev-jetpack-carousel, dev-master, dev-philipjohn-fix/check-array, dev-playbuzz, dev-slideshow-header, dev-the-image, dev-validation-iframe-width-height, v0.1.0, v0.2.0, v0.3.0, v0.4.0, v0.4.1, v0.5.0, v0.6.0, v0.6.1, v0.6.2, v0.6.3, v0.6.4, v0.6.5, v0.6.6, v0.6.7, v0.6.8, v0.6.9, v1.0.0, v1.0.1, v1.0.2, v1.0.3, v1.0.5, v1.0.6, v1.1.0, v1.2.0, v1.3.0, v1.3.1, v1.4.0] but these are rejected by your constraint.

Transformer Error

I just updated my SDK and my transformer-rules.json file is apparently gone. Is there an updated version?

Class undefined: Facebook\InstantArticles\Elements\AnimatedGif in Elements/InstantArticle.php on line 196

Hi!

When I try to run the tests I see the following error:

Fatal error: Class undefined: Facebook\InstantArticles\Elements\AnimatedGif in /var/www/mysite/src/sites/all/modules/contrib/fb_instant_articles/vendor/facebook/facebook-instant-articles-sdk-php/src/Facebook/InstantArticles/Elements/InstantArticle.php on line 196

I'm not familiar with the code base, but I tried to find that class and only found facebook-instant-articles-sdk-php/src/Facebook/InstantArticles/Elements/AnimatedGIF.php. If I change that line, replacing the class name to AnimatedGIF as defined in that file, the issue disappears.

Is this an error or am I doing something wrong?

Thanks!

Installation fails, requires older version of syfony/css-selector

I have installed symfony/css-selector v 3.0.4 and when I try to install this package it says that it requires symfony/css-selector 2.8.* and thus it won't install. I can't downgrade symfony/css-selector because it's required for another package. Is this something that can be fixed?

Handling images inside paragraphs in Transformer

WYSISWYG Editors used in CMSs like drupal or WordPress often wrap <img> tags around a <p> tag. I was able to eliminate the wrap with preg_replace, but I am having issues with images inside a longer paragraph. Inserting an image inside a paragraph is valid according to html, but facebook instant articles requires any image to be wrapped inside a <figure> tag. I think that the ImageRule should be able to correctly handle images inside paragraphs.

HTML tags in titles

On my blog, I'm using HTML tags in the titles of my post, mainly <em></em> for the title of a work (like a movie). The plugin should strip HTML tags, since Instant Articles do not allow html in titles.

For instance, here is what I have in Facebook app :

img_2649-me

Here is the original URL : https://voiretmanger.fr/mommy-dolan/

Submit from a string

I would like to use a string variable that contains pre-validated IA markup to post a new article. Something like:

$client = Client::create($app_id, $app_secret, $page_token, $page_id, false);

// Import the article
try {
    $client->importArticle($article, false);
} catch (Exception $e) {
    echo 'Could not import the article: '.$e->getMessage();
}

where $article is a string.

How do you use the PullquoteRule and PullquoteCiteRule classes to put together a pull quote with a cite?

I'm using the Transformer. My target markup is this:

<blockquote class="pull-quote">
  <div class="field-quote">
    <p>Here is a fancy pull quote for the world to see it all.</p> 
  </div>
  <div class="field-quote-author">Matthew Oliveira</div>
</blockquote>

How do I use PullquoteRule and/or PullquoteCiteRule to transform to this:

<aside>
  Here is a fancy pull quote for the world to see it all.
  <cite>Matthew Oliveira</cite>
</aside>

At least it seems like PullquoteRule class is missing a property for the attribution?

WYSIWYG Instant Articles transformer

I have a proposal. In general, it's a great package, and it now has an implementation for WordPress as a plugin, which is fine. However, it may be interesting to create a package which would work as a wrapper for other systems as well.
It can be a universal package to translate ORM (or any data format) to Instant Articles format. The thing is, that most of the CMS systems actually do have database models (more or less), therefore have WYSIWYG editors installed - usually it's either CkEditor, either TinyMCE. If you'd make general translation code, taken from current WordPress plugin more abstract, it would be quite easy to adopt. E.g. people will be able to write native plugin to CkEditor itself.

Transformer drops images from li

The content:

<ul>
<li>
some text <a href="http://example.com/"><img src="http://example.com/image.jpg" width="600" height="360" /></a>
</li>
</ul>

After the transformer is done, there is no image.

Expected Result

<ul>
        <li>some text</li>
</ul>
<figure>
        <img src="http://example.com/image.jpg"/>
</figure>

Actual Result

<ul>
        <li>some text</li>
</ul>

The image is missing.

no any Class for div tag ??

Steps required to reproduce the problem

I have one recipe site and my recipe content not showing in facebook instant article post .
Showing this error : No rules defined for <div class="zlrecipe-container-border"> in the context of InstantArticle

"<div class="zlrecipe-container-border">" this div has all tags like heading h1, p, ul, li, dropdown etc...

I have checked all classes here: https://github.com/facebook/facebook-instant-articles-sdk-php/pull/118/files
Please let me know how to create rule for this ??

CDATA tag being added after <script> tags

We have custom embed code for some of our content that uses javascript. When outputing the article, the code within the <script> tags is wrapped with a CDATA tag.

This is the outcome:
<figure class="op-social"><iframe><script><![CDATA[ // javascript content here ]]></script></iframe></figure>
What we need:
<figure class="op-social"><iframe><script>// javascript content here</script></iframe></figure>

This is being caused by the render() return statement in Element.php. If we use a saveXML, it creates this CDATA tag after <script>, but if we use a saveHTML, there is no CDATA added.

return $doctype.$document->saveXML($element); // adds CDATA
return $doctype.$document->saveHTML($element); // correct (no CDATA)

youtube-nocookie errors

Steps required to reproduce the problem

insert <iframe src="https://www.youtube-nocookie.com/embed/F0vg4HUEIyk?rel=0&amp;showinfo=0" width="640" height="360" frameborder="0" allowfullscreen="allowfullscreen"></iframe> in the content field of wordpress

Expected Result

<figure class="op-social"><iframe width="640" height="360" src="https://www.youtube-nocookie.com/embed/F0vg4HUEIyk?rel=0&amp;showinfo=0"></iframe></figure>
If youtube-nocookie isn't support just rewrite the url to youtube.com without the -nocookie.

Actual Result

Webview with op-social class without any supported embed type: When using op-social class on a webview, it must have a supported embed inside it e.g. Instagram, Twitter, Facebook, Youtube, etc. We didn't find any here.

HTML Embeds Require Valid Width: HTML Embeds require a valid integer width in order to be displayed properly.

HTML Embeds Require Valid Height: HTML Embeds require a valid integer height in order to be displayed properly.

<figure class="op-social"><iframe src="https://www.youtube-nocookie.com/embed/F0vg4HUEIyk?rel=0&amp;showinfo=0"></iframe></figure>

Class 'InstantArticle' not found

I've followed the installation directions but am running into issues.

When I run composer install I get the following output:
Loading composer repositories with package information Installing dependencies (including require-dev) from lock file Nothing to install or update Generating autoload files

Then after requiring the vendor/autoload.php file the InstantArticle class is not found.

Need help, unable to import articles via Client

I am getting this exception while trying to import articles - The following code is copied straight from the quickstart.md

        // Instantiate an API client
        $client = Client::create($app_id,$secret,$access_token,$page_id,false);

        // Import the article
        try {
            $client->importArticle($instant_article, false);
        } catch (Exception $e) {
            echo 'Could not import the article: '.$e->getMessage();
        }
exception 'Facebook\Exceptions\FacebookAuthenticationException' with message 'Invalid appsecret_proof provided in the API argument' in /var/www/code/collegehumor/vendor/facebook/php-sdk-v4/src/Facebook/Exceptions/FacebookResponseException.php:106

Google Analytics: Specification mandate value for attribute async

Hi,

How do I use Google Analytics with your SDK?

Example from here is not working.

My code is

        $document = new DOMDocument();
        $analyticsNode = $document->createDocumentFragment();

        $analyticsNode->appendXML($this->analyticsHtmlCode);

        return Analytics::create()->withHTML($analyticsNode);

$this->analyticsHtmlCode =

<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
//id etc
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>

and the error is

DOMDocumentFragment::appendXML(): Entity: line 6: parser error : Specification mandate value for attribute async

Transformer drops content in pharagraph if there is image too

The content:
<p><a href="http://example.com/image.jpg"><img class="alignnone size-medium wp-image-45" src="http://example.com/image.jpg" alt="imagealt" width="300" height="169" /></a>Some text comes here and some more and more ... and some.</p>

After the closing <a> tag, there is some text, and the sdk drops that text.

Same happens when I reorder the inside:
<p>Some text comes here and some more and more ... and some.<a href="http://example.com/image.jpg"><img class="alignnone size-medium wp-image-45" src="http://example.com/image.jpg" alt="imagealt" width="300" height="169" /></a></p>

Or if there is text before and after:
<p>Some text comes here and some more and more ... and some.<a href="http://example.com/image.jpg"><img class="alignnone size-medium wp-image-45" src="http://example.com/image.jpg" alt="imagealt" width="300" height="169" /></a>Some text comes here and some more and more ... and some.</p>

The below expexted result is just for the first content example.

Expected Result

<figure>
        <img src="http://example.com/image.jpg"/>
</figure>
<p>Some text comes here and some more and more ... and some.</p>

Actual Result

<figure>
        <img src="http://example.com/image.jpg"/>
</figure>

composer.json needs update

The composer.json still links to facebook-php-sdk, which has been renamed/moved to facebook/graph-sdk. Please change the Requirement, so that only facebook/graph-sdk is included in external projects (otherwise, there are two Facebook SDKs installed).

Remove InstantArticle dependency from the Client

https://github.com/facebook/facebook-instant-articles-sdk-php/blob/master/src/Facebook/InstantArticles/Client/Client.php#L89

Client has hard dependency on InstantArticle. The only method being used is render which returns a markup.

Maybe we could do something like this to make Client usable outside of the SDK:

  1. Check against InstantArticleInterface that will have render method
  2. pass in string instead of InstantArticle - breaking change

Have you considered moving Client to a separate package?

Let me know what you think, I'll be happy to work on removing this dependency.

Thanks!

Getting "DEBUG =======." when using Transform

I have implemented Instant Article's API and I'm getting a DEBUG text when transforming the article.

Steps required to reproduce the problem

  1. Create a Instant Article Instance
  2. Append Header Data
  3. Transform a normal html (article content) via Transformer object
  4. Connect to Client
  5. Render Instant Article
  6. Import Article

You can find the code here:
http://paste.ofcode.org/36RBimG7nmeuiXCTCHGaQiC

Expected Result

(boolean)

Actual Result

I'm getting a "DEBUG =======.." row for each of DOM Elements in the article's content!

This is happening right after the following row:
$transformer->transform($instant_article, $document);

Bug was also reported in Facebook:
https://developers.facebook.com/bugs/1756986321207897/

Transformer logger use

The use of the logger in the Transformer code can be awkward when appenders are used that list in reverse chronological order. Or even just when each call to $log->debug() is stored in the database as a separate record rather then in a flat file. For example, we are using the Instant Articles SDK in a Drupal module here https://github.com/BurdaMagazinOrg/module-fb_instant_articles and the logs come out like this:

http://take.ms/y59qK

Could we instead build up the whole message as a string using newlines, before calling $log->debug with the entire message?

https://github.com/facebook/facebook-instant-articles-sdk-php/blob/master/src/Facebook/InstantArticles/Transformer/Rules/Rule.php#L20,L25

ImageRule

Is it possible to have the presentation property parsed in the image rule, the same way it is done in the VideoRule?

E.G.

    if ($this->getProperty(Video::ASPECT_FIT, $node)) {
        $video->withPresentation(Video::ASPECT_FIT);
    } elseif ($this->getProperty(Video::ASPECT_FIT_ONLY, $node)) {
        $video->withPresentation(Video::ASPECT_FIT_ONLY);
    } elseif ($this->getProperty(Video::FULLSCREEN, $node)) {
        $video->withPresentation(Video::FULLSCREEN);
    } elseif ($this->getProperty(Video::NON_INTERACTIVE, $node)) {
        $video->withPresentation(Video::NON_INTERACTIVE);
    }

Preformatted HTML

If I have HTML that already is in IA format, how do I use the API to submit it?

Problem with Custom Shortcodes Video Embed

Hello, I'm using custom shortcodes to embed youtube and facebook videos using their respective Javascript APIs. Example: [customyoutube id="XXXXX"] where XXXXX is the youtube video ID. The reason for this is that I added callback functions when the video finished playing. Now my problem is, Instant Articles displays the javascript part of the shortcode as paragraph block in the Instant Articles. Please kindly advice me how to transform the shortcode so that the output is IA compliant video embed. Thank you in advance.

Insufficient Transformer Documentation

I've been working with the "Instant Articles for WP" plugin which uses this library and I can't quite figure out how the transformer rules work, or how to create a new one, and the Quick Start Guide wasn't much help. It sort've just says, here are some things, they need these parameters, have fun. The code itself also doesn't have any docblocks so I can't wrap my head around what's actually going on and since everything is being autoloaded it's even harder to track. Please add some documentation so us non-facebook geniuses can work with this SDK.

FWIW I also created a ticket on the plugin support page: https://wordpress.org/support/topic/insufficient-transformer-documentation?replies=1

Thanks,
Alex

Analytics not rendering correctly

Hi,

So if you do the following as per the Facebook SDK found here: https://github.com/facebook/facebook-instant-articles-sdk-php/blob/master/docs/QuickStart.md#elements you'll get errors:

 ->addChild(
            Analytics::create()
                ->withHTML(
                    <h1>Some custom code</h1>
                    <script>alert("test");</script>
                )
        )

However if you do the following it works like a charm, I think the Facebook SDK documentation needs to be updated to reflect this:

$document = new \DOMDocument();
        $fragment = $document->createDocumentFragment();
        $valid_html = @$fragment->appendXML( "<script>". $analytics_code ."</script>" );
        if ( $valid_html ) {
            $article->addChild(
                \Facebook\InstantArticles\Elements\Analytics::create()
                        ->withHTML(
                            $fragment
                        )
                );
        }

Cross calls in the transformer and apply files slowing down the generation

I'm using the Instant Articles for WP plugin, which is works fine.
They are using this sdk and the problem is that the generation of the feed is very slow and it timeouts.
The problem is in the sdk, not in the plugin.

\src\Facebook\InstantArticles\Transformer\Transformer.php
The transform function calls the $rule->apply(...)
That's ok, but some of the apply rules call back the transfrom function.

For example it is a problem if you have a post with many images, then for one post to generate in the feed, it takes 5-10 seconds.
ImageRule.php: $transformer->transform($image, $node);
So, if the timeout is set to 180 second, then I can't generate more than 20 posts without a timeout, if they have multiple images. And for obvious reasons I don't want to raise the timeout.

I looked just for images, but the ParagraphRule and others also call back to the transformer function and slows down the process.

Submission Issue

I am having a recurring issue where an attempt to submit a new article results in the following error:

Steps required to reproduce the problem

  1. Create formatted HTML
  2. Run through transformer
  3. Submit to API

Expected Result

  • Accepted new article

Actual Result

  • Error code as show below
DEBUG - ===========================
DEBUG - 
DEBUG - ===========================
DEBUG - <html lang="en" prefix="op: http://media.facebook.com/op#">

Transformer->loadRules($rules_file) - trying to load rule classes outside the package namespace

I am getting 'Warning: Class .. not found' when using loadRules method. Seems like the try catch block inside loadRules needs to flip the conditions order.

try {
    $factory_method = new \ReflectionMethod($clazz, 'createFrom');
} catch (\ReflectionException $e) {
    $factory_method =
        new \ReflectionMethod(
            'Facebook\\InstantArticles\\Transformer\\Rules\\'.$clazz,
            'createFrom'
        );
}

CDATA XHTML handling

Currently, loadHTML (DOMDocument) does not do anything on parsing cdata and the script content can include CDATA tags. This causes an issue on Elements\GeoTag->isValid() and the code omit script in CDATA even we use the original transform function.

One of the workaround for developers is to write

<script type="text/javascript">
// <![CDATA[
script here
// ]]>
</script>

And this is a typical solution for browsers who cannot understand XHTML.

On the other hand, we can remove '' string from the original content. do you want to do this on SDK in this PR?

This is a side task from #161

Nested div is discarded from transformer.

Steps required to reproduce the problem

  1. Simply use this html snippet with the transformer
<div>First div text</div>
<p>First paragraph text</p>
<div>
  <div>A nested div</div>
  <p>Plus a nested paragraph</p>
</div>

Expected Result

  • Same html as input

Actual Result

  • <p>First div text</p><p>First paragraph text</p>

Notes

I am using facebook-instant-articles-sdk-php within a Drupal 7 website via the fb_instant_articles module, however from what I was able to observe the issue relies in the Transformer class.

Auto-strip empty <p /> tags

A lot of our content has <p>&nbsp;</p> in the content. This is kind of a bad habit of editors to introduce vertical space in an article, but I digress. Also, I've found that loading up HTML to pass to the transformer can also introduce empty <p></p> tags. For example:

$html = '<p><h2>I'm a real title</h2></p>';
$document = new \DOMDocument();
$output = '<!doctype html><html><head><meta charset="utf-8" /></head><body>' . $html . '</body>';
@$document->loadHTML($output);
$transformer->transform($body, $document);

In the output you get:

<p></p>
<h2>I'm a real title</h2>

Of course, this is bad source HTML, headings are not allowed as children of <p>, so we'll look at fixing our source HTML, but here an empty paragraph is allowed to pass through to Facebook, where there is no reason for it in the context of FBIA.

Is there a way that the SDK could strip out empty <p> tags? Or is there a Transformer rule that you can write to strip out empty <p> tags (I've tried this to no avail..)?

Interactive element doesn't support iframe width

The documentation for the Interactive element shows many examples of specifying a width for the iframe, and recommends that you do so: https://developers.facebook.com/docs/instant-articles/reference/interactive

When you save an Instant Article that contains an interactive element with no width, you receive the following warning: "HTML Embeds Require Valid Width: HTML Embeds require a valid integer width in order to be displayed properly."

However, the Interactive element in the SDK (https://github.com/facebook/facebook-instant-articles-sdk-php/blob/master/src/Facebook/InstantArticles/Elements/Interactive.php) does not support the width attribute for the iframe. While the class itself does contain a "width" variable, it is used to set the "no-margin" and "column-width" classes, not the integer width of the iframe.

Add Slideshow to Cover

I told my boss that we cannot add a slideshow to the cover of an Instant Article, based on the documentation I found online & the cover type enforcement in the SDK. Based on these sources, images & video are the only allowable covers.

https://developers.facebook.com/docs/instant-articles/guides/articlecreate#specify-cover
https://developers.facebook.com/docs/instant-articles/reference/cover#options
https://github.com/facebook/facebook-instant-articles-sdk-php/blob/master/src/Facebook/InstantArticles/Elements/Header.php#L103

But he found instant articles with slideshows as covers on Wired.
Wired's code:
https://github.com/whyisjake/Simple-Instant-Articles-for-Facebook/blob/db9651d2c9925b4fb0cced0861fb684fa0528bcd/templates/article-cover.php
An example Wired post with a slideshow cover:
https://www.facebook.com/wired/posts/10153790809838721

If I manually update an instant article, moving the slideshow figure into the header, facebook doesn't throw any errors. Playing with the SDK locally, if I add Slideshow to the allowable types for the cover, the slideshow is added with no issue to the header. If Slideshow's aren't allowed in the header, why don't I get any errors when I manually add them? Is this a fault on Facebook's documentation? Is a slideshow basically an image?

Steps required to reproduce the problem

  1. Try to add a slideshow as a cover:
$instant_article->getHeader()->withCover($slideshow);

Expected Result

  • Slideshow added to the <header>.
    <article>
      <header>
        <figure class="op-slideshow">
          <figure>
            <img src="http://example.com/image1.jpg"/>
            <figcaption>Caption caption caption...</figcaption>
          </figure>
          [...]
      </figure>
      <h1>Example Title</h1>
      [...]         
     </header>
     [...]
  </article>

Actual Result

  • Error
Additional uncaught exception thrown while handling exception.

InvalidArgumentException: Method expects this value ----[ object(Facebook\InstantArticles\Elements\Slideshow)#587 (5) { [...] } ]---- to be one of the types ====[ array(2) { 
[0]=> string(39) "Facebook\InstantArticles\Elements\Image"
 [1]=>string(39) "Facebook\InstantArticles\Elements\Video" 
} ]==== in Facebook\InstantArticles\Validators\Type::throwException() (line 182 of /var/www/drupalvm/sites/all/vendor/facebook/facebook-instant-articles-sdk-php/src/Facebook/InstantArticles/Validators/Type.php).

Multiple Paragraphs in Single Text Submssion

This may be a complete noob question, so forgive me if this is the wrong place to ask. Because our content is coming from a database, the paragraphs are in a single field. For a single paragraph this works great:

        ->addChild(
            Paragraph::create()
                ->appendText($content)
        )

But is there an emelent that will allow multiple paragraphs? I can explode the field into an array but I have no idea how to iterate through to create a Paragraph element for each (foreach loops do not work in the element creation code).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.