1<?php
2
3namespace dokuwiki\plugin\sql2wiki;
4
5class Csv
6{
7    /**
8     * Escapes and wraps the given string
9     *
10     * @param string $str
11     * @return string
12     */
13    static function escape($str) {
14        $backslashes_escaped = str_replace("\\", "\\\\", $str);
15        $nl_escaped = str_replace(["\n", "\r"], ["\\n", "\\r"], $backslashes_escaped);
16        return '"' . htmlspecialchars($nl_escaped, ENT_COMPAT) . '"';
17    }
18
19    /**
20     * Unescapes given string
21     *
22     * @param string $str
23     * @return string
24     */
25    static function unescape($str) {
26        $unescaped_htmlspecialchars = htmlspecialchars_decode($str, ENT_COMPAT);
27        $unescaped_nl = str_replace(["\\n", "\\r"], ["\n", "\r"], $unescaped_htmlspecialchars);
28        $unescaped_backshlashes = str_replace("\\\\", "\\", $unescaped_nl);
29        return $unescaped_backshlashes;
30    }
31
32    /**
33     * Converts two-dimensional array into csv string that can be written to dokuwiki page content.
34     *
35     * @param array $array
36     * @return string
37     */
38    static function arr2csv($array) {
39        $csv = "";
40        foreach ($array as $row) {
41            $csv_row = join(',', array_map('self::escape', $row));
42            $csv .= $csv_row . "\n";
43        }
44        return $csv;
45    }
46
47    /**
48     * Converts csv string to two-dimensional array.
49     *
50     * @param string $csv
51     * @return array
52     */
53
54    static function csv2arr($csv) {
55        $lines = array_values(array_filter(preg_split('/\r\n|\r|\n/', $csv)));
56        $array = array_map('str_getcsv', $lines);
57        $unescaped_array = array_map(function ($row) {
58            return array_map('self::unescape', $row);
59        }, $array);
60        return $unescaped_array;
61    }
62}