File: csv.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (315 lines) | stat: -rw-r--r-- 11,751 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<?php
/**
 * Horde_Data implementation for comma-separated data (CSV).
 *
 * $Horde: framework/Data/Data/csv.php,v 1.30.10.8 2006/01/28 16:21:58 chuck Exp $
 *
 * Copyright 1999-2006 Jan Schneider <jan@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you did
 * not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Jan Schneider <jan@horde.org>
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @since   Horde 1.3
 * @package Horde_Data
 */
class Horde_Data_csv extends Horde_Data {

    var $_extension = 'csv';
    var $_contentType = 'text/comma-separated-values';

    /**
     * Tries to discover the CSV file's parameters.
     *
     * @param string $filename  The name of the file to investigate.
     *
     * @return array  An associative array with the following possible keys:
     * <pre>
     * 'sep':    The field separator
     * 'quote':  The quoting character
     * 'fields': The number of fields (columns)
     * </pre>
     */
    function discoverFormat($filename)
    {
        @include_once('File/CSV.php');
        if (class_exists('File_CSV')) {
            return File_CSV::discoverFormat($filename);
        } else {
            return array('sep' => ',');
        }
    }

    /**
     * Imports and parses a CSV file.
     *
     * @param string $filename  The name of the file to parse.
     * @param boolean $header   Does the first line contain the field/column
     *                          names?
     * @param string $sep       The field/column separator.
     * @param string $quote     The quoting character.
     * @param integer $fields   The number or fields/columns.
     * @param string $charset   The file's charset. @since Horde 3.1.
     * @param string $crlf      The file's linefeed characters. @since Horde 3.1.
     *
     * @return array  A two-dimensional array of all imported data rows.  If
     *                $header was true the rows are associative arrays with the
     *                field/column names as the keys.
     */
    function importFile($filename, $header = false, $sep = '', $quote = '',
                        $fields = null, $import_mapping = array(),
                        $charset = null, $crlf = null)
    {
        @include_once('File/CSV.php');

        $data = array();

        /* File_CSV is present. */
        if (class_exists('File_CSV')) {
            $this->_warnings = array();

            /* File_CSV is a bit picky at what parameter it expects. */
            $conf = array();
            if (!empty($quote)) {
                $conf['quote'] = $quote;
            }
            if (empty($sep)) {
                $conf['sep'] = ',';
            } else {
                $conf['sep'] = $sep;
            }
            if ($fields) {
                $conf['fields'] = $fields;
            } else {
                return $data;
            }
            if (!empty($crlf)) {
                $conf['crlf'] = $crlf;
            }

            /* Strip and keep the first line if it contains the field
             * names. */
            if ($header) {
                $head = File_CSV::read($filename, $conf);
                if (is_a($head, 'PEAR_Error')) {
                    return $head;
                }
                if (!empty($charset)) {
                    $head = String::convertCharset($head, $charset, NLS::getCharset());
                }
            }

            while ($line = File_CSV::read($filename, $conf)) {
                if (is_a($line, 'PEAR_Error')) {
                    return $line;
                }
                if (!empty($charset)) {
                    $line = String::convertCharset($line, $charset, NLS::getCharset());
                }
                if (!isset($head)) {
                    $data[] = $line;
                } else {
                    $newline = array();
                    for ($i = 0; $i < count($head); $i++) {
                        if (isset($import_mapping[$head[$i]])) {
                            $head[$i] = $import_mapping[$head[$i]];
                        }
                        $cell = $line[$i];
                        $cell = preg_replace("/\"\"/", "\"", $cell);
                        $newline[$head[$i]] = empty($cell) ? '' : $cell;
                    }
                    $data[] = $newline;
                }
            }

            $fp = File_CSV::getPointer($filename, $conf);
            if ($fp && !is_a($fp, 'PEAR_Error')) {
                rewind($fp);
            }

            $this->_warnings = File_CSV::warning();

        /* Fall back to fgetcsv(). */
        } else {
            $fp = fopen($filename, 'r');
            if (!$fp) {
                return false;
            }

            /* Strip and keep the first line if it contains the field
               names. */
            if ($header) {
                $head = fgetcsv($fp, 1024, $sep);
            }
            if (!empty($charset)) {
                $head = String::convertCharset($head, $charset, NLS::getCharset());
            }
            while ($line = fgetcsv($fp, 1024, $sep)) {
                if (!empty($charset)) {
                    $line = String::convertCharset($line, $charset, NLS::getCharset());
                }
                if (!isset($head)) {
                    $data[] = $line;
                } else {
                    $newline = array();
                    for ($i = 0; $i < count($head); $i++) {
                        if (isset($import_mapping[$head[$i]])) {
                            $head[$i] = $import_mapping[$head[$i]];
                        }
                        $cell = $line[$i];
                        $cell = preg_replace("/\"/", "\"\"", $cell);
                        $newline[$head[$i]] = empty($cell) ? '' : $cell;
                    }
                    $data[] = $newline;
                }
            }

            fclose($fp);
        }
        return $data;
    }

    /**
     * Builds a CSV file from a given data structure and returns it as a
     * string.
     *
     * @param array $data      A two-dimensional array containing the data set.
     * @param boolean $header  If true, the rows of $data are associative
     *                         arrays with field names as their keys.
     *
     * @return string  The CSV data.
     */
    function exportData($data, $header = false, $export_mapping = array())
    {
        if (!is_array($data) || count($data) == 0) {
            return '';
        }

        $export = '';
        $eol = "\n";
        $head = array_keys(current($data));
        if ($header) {
            foreach ($head as $key) {
                if (!empty($key)) {
                    if (isset($export_mapping[$key])) {
                        $key = $export_mapping[$key];
                    }
                    $export .= '"' . $key . '"';
                }
                $export .= ',';
            }
            $export = substr($export, 0, -1) . $eol;
        }

        foreach ($data as $row) {
            foreach ($head as $key) {
                $cell = $row[$key];
                if (!empty($cell) || $cell === 0) {
                    $export .= '"' . $cell . '"';
                }
                $export .= ',';
            }
            $export = substr($export, 0, -1) . $eol;
        }

        return $export;
    }

    /**
     * Builds a CSV file from a given data structure and triggers its
     * download.  It DOES NOT exit the current script but only outputs the
     * correct headers and data.
     *
     * @param string $filename  The name of the file to be downloaded.
     * @param array $data       A two-dimensional array containing the data
     *                          set.
     * @param boolean $header   If true, the rows of $data are associative
     *                          arrays with field names as their keys.
     */
    function exportFile($filename, $data, $header = false,
                        $export_mapping = array())
    {
        $export = $this->exportData($data, $header, $export_mapping);
        $GLOBALS['browser']->downloadHeaders($filename, 'application/csv', false, strlen($export));
        echo $export;
    }

    /**
     * Takes all necessary actions for the given import step, parameters and
     * form values and returns the next necessary step.
     *
     * @param integer $action  The current step. One of the IMPORT_* constants.
     * @param array $param     An associative array containing needed
     *                         parameters for the current step.
     *
     * @return mixed  Either the next step as an integer constant or imported
     *                data set after the final step.
     */
    function nextStep($action, $param = array())
    {
        switch ($action) {
        case IMPORT_FILE:
            $next_step = parent::nextStep($action, $param);
            if (is_a($next_step, 'PEAR_Error')) {
                return $next_step;
            }

            /* Move uploaded file so that we can read it again in the next
               step after the user gave some format details. */
            $file_name = Horde::getTempFile('import', false);
            if (!move_uploaded_file($_FILES['import_file']['tmp_name'], $file_name)) {
                return PEAR::raiseError(_("The uploaded file could not be saved."));
            }
            $_SESSION['import_data']['file_name'] = $file_name;

            /* Try to discover the file format ourselves. */
            $conf = $this->discoverFormat($file_name);
            if (!$conf) {
                $conf = array('sep' => ',');
            }
            $_SESSION['import_data'] = array_merge($_SESSION['import_data'], $conf);

            /* Check if charset was specified. */
            $_SESSION['import_data']['charset'] = Util::getFormData('charset');

            /* Read the file's first two lines to show them to the user. */
            $_SESSION['import_data']['first_lines'] = '';
            $fp = @fopen($file_name, 'r');
            if ($fp) {
                $line_no = 1;
                while ($line_no < 3 && $line = fgets($fp)) {
                    if (!empty($_SESSION['import_data']['charset'])) {
                        $line = String::convertCharset($line, $_SESSION['import_data']['charset'], NLS::getCharset());
                    }
                    $newline = String::length($line) > 100 ? "\n" : '';
                    $_SESSION['import_data']['first_lines'] .= substr($line, 0, 100) . $newline;
                    $line_no++;
                }
            }
            return IMPORT_CSV;

        case IMPORT_CSV:
            $_SESSION['import_data']['header'] = Util::getFormData('header');
            $import_mapping = array();
            if (isset($param['import_mapping'])) {
                $import_mapping = $param['import_mapping'];
            }
            $import_data = $this->importFile($_SESSION['import_data']['file_name'],
                                             $_SESSION['import_data']['header'],
                                             Util::getFormData('sep'),
                                             Util::getFormData('quote'),
                                             Util::getFormData('fields'),
                                             $import_mapping,
                                             $_SESSION['import_data']['charset'],
                                             $_SESSION['import_data']['crlf']);
            $_SESSION['import_data']['data'] = $import_data;
            unset($_SESSION['import_data']['map']);
            return IMPORT_MAPPED;

        default:
            return parent::nextStep($action, $param);
        }
    }

}