1 <?php
  2 /**
  3  * @package     Joomla.Platform
  4  * @subpackage  Document
  5  *
  6  * @copyright   Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
  7  * @license     GNU General Public License version 2 or later; see LICENSE
  8  */
  9 
 10 defined('JPATH_PLATFORM') or die;
 11 
 12 /**
 13  * JDocumentJson class, provides an easy interface to parse and display JSON output
 14  *
 15  * @link   http://www.json.org/
 16  * @since  11.1
 17  */
 18 class JDocumentJson extends JDocument
 19 {
 20     /**
 21      * Document name
 22      *
 23      * @var    string
 24      * @since  11.1
 25      */
 26     protected $_name = 'joomla';
 27 
 28     /**
 29      * Class constructor
 30      *
 31      * @param   array  $options  Associative array of options
 32      *
 33      * @since  11.1
 34      */
 35     public function __construct($options = array())
 36     {
 37         parent::__construct($options);
 38 
 39         // Set mime type
 40         if (isset($_SERVER['HTTP_ACCEPT'])
 41             && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') === false
 42             && strpos($_SERVER['HTTP_ACCEPT'], 'text/html') !== false)
 43         {
 44             // Internet Explorer < 10
 45             $this->_mime = 'text/plain';
 46         }
 47         else
 48         {
 49             $this->_mime = 'application/json';
 50         }
 51 
 52         // Set document type
 53         $this->_type = 'json';
 54     }
 55 
 56     /**
 57      * Render the document.
 58      *
 59      * @param   boolean  $cache   If true, cache the output
 60      * @param   array    $params  Associative array of attributes
 61      *
 62      * @return  The rendered data
 63      *
 64      * @since  11.1
 65      */
 66     public function render($cache = false, $params = array())
 67     {
 68         $app = JFactory::getApplication();
 69 
 70         $app->allowCache(false);
 71 
 72         if ($this->_mime == 'application/json')
 73         {
 74             // Browser other than Internet Explorer < 10
 75             $app->setHeader('Content-Disposition', 'attachment; filename="' . $this->getName() . '.json"', true);
 76         }
 77 
 78         parent::render();
 79 
 80         return $this->getBuffer();
 81     }
 82 
 83     /**
 84      * Returns the document name
 85      *
 86      * @return  string
 87      *
 88      * @since  11.1
 89      */
 90     public function getName()
 91     {
 92         return $this->_name;
 93     }
 94 
 95     /**
 96      * Sets the document name
 97      *
 98      * @param   string  $name  Document name
 99      *
100      * @return  JDocumentJSON instance of $this to allow chaining
101      *
102      * @since   11.1
103      */
104     public function setName($name = 'joomla')
105     {
106         $this->_name = $name;
107 
108         return $this;
109     }
110 }
111