Skip to content
Snippets Groups Projects
class.import.php 6.37 KiB
<?php
/*********************************************************************
    class.import.php

    Utilities for importing objects and data (usually via CSV)

    Peter Rotich <peter@osticket.com>
    Jared Hancock <jared@osticket.com>
    Copyright (c)  2006-2015 osTicket
    http://www.osticket.com

    Released under the GNU General Public License WITHOUT ANY WARRANTY.
    See LICENSE.TXT for details.

    vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/

class ImportError extends Exception {}
class ImportDataError extends ImportError {}

class CsvImporter {
    var $stream;

    function __construct($stream) {
        // File upload
        if (is_array($stream) && !$stream['error']) {
            // Properly detect Macintosh style line endings
            ini_set('auto_detect_line_endings', true);
            $this->stream = fopen($stream['tmp_name'], 'r');
        }
        // Open file
        elseif (is_resource($stream)) {
            $this->stream = $stream;
        }
        // Text from standard-in
        elseif (is_string($stream)) {
            $this->stream = fopen('php://temp', 'w+');
            fwrite($this->stream, $stream);
            rewind($this->stream);
        }
        else {
            throw new ImportError(__('Unable to parse submitted csv: ').print_r($stream, true));
        }
    }

    function __destruct() {
        fclose($this->stream);
    }

    function importCsv($all_fields=array(), $defaults=array()) {
        $named_fields = array();
        $has_header = true;
        foreach ($all_fields as $f)
            if ($f->get('name'))
                $named_fields[$f->get('name')] = $f;

        // Read the first row and see if it is a header or not
        if (!($data = fgetcsv($this->stream, 1000, ",")))
            throw new ImportError(__('Whoops. Perhaps you meant to send some CSV records'));

        $headers = array();
        foreach ($data as $h) {
            $h = trim($h);
            $found = false;
            foreach ($all_fields as $f) {
                if (in_array(mb_strtolower($h), array(
                        mb_strtolower($f->get('name')), mb_strtolower($f->get('label'))))) {
                    $found = true;
                    if (!$f->get('name'))
                        throw new ImportError(sprintf(__(