1<?php
2/**
3 * Display quotations
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 * @author     Trailjeep <trailjeep@gmail.com>
8 */
9
10class helper_plugin_jquotes extends DokuWiki_Plugin {
11
12    /**
13     * Get a random cookie properly escaped
14     *
15     * @param string $cookieID the media file id to the cookie file
16     * @param int $maxlines
17     * @return string
18     */
19    static public function getCookieHTML($cookieID) {
20        $cookie = self::getCookie($cookieID);
21
22        return nl2br(hsc($cookie));
23    }
24
25    /**
26     * Get a file for the given ID
27     *
28     * If the ID ends with a colon a namespace is assumed and a random txt file is picked from there
29     *
30     * @param $cookieID
31     * @return string
32     * @throws Exception
33     */
34    static public function id2file($cookieID) {
35        $file = mediaFN($cookieID);
36        if(auth_quickaclcheck($cookieID) < AUTH_READ) throw new Exception("No read permissions for $cookieID");
37        // we now should have a valid file
38        if(!file_exists($file)) throw new Exception("No quotes file at $cookieID");
39
40        return $file;
41    }
42
43    /**
44     * Returns one quotation
45     *
46     * @param string $cookieID the media file id to the cookie file
47     * @return string
48     */
49    static public function getCookie($cookieID) {
50        try {
51            $file = self::id2file($cookieID);
52        } catch(Exception $e) {
53            return 'ERROR: '.$e->getMessage();
54        }
55
56		$jsonFile = file_get_contents($file);
57		//json must already be UTF8
58		$jsonArray = json_decode($jsonFile, true);
59		if (json_last_error() !== 0) return 'JSON error: '.json_last_error_msg();
60		//$i = mt_rand(0, count($jsonArray['quotes']) -1);
61		$i = array_rand($jsonArray['quotes']);
62		$quote = $jsonArray['quotes'][$i]['quote'];
63		$cite = $jsonArray['quotes'][$i]['author'];
64        $text = $quote.'|'.$cite;
65
66        return $text;
67    }
68
69}
70