src/Tweeper.php: make code more robust by properly check return values
[tweeper.git] / src / Tweeper.php
index 831f47d..22d16ab 100644 (file)
@@ -39,10 +39,18 @@ class Tweeper {
   private static $userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0";
 
   /**
-   * Constructor sets up {@link $generate_enclosure}.
+   * Create a new Tweeper object controlling optional settings.
+   *
+   * @param bool $generate_enclosure
+   *   Enables the creation of <enclosure/> elements (disabled by default).
+   * @param bool $show_usernames
+   *   Enables showing the username in front of the content for multi-user
+   *   sites (enabled by default). Only some stylesheets supports this
+   *   functionality (twitter, instagram, pump.io).
    */
-  public function __construct($generate_enclosure = FALSE) {
+  public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE) {
     $this->generate_enclosure = $generate_enclosure;
+    $this->show_usernames = $show_usernames;
   }
 
   /**
@@ -116,7 +124,14 @@ class Tweeper {
       CURLOPT_SSL_VERIFYPEER => FALSE,
       CURLOPT_USERAGENT => Tweeper::$userAgent,
     ));
-    curl_exec($ch);
+
+    $ret = curl_exec($ch);
+    if (FALSE === $ret) {
+      trigger_error(curl_error($ch));
+      curl_close($ch);
+      return FALSE;
+    }
+
     $url_info = curl_getinfo($ch);
     if (FALSE === $url_info) {
       trigger_error(curl_error($ch));
@@ -152,6 +167,10 @@ class Tweeper {
     );
 
     $url_info = Tweeper::getUrlInfo($url);
+    if (FALSE === $url_info) {
+      error_log("Failed to retrieve info for URL: " . $url);
+      return '';
+    }
 
     $supported = in_array($url_info['content_type'], $supported_content_types);
     if (!$supported) {
@@ -255,6 +274,10 @@ class Tweeper {
     // element names, so remove it.
     unset($data["qe"]);
 
+    // The "knobs" object contains elements with undefined namespaces, so
+    // remove it to silence an error message.
+    unset($data["knobs"]);
+
     $json = json_encode($data);
 
     return Tweeper::jsonToXml($json, 'instagram');
@@ -308,6 +331,9 @@ class Tweeper {
     }
 
     $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
+    if (FALSE === $stylesheet_contents) {
+      return NULL;
+    }
 
     $xslDoc = new DOMDocument();
     $xslDoc->loadXML($stylesheet_contents);
@@ -315,6 +341,7 @@ class Tweeper {
     $xsltProcessor = new XSLTProcessor();
     $xsltProcessor->registerPHPFunctions();
     $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
+    $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
     $xsltProcessor->importStylesheet($xslDoc);
 
     return $xsltProcessor;