From d8118b5b03cd415ff41a895afdd9458ec93c88aa Mon Sep 17 00:00:00 2001
From: Antonio Ospite <ospite@studenti.unina.it>
Date: Fri, 8 Nov 2013 15:01:25 +0100
Subject: [PATCH 1/1] Write error messages on STDERR and return saner values in
 CLI mode

The previous use of die() was not very useful in CLI mode as the script
was always returning 0.

Fix that and also write error messages to the appropriate output stream.

Note the use of 'php://output' as error stream for non CLI mode, this
ensures that error messages would be readable in the browser window.
---
 tweeper.php | 28 +++++++++++++++++++---------
 1 file changed, 19 insertions(+), 9 deletions(-)

diff --git a/tweeper.php b/tweeper.php
index e1483f1..1d50f60 100644
--- a/tweeper.php
+++ b/tweeper.php
@@ -205,7 +205,8 @@ function parse_options_cli($argv, $argc)
       echo usage($argv);
       exit(0);
     default:
-      die(usage($argv));
+      fwrite(STDERR, usage($argv));
+      exit(1);
     }
   }
 
@@ -230,21 +231,30 @@ function parse_options_query_string()
 }
 
 
-if (php_sapi_name() != 'cli')
+if (php_sapi_name() != 'cli') {
   $options = parse_options_query_string();
-else
+  $ERROR_STREAM = fopen('php://output', 'w');
+} else {
   $options = parse_options_cli($argv, $argc);
+  $ERROR_STREAM = fopen('php://stderr', 'w');
+}
 
-if (!isset($options['src_url']))
-  die(usage($argv));
+if (!isset($options['src_url'])) {
+  fwrite($ERROR_STREAM, usage($argv));
+  exit(1);
+}
 
 $url = parse_url($options['src_url']);
-if (FALSE === $url || empty($url["host"]))
-  die("Invalid url: ${options['src_url']}\n");
+if (FALSE === $url || empty($url["host"])) {
+  fwrite($ERROR_STREAM, "Invalid url: ${options['src_url']}\n");
+  exit(1);
+}
 
 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $url["host"] . ".xsl";
-if (FALSE === file_exists($stylesheet))
-  die("Conversion to RSS not supported: {$url["host"]}\n");
+if (FALSE === file_exists($stylesheet)) {
+  fwrite($ERROR_STREAM, "Conversion to RSS not supported: {$url["host"]}\n");
+  exit(1);
+}
 
 $tweeper = new Tweeper($stylesheet, $options['generate_enclosure']);
 echo $tweeper->tweep($options['src_url']);
-- 
2.1.4