3 * Library for CSV serialization.
5 * This is used by the csv/proxy driver and is the CacheExecute()
6 * serialization format.
8 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
11 * @link https://adodb.org Project's web site and documentation
12 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
14 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
15 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
16 * any later version. This means you can use it in proprietary products.
17 * See the LICENSE.md file distributed with this source code for details.
18 * @license BSD-3-Clause
19 * @license LGPL-2.1-or-later
21 * @copyright 2000-2013 John Lim
22 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
25 // security - hide paths
26 if (!defined('ADODB_DIR')) die();
28 global $ADODB_INCLUDED_CSV;
29 $ADODB_INCLUDED_CSV = 1;
32 * convert a recordset into special format
34 * @param rs the recordset
36 * @return the CSV formatted data
38 function _rs2serialize(&$rs,$conn=false,$sql='')
40 $max = ($rs) ?
$rs->FieldCount() : 0;
42 if ($sql) $sql = urlencode($sql);
45 if ($max <= 0 ||
$rs->dataProvider
== 'empty') { // is insert/update/delete
46 if (is_object($conn)) {
47 $sql .= ','.$conn->Affected_Rows();
48 $sql .= ','.$conn->Insert_ID();
52 $text = "====-1,0,$sql\n";
55 $tt = ($rs->timeCreated
) ?
$rs->timeCreated
: time();
57 ## changed format from ====0 to ====1
58 $line = "====1,$tt,$sql\n";
60 if ($rs->databaseType
== 'array') {
65 $rows[] = $rs->fields
;
70 for($i=0; $i < $max; $i++
) {
71 $o = $rs->FetchField($i);
75 $savefetch = isset($rs->adodbFetchMode
) ?
$rs->adodbFetchMode
: $rs->fetchMode
;
76 $class = $rs->connection
->arrayClass
;
78 $rs2->timeCreated
= $rs->timeCreated
; # memcache fix
80 $rs2->oldProvider
= $rs->dataProvider
;
81 $rs2->InitArrayFields($rows,$flds);
82 $rs2->fetchMode
= $savefetch;
83 return $line.serialize($rs2);
88 * Open CSV file and convert it into Data.
90 * @param url file/ftp/http url
91 * @param err returns the error message
92 * @param timeout dispose if recordset has been alive for $timeout secs
94 * @return recordset, or false if error occurred. If no
95 * error occurred in sql INSERT/UPDATE/DELETE,
96 * empty recordset is returned
98 function csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
102 $fp = @fopen
($url,'rb');
104 $err = $url.' file/URL not found';
107 @flock
($fp, LOCK_SH
);
111 if ($meta = fgetcsv($fp, 32000, ",")) {
112 // check if error message
113 if (strncmp($meta[0],'****',4) === 0) {
114 $err = trim(substr($meta[0],4,1024));
118 // check for meta data
119 // $meta[0] is -1 means return an empty recordset
120 // $meta[1] contains a time
122 if (strncmp($meta[0], '====',4) === 0) {
124 if ($meta[0] == "====-1") {
125 if (sizeof($meta) < 5) {
126 $err = "Corrupt first line for format -1";
133 $err = " Illegal Timeout $timeout ";
137 $rs = new $rsclass($val=true);
138 $rs->fields
= array();
139 $rs->timeCreated
= $meta[1];
141 $rs->_numOfFields
= 0;
142 $rs->sql
= urldecode($meta[2]);
143 $rs->affectedrows
= (integer)$meta[3];
144 $rs->insertid
= $meta[4];
147 # Under high volume loads, we want only 1 thread/process to _write_file
148 # so that we don't have 50 processes queueing to write the same data.
149 # We use probabilistic timeout, ahead of time.
151 # -4 sec before timeout, give processes 1/32 chance of timing out
152 # -2 sec before timeout, give processes 1/16 chance of timing out
153 # -1 sec after timeout give processes 1/4 chance of timing out
154 # +0 sec after timeout, give processes 100% chance of timing out
155 if (sizeof($meta) > 1) {
157 $tdiff = (integer)( $meta[1]+
$timeout - time());
162 if ((rand() & 31) == 0) {
169 if ((rand() & 15) == 0) {
176 if ((rand() & 3) == 0) {
188 } // if check flush cache
192 //================================================
193 // new cache format - use serialize extensively...
194 if ($meta[0] === '====1') {
198 $text = fread($fp,$MAXSIZE);
200 while ($txt = fread($fp,$MAXSIZE)) {
205 $rs = unserialize($text);
206 if (is_object($rs)) $rs->timeCreated
= $ttl;
208 $err = "Unable to unserialize recordset";
209 //echo htmlspecialchars($text),' !--END--!<p>';
215 $meta = fgetcsv($fp, 32000, ",");
218 $err = "Unexpected EOF 1";
223 // Get Column definitions
225 foreach($meta as $o) {
226 $o2 = explode(':',$o);
227 if (sizeof($o2)!=3) {
232 $fld = new ADOFieldObject();
233 $fld->name
= urldecode($o2[0]);
235 $fld->max_length
= $o2[2];
240 $err = "Recordset had unexpected EOF 2";
248 while ($txt = fread($fp,$MAXSIZE)) {
253 @$arr = unserialize($text);
254 if (!is_array($arr)) {
255 $err = "Recordset had unexpected EOF (in serialized recordset)";
258 $rs = new $rsclass();
259 $rs->timeCreated
= $ttl;
260 $rs->InitArrayFields($arr,$flds);
266 * Save a file $filename and its $contents (normally for caching) with file locking
267 * Returns true if ok, false if fopen/fwrite error, 0 if rename error (eg. file is locked)
269 function adodb_write_file($filename, $contents,$debug=false)
271 # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
272 # So to simulate locking, we assume that rename is an atomic operation.
273 # First we delete $filename, then we create a $tempfile write to it and
274 # rename to the desired $filename. If the rename works, then we successfully
275 # modified the file exclusively.
276 # What a stupid need - having to simulate locking.
278 # 1. $tempfile name is not unique -- very very low
279 # 2. unlink($filename) fails -- ok, rename will fail
280 # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
281 # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
282 if (strncmp(PHP_OS
,'WIN',3) === 0) {
283 // skip the decimal place
284 $mtime = substr(str_replace(' ','_',microtime()),2);
285 // getmypid() actually returns 0 on Win98 - never mind!
286 $tmpname = $filename.uniqid($mtime).getmypid();
287 if (!($fd = @fopen
($tmpname,'w'))) return false;
288 if (fwrite($fd,$contents)) $ok = true;
293 @chmod
($tmpname,0644);
296 if (!@rename
($tmpname,$filename)) {
301 if ($debug) ADOConnection
::outp( " Rename $tmpname ".($ok?
'ok' : 'failed'));
306 if (!($fd = @fopen
($filename, 'a'))) return false;
307 if (flock($fd, LOCK_EX
) && ftruncate($fd, 0)) {
308 if (fwrite( $fd, $contents )) $ok = true;
311 @chmod
($filename,0644);
314 if ($debug)ADOConnection
::outp( " Failed acquiring lock for $filename<br>\n");