* contact.import.from.csv.php. * * @package core * @author John.meng <*****@*****.**> * @author цот╤РШ * @author QQ:3440895 * @version CVS: $Id: contact.import.from.csv.php,v 1.1 2006/09/27 16:08:53 arzen Exp $ */ define('APF_ROOT_DIR', realpath(dirname(__FILE__) . '/..')); define('APF_DEBUG', true); require_once APF_ROOT_DIR . DIRECTORY_SEPARATOR . 'tools.init.php'; require_once 'File/CSV.php'; require_once $ClassDir . 'StringHelper.class.php'; $header = array("name", "mobile", "phone"); $conf = array('fields' => count($header), 'sep' => ";", 'quote' => '', 'header' => false, 'crlf' => "\r\n"); $file = "D:/nokia_tool/contact.txt"; $csv = new File_CSV(); $conf = File_CSV::discoverFormat($file); $i = 0; while ($fields = File_CSV::read($file, $conf)) { $apf_contact = DB_DataObject::factory('ApfContact'); $j = 0; foreach ($fields as $coloum_data) { $coloum_function = "set" . StringHelper::CamelCaseFromUnderscore($header[$j]); $apf_contact->{$coloum_function}($coloum_data); $j++; } $apf_contact->insert(); $i++; } echo "Import {$i} records;";
/** * The CSV file is parsed here so validation errors can be returned to the * user. The data from a successful parsing is stored in the <var>$CVSDATA</var> * array so it can be accessed by the submit function * * @param Pieform $form The form to validate * @param array $values The values submitted */ function uploadcsv_validate(Pieform $form, $values) { global $CSVDATA, $ALLOWEDKEYS, $FORMAT, $USER; // Don't even start attempting to parse if there are previous errors if ($form->has_errors()) { return; } if ($values['file']['size'] == 0) { $form->set_error('file', $form->i18n('rule', 'required', 'required', array())); return; } require_once 'pear/File.php'; require_once 'pear/File/CSV.php'; // Don't be tempted to use 'explode' here. There may be > 1 underscore. $break = strpos($values['authinstance'], '_'); $authinstance = substr($values['authinstance'], 0, $break); $institution = substr($values['authinstance'], $break + 1); if (!$USER->can_edit_institution($institution)) { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } $usernames = array(); $emails = array(); $conf = File_CSV::discoverFormat($values['file']['tmp_name']); $i = 0; while ($line = File_CSV::readQuoted($values['file']['tmp_name'], $conf)) { $i++; if (!is_array($line)) { // Note: the CSV parser returns true on some errors and false on // others! Yes that's retarded. No I didn't write it :( $form->set_error('file', get_string('uploadcsverrorincorrectnumberoffields', 'admin', $i)); return; } // Get the format of the file if ($i == 1) { foreach ($line as &$potentialkey) { $potentialkey = trim($potentialkey); if (!in_array($potentialkey, $ALLOWEDKEYS)) { $form->set_error('file', get_string('uploadcsverrorinvalidfieldname', 'admin', $potentialkey)); return; } } // Now we know all of the field names are valid, we need to make // sure that the required fields are included $mandatoryfields = array('username', 'password'); $mandatoryfields = array_merge($mandatoryfields, array_keys(ArtefactTypeProfile::get_mandatory_fields())); if ($lockedprofilefields = get_column('institution_locked_profile_field', 'profilefield', 'name', $institution)) { $mandatoryfields = array_merge($mandatoryfields, $lockedprofilefields); } // Add in the locked profile fields for this institution foreach ($mandatoryfields as $field) { if (!in_array($field, $line)) { $form->set_error('file', get_string('uploadcsverrorrequiredfieldnotspecified', 'admin', $field)); return; } } // The format line is valid $FORMAT = $line; log_info('FORMAT:'); log_info($FORMAT); } else { // Trim non-breaking spaces -- they get left in place by File_CSV foreach ($line as &$field) { $field = preg_replace('/^(\\s|\\xc2\\xa0)*(.*?)(\\s|\\xc2\\xa0)*$/', '$2', $field); } // We have a line with the correct number of fields, but should validate these fields // Note: This validation should really be methods on each profile class, that way // it can be used in the profile screen as well. $formatkeylookup = array_flip($FORMAT); $username = $line[$formatkeylookup['username']]; $password = $line[$formatkeylookup['password']]; $email = $line[$formatkeylookup['email']]; $authobj = AuthFactory::create($authinstance); if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($username)) { $form->set_error('file', get_string('uploadcsverrorinvalidusername', 'admin', $i)); return; } if (record_exists_select('usr', 'LOWER(username) = ?', strtolower($username)) || isset($usernames[strtolower($username)])) { $form->set_error('file', get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username)); return; } if (record_exists('usr', 'email', $email) || isset($emails[$email])) { $form->set_error('file', get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email)); } // Note: only checks for valid form are done here, none of the checks // like whether the password is too easy. The user is going to have to // change their password on first login anyway. if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $form->set_error('file', get_string('uploadcsverrorinvalidpassword', 'admin', $i)); return; } $usernames[strtolower($username)] = 1; $emails[$email] = 1; // All OK! $CSVDATA[] = $line; } } if ($i == 1) { // There was only the title row :( $form->set_error('file', get_string('uploadcsverrornorecords', 'admin')); return; } if ($CSVDATA === null) { // Oops! Couldn't get CSV data for some reason $form->set_error('file', get_string('uploadcsverrorunspecifiedproblem', 'admin')); } }
/** * 連想配列の取得 * * <pre> * PHPの連想配列を指定すればそのまま、ファイルパスを指定すれば * 設定ファイルから読み込み連想配列として渡します。 * またURLのクエリー形式も使用できます。 * BEARで広く使われています。BEARの全てのクラスのコンストラクタ * (シングルトン含む)、リソースへの引数、 * オプションにこの連想配列フォーマットが使われます。 * * array -- 連想配列としてオプションが入力されます * * string -- ファイルから拡張子によりフォーマットが異なります * URLクエリー形式 ?foo1=bar1&hoge=fugaのようなフォーマットを連想配列にします * *.ini iniフォーマット * *.xml XMLフォーマット * *.php phpのdefineが連想配列として読み込まれます * *.yml yamlファイル * * $options * 'extention' string オーバーロード拡張子 * </pre> * * @param mixed $target ターゲット ファイルパス,URLなど * @param array $options オプション * * @return array * * @see http://pear.php.net/manual/ja/package.configuration.config.php * @see BEAR/test/files/example.ini * @see BEAR/test/files/example.xml * @see BEAR/test/files/example.php * @throws BEAR_Exception */ public static function loadValues($target, $options = array()) { if (!is_file((string) $target)) { // arrayならそのまま if (is_array($target) || is_object($target)) { return (array) $target; } // false | null なら 設定な if (!$target) { return null; } // クエリーがあるときはクエリーをパースした連想配列を返す $parseUrl = parse_url($target); if (isset($parseUrl['query'])) { $options = array(); parse_str($parseUrl['query'], $options); return $options; } else { return null; } } else { $cache = self::factory('BEAR_Cache'); $cache->setLife(BEAR_Cache::LIFE_UNLIMITED); $key = $target . filemtime($target); $cacheResult = $cache->get($key); if ($cacheResult) { return $cacheResult; } // PEAR::Configを使って設定ファイルをパース $pathinfo = pathinfo($target); // 相対パスなら絶対パスに (/:linux :win) $target = substr($target, 0, 1) == '/' || substr($target, 1, 1) == ':' ? $target : _BEAR_APP_HOME . '/App/Ro/' . $target; $extension = isset($options['extention']) ? $options['extention'] : $pathinfo['extension']; switch ($extension) { case 'yml': if (function_exists('syck_load')) { $content = file_get_contents($target); $yaml = syck_load($content); } else { include_once 'BEAR/vendors/spyc-0.2.5/spyc.php'; $yaml = Spyc::YAMLLoad($target); } $cache->set($key, $yaml); return $yaml; case 'csv': $conf = File_CSV::discoverFormat($target); $csv = array(); while ($fields = File_CSV::read($target, $conf)) { array_push($csv, $fields); } $result = $cache->set($key, $csv); return $csv; case 'ini': $parse = 'inicommented'; break; case 'xml': $unserializer = new XML_Unserializer(); $unserializer->setOption('parseAttributes', true); $xml = file_get_contents($target); $unserializer->unserialize($xml); $result = $unserializer->getUnserializedData(); return $result; break; case 'php': $parse = 'PHPConstants'; break; default: return file_get_contents($target, FILE_TEXT); break; } $config = new Config(); $root =& $config->parseConfig($target, $parse); if (PEAR::isError($root)) { $msg = '設定を読み込む際のエラー: '; $msg .= $root->getMessage(); $info = array('parse' => $parse, 'input' => $target); throw new BEAR_Exception($msg, compact('info')); return false; } else { $result = $root->toArray(); return $result['root']; } } }
<?php /** * var_export(get_class_methods('File_CSV')); * * array ( * 0 => 'raiseError', * 1 => '_conf', * 2 => 'getPointer', * 3 => 'unquote', * 4 => 'readQuoted', * 5 => 'read', * 6 => '_dbgBuff', * 7 => 'write', * 8 => 'discoverFormat', * 9 => 'resetPointer', * ) */ require_once 'File/CSV.php'; $csv = new File_CSV(); $file = 'tests/data/symmetric.csv'; $conf = $csv->discoverFormat($file); foreach (range(0, (int) $conf['fields']) as $iteration) { if ($iteration == 0) { $x = $csv->read($file, $conf); var_export($x); } // rows }