This repository was archived by the owner on Feb 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathgridfs.c
1270 lines (1039 loc) · 35.1 KB
/
gridfs.c
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2009-2014 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <php.h>
#include <php_globals.h>
#include <zend_exceptions.h>
#include <ext/standard/php_smart_str.h>
#include "../php_mongo.h"
#include "../collection.h"
#include "../cursor.h"
#include "../cursor_shared.h"
#include "../db.h"
#include "gridfs_cursor.h"
#include "gridfs_file.h"
#include "../types/bin_data.h"
#include "../types/date.h"
#include "../types/id.h"
ZEND_EXTERN_MODULE_GLOBALS(mongo)
extern zend_class_entry *mongo_ce_BinData;
extern zend_class_entry *mongo_ce_Collection;
extern zend_class_entry *mongo_ce_Date;
extern zend_class_entry *mongo_ce_DB;
extern zend_class_entry *mongo_ce_Exception;
extern zend_class_entry *mongo_ce_GridFSCursor;
extern zend_class_entry *mongo_ce_GridFSException;
extern zend_class_entry *mongo_ce_GridFSFile;
extern zend_class_entry *mongo_ce_Id;
zend_class_entry *mongo_ce_GridFS = NULL;
typedef struct {
FILE *file;
int fd; /* underlying file descriptor */
unsigned is_process_pipe:1; /* use pclose instead of fclose */
unsigned is_pipe:1; /* don't try and seek */
unsigned cached_fstat:1; /* sb is valid */
unsigned _reserved:29;
int lock_flag; /* stores the lock state */
char *temp_file_name; /* if non-null, this is the path to a temporary file that
* is to be deleted when the stream is closed */
#if HAVE_FLUSHIO
char last_op;
#endif
#if HAVE_MMAP
char *last_mapped_addr;
size_t last_mapped_len;
#endif
#ifdef PHP_WIN32
char *last_mapped_addr;
HANDLE file_mapping;
#endif
struct stat sb;
} php_stdio_stream_data;
static int setup_file_fields(zval *zfile, char *filename, long size TSRMLS_DC);
static zval* insert_chunk(zval *chunks, zval *zid, int chunk_num, char *buf, int chunk_size, zval *options TSRMLS_DC);
/* {{{ proto MongoGridFS::__construct(MongoDB db [, string prefix = "fs"])
Creates a new MongoGridFS object */
PHP_METHOD(MongoGridFS, __construct)
{
zval *zdb, *files = NULL, *chunks = NULL, *zchunks;
zval *z_w = NULL;
/* chunks is deprecated */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|zz", &zdb, mongo_ce_DB, &files, &chunks) == FAILURE) {
zval *object = getThis();
ZVAL_NULL(object);
return;
}
if (chunks) {
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'chunks' argument is deprecated and ignored");
}
if (files) {
zval *temp_file;
char *temp;
if (Z_TYPE_P(files) != IS_STRING || Z_STRLEN_P(files) == 0 ) {
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 2 TSRMLS_CC, "MongoGridFS::__construct(): invalid prefix");
return;
}
MAKE_STD_ZVAL(chunks);
spprintf(&temp, 0, "%s.chunks", Z_STRVAL_P(files));
ZVAL_STRING(chunks, temp, 0);
MAKE_STD_ZVAL(temp_file);
spprintf(&temp, 0, "%s.files", Z_STRVAL_P(files));
ZVAL_STRING(temp_file, temp, 0);
files = temp_file;
} else {
MAKE_STD_ZVAL(files);
ZVAL_STRING(files, "fs.files", 1);
MAKE_STD_ZVAL(chunks);
ZVAL_STRING(chunks, "fs.chunks", 1);
}
/* create files collection */
MONGO_METHOD2(MongoCollection, __construct, return_value, getThis(), zdb, files);
/* create chunks collection */
MAKE_STD_ZVAL(zchunks);
object_init_ex(zchunks, mongo_ce_Collection);
MONGO_METHOD2(MongoCollection, __construct, return_value, zchunks, zdb, chunks);
/* add chunks collection as a property */
zend_update_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), zchunks TSRMLS_CC);
zend_update_property(mongo_ce_GridFS, getThis(), "filesName", strlen("filesName"), files TSRMLS_CC);
zend_update_property(mongo_ce_GridFS, getThis(), "chunksName", strlen("chunksName"), chunks TSRMLS_CC);
/* GridFS is forced in our codebase to be w=1 so this property doesn't actually mean
* anything, but we can't lie to the user so we have to overwrite it if the MongoDB
* object that created this object was w=0.
* This property is initialized in the MongoCollection (which we extend) ctor */
z_w = zend_read_property(mongo_ce_GridFS, getThis(), "w", strlen("w"), NOISY TSRMLS_CC);
if (Z_TYPE_P(z_w) != IS_STRING) {
convert_to_long(z_w);
if (Z_LVAL_P(z_w) < 2) {
zend_update_property_long(mongo_ce_GridFS, getThis(), "w", strlen("w"), 1 TSRMLS_CC);
}
}
/* cleanup */
zval_ptr_dtor(&zchunks);
zval_ptr_dtor(&files);
zval_ptr_dtor(&chunks);
}
/* }}} */
void php_mongo_ensure_gridfs_index(zval *return_value, zval *this_ptr TSRMLS_DC)
{
zval *index, *options;
/* ensure unique index on chunks collection's "files_id" and "n" fields */
MAKE_STD_ZVAL(index);
array_init(index);
add_assoc_long(index, "files_id", 1);
add_assoc_long(index, "n", 1);
MAKE_STD_ZVAL(options);
array_init(options);
add_assoc_bool(options, "unique", 1);
MONGO_METHOD2(MongoCollection, ensureIndex, return_value, getThis(), index, options);
zval_ptr_dtor(&index);
zval_ptr_dtor(&options);
}
/* {{{ proto array MongoGridFS::drop()
Drops the files and chunks collections */
PHP_METHOD(MongoGridFS, drop)
{
zval *temp;
zval *zchunks = zend_read_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), NOISY TSRMLS_CC);
MAKE_STD_ZVAL(temp);
MONGO_METHOD(MongoCollection, drop, temp, zchunks);
zval_ptr_dtor(&temp);
MONGO_METHOD(MongoCollection, drop, return_value, getThis());
}
/* }}} */
/* {{{ proto MongoGridFSCursor MongoGridFS::find([array|object query = array() [, array fields = array()]])
Queries for files */
PHP_METHOD(MongoGridFS, find)
{
zval temp;
zval *zquery = 0, *zfields = 0;
mongo_collection *c;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &zquery, &zfields) == FAILURE) {
return;
}
MUST_BE_ARRAY_OR_OBJECT(1, zquery);
MUST_BE_ARRAY_OR_OBJECT(2, zfields);
if (!zquery) {
MAKE_STD_ZVAL(zquery);
array_init(zquery);
} else {
zval_add_ref(&zquery);
}
if (!zfields) {
MAKE_STD_ZVAL(zfields);
array_init(zfields);
} else {
zval_add_ref(&zfields);
}
object_init_ex(return_value, mongo_ce_GridFSCursor);
c = (mongo_collection*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(c->ns, MongoGridFS);
MONGO_METHOD5(MongoGridFSCursor, __construct, &temp, return_value, getThis(), c->link, c->ns, zquery, zfields);
zval_ptr_dtor(&zquery);
zval_ptr_dtor(&zfields);
}
/* }}} */
static long get_chunk_size(zval *array TSRMLS_DC)
{
zval **zchunk_size = 0;
if (zend_hash_find(HASH_P(array), "chunkSize", strlen("chunkSize") + 1, (void**)&zchunk_size) == FAILURE) {
add_assoc_long(array, "chunkSize", MonGlo(chunk_size));
return MonGlo(chunk_size);
}
convert_to_long(*zchunk_size);
return Z_LVAL_PP(zchunk_size) > 0 ? Z_LVAL_PP(zchunk_size) : MonGlo(chunk_size);
}
static long setup_file(FILE *fp, char *filename TSRMLS_DC)
{
long size = 0;
/* try to open the file */
if (!fp) {
zend_throw_exception_ex(mongo_ce_GridFSException, 3 TSRMLS_CC, "could not open file %s", filename);
return FAILURE;
}
/* get size */
fseek(fp, 0, SEEK_END);
size = ftell(fp);
if (size == -1) {
zend_throw_exception_ex(mongo_ce_GridFSException, 4 TSRMLS_CC, "file %s is too large: %ld bytes", filename, size);
fclose(fp);
return FAILURE;
}
/* reset file ptr */
fseek(fp, 0, SEEK_SET);
return size;
}
static zval* setup_extra(zval *zfile, zval *extra TSRMLS_DC)
{
zval *zid = 0;
zval **zzid = 0;
array_init(zfile);
/* add user-defined fields */
if (extra) {
zval temp;
zend_hash_merge(HASH_P(zfile), Z_ARRVAL_P(extra), (void (*)(void*))zval_add_ref, &temp, sizeof(zval*), 1);
}
/* check if we need to add any fields */
/* _id */
if (zend_hash_find(HASH_P(zfile), "_id", strlen("_id") + 1, (void**)&zzid) == FAILURE) {
/* create an id for the file */
MAKE_STD_ZVAL(zid);
object_init_ex(zid, mongo_ce_Id);
php_mongo_mongoid_populate(zid, NULL TSRMLS_CC);
add_assoc_zval(zfile, "_id", zid);
} else {
zid = *zzid;
}
return zid;
}
/* Use the db command to get the md5 hash of the inserted chunks
*
* $db->command(array(filemd5 => $fileId, "root" => $ns));
*
* adds the response to zfile as the "md5" field. */
static void add_md5(zval *zfile, zval *zid, mongo_collection *c TSRMLS_DC)
{
if (!zend_hash_exists(HASH_P(zfile), "md5", strlen("md5") + 1)) {
zval *cmd = 0, *response = 0, **md5 = 0;
mongo_db *db = (mongo_db*)zend_object_store_get_object(c->parent TSRMLS_CC);
/* get the prefix */
int prefix_len = strchr(Z_STRVAL_P(c->name), '.') - Z_STRVAL_P(c->name);
char *prefix = estrndup(Z_STRVAL_P(c->name), prefix_len);
if (!db->name) {
zend_throw_exception(mongo_ce_Exception, "The MongoGridFS object has not been correctly initialized by its constructor", 0 TSRMLS_CC);
return;
}
/* create command */
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_zval(cmd, "filemd5", zid);
zval_add_ref(&zid);
add_assoc_stringl(cmd, "root", prefix, prefix_len, 0);
/* run command */
response = php_mongo_runcommand(db->link, &db->read_pref, Z_STRVAL_P(db->name), Z_STRLEN_P(db->name), cmd, NULL, 0, NULL TSRMLS_CC);
zval_ptr_dtor(&cmd);
if (!response) {
return;
}
/* make sure there wasn't an error */
if (zend_hash_find(HASH_P(response), "md5", strlen("md5") + 1, (void**)&md5) == SUCCESS) {
add_assoc_zval(zfile, "md5", *md5);
/* Increment the refcount so it isn't cleaned up at the end of this
* method */
zval_add_ref(md5);
}
/* cleanup */
zval_ptr_dtor(&response);
}
}
static void gridfs_rewrite_cursor_exception(TSRMLS_D)
{
char *message = NULL;
long code = 0;
smart_str tmp_message = { NULL, 0, 0 };
if (EG(exception)) {
message = estrdup(Z_STRVAL_P(zend_read_property(mongo_ce_GridFSException, EG(exception), "message", strlen("message"), NOISY TSRMLS_CC)));
code = Z_LVAL_P(zend_read_property(mongo_ce_GridFSException, EG(exception), "code", strlen("code"), NOISY TSRMLS_CC));
zend_clear_exception(TSRMLS_C);
}
/* create the message for the exception */
if (message) {
smart_str_appends(&tmp_message, "Could not store file: ");
smart_str_appends(&tmp_message, message);
smart_str_0(&tmp_message);
efree(message);
} else {
smart_str_appends(&tmp_message, "Could not store file for unknown reasons");
smart_str_0(&tmp_message);
}
zend_throw_exception(mongo_ce_GridFSException, tmp_message.c, code TSRMLS_CC);
smart_str_free(&tmp_message);
}
static void cleanup_stale_chunks(INTERNAL_FUNCTION_PARAMETERS, zval *cleanup_ids)
{
zval *chunks, *temp_return;
zval **tmp;
HashPosition pos;
zval *tmp_exception;
if (EG(exception)) {
tmp_exception = EG(exception);
EG(exception) = NULL;
}
chunks = zend_read_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), NOISY TSRMLS_CC);
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(cleanup_ids), &pos);
while (zend_hash_get_current_data_ex(Z_ARRVAL_P(cleanup_ids), (void **) &tmp, &pos) == SUCCESS) {
zval *query, *cid;
MAKE_STD_ZVAL(query);
MAKE_STD_ZVAL(cid);
array_init(query);
MAKE_COPY_ZVAL(tmp, cid);
add_assoc_zval(query, "_id", cid);
MAKE_STD_ZVAL(temp_return);
ZVAL_NULL(temp_return);
MONGO_METHOD1(MongoCollection, remove, temp_return, chunks, query);
zend_hash_move_forward_ex(Z_ARRVAL_P(cleanup_ids), &pos);
zval_ptr_dtor(&temp_return);
zval_ptr_dtor(&query);
}
if (tmp_exception) {
EG(exception) = tmp_exception;
}
RETVAL_FALSE;
}
/* {{{ proto mixed MongoGridFS::storeBytes(string bytes [, array|object metadata = array() [, array options = array()]])
Stores a string of bytes in the database */
PHP_METHOD(MongoGridFS, storeBytes)
{
char *bytes = 0;
int bytes_len = 0, chunk_num = 0;
long global_chunk_size = 0, pos = 0;
int revert = 0;
zval temp;
zval *extra = 0, *zid = 0, *zfile = 0, *chunks = 0, *options = 0;
zval *cleanup_ids;
zval *chunk_id = NULL;
mongo_db *db;
mongo_collection *c = (mongo_collection*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(c->ns, MongoGridFS);
PHP_MONGO_GET_DB(c->parent);
chunks = zend_read_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), NOISY TSRMLS_CC);
php_mongo_ensure_gridfs_index(&temp, chunks TSRMLS_CC);
zval_dtor(&temp);
/* Abort if we could not create the unique index on fs.chunks */
if (EG(exception)) {
gridfs_rewrite_cursor_exception(TSRMLS_C);
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|aa/", &bytes, &bytes_len, &extra, &options) == FAILURE) {
return;
}
MAKE_STD_ZVAL(cleanup_ids);
array_init(cleanup_ids);
/* file array object */
MAKE_STD_ZVAL(zfile);
/* merge extra & zfile and add _id if needed */
zid = setup_extra(zfile, extra TSRMLS_CC);
setup_file_fields(zfile, NULL, (long) bytes_len TSRMLS_CC);
/* chunkSize */
global_chunk_size = get_chunk_size(zfile TSRMLS_CC);
/* size */
if (!zend_hash_exists(HASH_P(zfile), "length", strlen("length") + 1)) {
add_assoc_long(zfile, "length", bytes_len);
}
/* options */
if (!options) {
zval *opts;
MAKE_STD_ZVAL(opts);
array_init(opts);
options = opts;
} else {
zval_add_ref(&options);
}
/* insert chunks */
while (pos < bytes_len) {
size_t chunk_size = bytes_len - pos >= global_chunk_size ? global_chunk_size : bytes_len - pos;
if (!(chunk_id = insert_chunk(chunks, zid, chunk_num, bytes + pos, chunk_size, options TSRMLS_CC))) {
revert = 1;
goto cleanup_on_failure;
}
/* Keep track of that successfully inserted chunk id */
add_next_index_zval(cleanup_ids, chunk_id);
if (EG(exception)) {
revert = 1;
goto cleanup_on_failure;
}
/* increment counters */
pos += chunk_size;
chunk_num++;
}
/* Run GLE, just to ensure all the data has been written */
{
zval *cmd, *gle_retval;
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_long(cmd, "getlasterror", 1);
/* run command */
gle_retval = php_mongo_runcommand(c->link, &c->read_pref, Z_STRVAL_P(db->name), Z_STRLEN_P(db->name), cmd, NULL, 0, NULL TSRMLS_CC);
zval_ptr_dtor(&cmd);
if (!gle_retval) {
revert = 1;
goto cleanup_on_failure;
}
if (Z_TYPE_P(gle_retval) == IS_ARRAY) {
zval **err;
if (zend_hash_find(Z_ARRVAL_P(gle_retval), "err", strlen("err") + 1, (void**)&err) == SUCCESS && Z_TYPE_PP(err) == IS_STRING) {
zend_throw_exception_ex(mongo_ce_GridFSException, 0 TSRMLS_CC, Z_STRVAL_PP(err));
/* Intentionally not returning, the exception is checked a line later */
}
}
zval_ptr_dtor(&gle_retval);
if (EG(exception)) {
goto cleanup_on_failure;
}
}
/* now that we've inserted the chunks, use them to calculate the hash */
add_md5(zfile, zid, c TSRMLS_CC);
/* Insert file */
MONGO_METHOD2(MongoCollection, insert, &temp, getThis(), zfile, options);
zval_dtor(&temp);
if (EG(exception)) {
revert = 1;
}
cleanup_on_failure:
if (revert) {
/* Cleanup any created chunks from the chunks collection */
/* If the insert into the files collection fails, it fails - and nothing to cleanup there anyway */
cleanup_stale_chunks(INTERNAL_FUNCTION_PARAM_PASSTHRU, cleanup_ids);
gridfs_rewrite_cursor_exception(TSRMLS_C);
RETVAL_FALSE;
} else {
RETVAL_ZVAL(zid, 1, 0);
}
zval_ptr_dtor(&zfile);
zval_ptr_dtor(&options);
zval_ptr_dtor(&cleanup_ids);
}
/* }}} */
/* add extra fields required for files:
* - filename
* - upload date
* - length
* these fields are only added if the user hasn't defined them. */
static int setup_file_fields(zval *zfile, char *filename, long length TSRMLS_DC)
{
/* filename */
if (filename && !zend_hash_exists(HASH_P(zfile), "filename", strlen("filename") + 1)) {
add_assoc_stringl(zfile, "filename", filename, strlen(filename), DUP);
}
/* uploadDate */
if (!zend_hash_exists(HASH_P(zfile), "uploadDate", strlen("uploadDate") + 1)) {
zval *upload_date;
long sec, usec;
MAKE_STD_ZVAL(upload_date);
object_init_ex(upload_date, mongo_ce_Date);
php_mongo_mongodate_make_now(&sec, &usec);
php_mongo_mongodate_populate(upload_date, sec, usec TSRMLS_CC);
add_assoc_zval(zfile, "uploadDate", upload_date);
}
/* length */
if (!zend_hash_exists(HASH_P(zfile), "length", strlen("length") + 1)) {
add_assoc_long(zfile, "length", length);
}
return SUCCESS;
}
/* Creates a chunk and adds it to the chunks collection as:
* array(3) {
* files_id => zid
* n => chunk_num
* data => MongoBinData(buf, chunk_size, type 2)
* }
*
* Clean up should leave:
* - 1 ref to zid
* - buf */
static zval* insert_chunk(zval *chunks, zval *zid, int chunk_num, char *buf, int chunk_size, zval *options TSRMLS_DC) {
zval temp;
zval *zchunk, *zbin, *zretval = NULL;
zval **_id;
/* create chunk */
MAKE_STD_ZVAL(zchunk);
array_init(zchunk);
add_assoc_zval(zchunk, "files_id", zid);
zval_add_ref(&zid); /* zid->refcount = 2 */
add_assoc_long(zchunk, "n", chunk_num);
/* create MongoBinData object */
MAKE_STD_ZVAL(zbin);
object_init_ex(zbin, mongo_ce_BinData);
zend_update_property_stringl(mongo_ce_BinData, zbin, "bin", strlen("bin"), buf, chunk_size TSRMLS_CC);
zend_update_property_long(mongo_ce_BinData, zbin, "type", strlen("type"), 2 TSRMLS_CC);
add_assoc_zval(zchunk, "data", zbin);
/* insert chunk */
if (options) {
MONGO_METHOD2(MongoCollection, insert, &temp, chunks, zchunk, options);
} else {
MONGO_METHOD1(MongoCollection, insert, &temp, chunks, zchunk);
}
if (zend_hash_find(Z_ARRVAL_P(zchunk), "_id", strlen("_id") + 1, (void**)&_id) == SUCCESS) {
MAKE_STD_ZVAL(zretval);
ZVAL_ZVAL(zretval, *_id, 1, 0);
}
zval_dtor(&temp);
/* increment counters */
zval_ptr_dtor(&zchunk); /* zid->refcount = 1 */
if (!zretval) {
return NULL;
}
if (EG(exception)) {
zval_ptr_dtor(&zretval);
return NULL;
}
return zretval;
}
/* {{{ proto mixed MongoGridFS::storeFile(string|resource filename [, array metadata = array() [, array options = array()]])
Stores a file in the database */
PHP_METHOD(MongoGridFS, storeFile)
{
zval *fh, *extra = 0, *options = 0;
char *filename = 0;
int chunk_num = 0, fd = -1;
long global_chunk_size = 0, size = 0, pos = 0;
int revert = 0;
FILE *fp = 0;
zval temp;
zval *zid = 0, *zfile = 0, *chunks = 0;
zval *cleanup_ids;
mongo_db *db;
mongo_collection *c = (mongo_collection*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(c->ns, MongoGridFS);
PHP_MONGO_GET_DB(c->parent);
chunks = zend_read_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), NOISY TSRMLS_CC);
php_mongo_ensure_gridfs_index(&temp, chunks TSRMLS_CC);
zval_dtor(&temp);
/* Abort if we could not create the unique index on fs.chunks */
if (EG(exception)) {
gridfs_rewrite_cursor_exception(TSRMLS_C);
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|aa/", &fh, &extra, &options) == FAILURE) {
return;
}
if (Z_TYPE_P(fh) == IS_RESOURCE) {
zend_rsrc_list_entry *le;
php_stdio_stream_data *stdio_fptr = 0;
if (zend_hash_index_find(&EG(regular_list), Z_LVAL_P(fh), (void **) &le) == SUCCESS) {
php_stream *stream = (php_stream*)le->ptr;
if (!stream) {
zend_throw_exception_ex(mongo_ce_GridFSException, 5 TSRMLS_CC, "could not find filehandle");
return;
}
stdio_fptr = (php_stdio_stream_data*)stream->abstract;
}
if (!stdio_fptr) {
zend_throw_exception_ex(mongo_ce_GridFSException, 6 TSRMLS_CC, "no file is associate with this filehandle");
return;
}
if (stdio_fptr->file) {
if ((size = setup_file(stdio_fptr->file, filename TSRMLS_CC)) == FAILURE) {
zend_throw_exception_ex(mongo_ce_GridFSException, 7 TSRMLS_CC, "error setting up file: %s", filename);
return;
}
fp = stdio_fptr->file;
}
fd = stdio_fptr->fd;
} else if (Z_TYPE_P(fh) == IS_STRING) {
filename = Z_STRVAL_P(fh);
fp = fopen(filename, "rb");
/* no point in continuing if we can't open the file */
if ((size = setup_file(fp, filename TSRMLS_CC)) == FAILURE) {
zend_throw_exception_ex(mongo_ce_GridFSException, 7 TSRMLS_CC, "error setting up file: %s", filename);
return;
}
} else {
char *msg = "first argument must be a string or stream resource";
zend_throw_exception(zend_exception_get_default(TSRMLS_C), msg, 8 TSRMLS_CC);
return;
}
/* file array object */
MAKE_STD_ZVAL(zfile);
ZVAL_NULL(zfile);
/* merge extra & zfile and add _id if needed */
zid = setup_extra(zfile, extra TSRMLS_CC);
setup_file_fields(zfile, filename, size TSRMLS_CC);
/* chunkSize */
global_chunk_size = get_chunk_size(zfile TSRMLS_CC);
/* options */
if (!options) {
zval *opts;
MAKE_STD_ZVAL(opts);
array_init(opts);
options = opts;
} else {
Z_ADDREF_P(options);
}
MAKE_STD_ZVAL(cleanup_ids);
array_init(cleanup_ids);
/* insert chunks */
while (pos < size || fp == 0) {
ssize_t result = 0;
char *buf;
zval *chunk_id = NULL;
size_t chunk_size = size-pos >= global_chunk_size || fp == 0 ? global_chunk_size : size-pos;
buf = (char*)emalloc(chunk_size);
if (fp) {
size_t retval = fread(buf, 1, chunk_size, fp);
if (retval < chunk_size) {
zend_throw_exception_ex(mongo_ce_GridFSException, 9 TSRMLS_CC, "error reading file %s", filename);
revert = 1;
efree(buf);
goto cleanup_on_failure;
}
pos += chunk_size;
if (!(chunk_id = insert_chunk(chunks, zid, chunk_num, buf, chunk_size, options TSRMLS_CC))) {
revert = 1;
efree(buf);
goto cleanup_on_failure;
}
add_next_index_zval(cleanup_ids, chunk_id);
} else {
result = read(fd, buf, chunk_size);
if (result == -1) {
zend_throw_exception_ex(mongo_ce_GridFSException, 10 TSRMLS_CC, "error reading filehandle");
revert = 1;
efree(buf);
goto cleanup_on_failure;
}
pos += result;
if (!(chunk_id = insert_chunk(chunks, zid, chunk_num, buf, result, options TSRMLS_CC))) {
revert = 1;
efree(buf);
goto cleanup_on_failure;
}
add_next_index_zval(cleanup_ids, chunk_id);
}
efree(buf);
/* Run GLE, just to ensure all the data has been written */
{
zval *cmd, *gle_retval;
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_long(cmd, "getlasterror", 1);
/* run command */
gle_retval = php_mongo_runcommand(db->link, &db->read_pref, Z_STRVAL_P(db->name), Z_STRLEN_P(db->name), cmd, NULL, 0, NULL TSRMLS_CC);
zval_ptr_dtor(&cmd);
if (!gle_retval) {
revert = 1;
goto cleanup_on_failure;
}
if (Z_TYPE_P(gle_retval) == IS_ARRAY) {
zval **err;
if (zend_hash_find(Z_ARRVAL_P(gle_retval), "err", strlen("err") + 1, (void**)&err) == SUCCESS && Z_TYPE_PP(err) == IS_STRING) {
zend_throw_exception_ex(mongo_ce_GridFSException, 0 TSRMLS_CC, Z_STRVAL_PP(err));
/* Intentionally not returning, the exception is checked a line later */
}
}
zval_ptr_dtor(&gle_retval);
if (EG(exception)) {
revert = 1;
goto cleanup_on_failure;
}
}
if (EG(exception)) {
revert = 1;
goto cleanup_on_failure;
}
chunk_num++;
if (fp == 0 && result < chunk_size) {
break;
}
}
/* close file ptr */
if (fp) {
fclose(fp);
}
if (EG(exception)) {
goto cleanup_on_failure;
}
if (!fp) {
add_assoc_long(zfile, "length", pos);
}
add_md5(zfile, zid, c TSRMLS_CC);
/* insert file */
if (!revert) {
zval *temp_return;
Z_ADDREF_P(options);
MAKE_STD_ZVAL(temp_return);
ZVAL_NULL(temp_return);
MONGO_METHOD2(MongoCollection, insert, temp_return, getThis(), zfile, options);
zval_ptr_dtor(&temp_return);
Z_DELREF_P(options);
if (EG(exception)) {
revert = 1;
}
}
if (!revert) {
RETVAL_ZVAL(zid, 1, 0);
}
cleanup_on_failure:
/* remove all inserted chunks and main file document */
if (revert) {
/* Cleanup any created chunks from the chunks collection. If the insert
* into the files collection fails, it fails - and nothing to cleanup
* there anyway */
cleanup_stale_chunks(INTERNAL_FUNCTION_PARAM_PASSTHRU, cleanup_ids);
gridfs_rewrite_cursor_exception(TSRMLS_C);
RETVAL_FALSE;
}
/* cleanup */
zval_ptr_dtor(&zfile);
zval_ptr_dtor(&cleanup_ids);
zval_ptr_dtor(&options);
}
/* }}} */
/* {{{ proto MongoGridFSFile MongoGridFS::findOne([array|string query [, array|object fields [, array options]]])
Returns a single file matching the criteria. If $query is a string, it will
be used to match documents by the filename field, which may not be unique. */
PHP_METHOD(MongoGridFS, findOne)
{
zval *zquery = 0, *zfields = 0, *zoptions = 0, *file;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zza", &zquery, &zfields, &zoptions) == FAILURE) {
return;
}
MUST_BE_ARRAY_OR_OBJECT(2, zfields);
if (!zquery) {
MAKE_STD_ZVAL(zquery);
array_init(zquery);
} else if (Z_TYPE_P(zquery) != IS_ARRAY) {
zval *temp;
convert_to_string(zquery);
MAKE_STD_ZVAL(temp);
array_init(temp);
add_assoc_string(temp, "filename", Z_STRVAL_P(zquery), 1);
zquery = temp;
} else {
zval_add_ref(&zquery);
}
if (!zfields) {
MAKE_STD_ZVAL(zfields);
array_init(zfields);
} else {
zval_add_ref(&zfields);
}
if (!zoptions) {
MAKE_STD_ZVAL(zoptions);
array_init(zoptions);
} else {
zval_add_ref(&zoptions);
}
MAKE_STD_ZVAL(file);
MONGO_METHOD3(MongoCollection, findOne, file, getThis(), zquery, zfields, zoptions);
if (Z_TYPE_P(file) == IS_NULL) {
RETVAL_NULL();
} else {
zval temp;
object_init_ex(return_value, mongo_ce_GridFSFile);
MONGO_METHOD2(MongoGridFSFile, __construct, &temp, return_value, getThis(), file);
}
zval_ptr_dtor(&file);
zval_ptr_dtor(&zquery);
zval_ptr_dtor(&zfields);
zval_ptr_dtor(&zoptions);
}
/* }}} */
/* {{{ proto mixed MongoGridFS::remove([array|string criteria = array() [, array options = array()]])
Removes files and corresponding chunks. If $query is a string, it will be
used to match documents by the filename field, which may not be unique. */
PHP_METHOD(MongoGridFS, remove)
{
zval *criteria = 0, *options = 0, *zfields, *zcursor, *chunks, *next, chunktemp;
zval **tmp;
int justOne = -1;
int options_created = 0;
chunks = zend_read_property(mongo_ce_GridFS, getThis(), "chunks", strlen("chunks"), NOISY TSRMLS_CC);
php_mongo_ensure_gridfs_index(&chunktemp, chunks TSRMLS_CC);
zval_dtor(&chunktemp);
/* Abort if we could not create the unique index on fs.chunks */
if (EG(exception)) {
gridfs_rewrite_cursor_exception(TSRMLS_C);
RETURN_FALSE;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|za/", &criteria, &options) == FAILURE) {
return;
}
if (!criteria) {
MAKE_STD_ZVAL(criteria);
array_init(criteria);
} else if (Z_TYPE_P(criteria) == IS_ARRAY) {
zval_add_ref(&criteria);
} else {
zval *temp;
MAKE_STD_ZVAL(temp);
array_init(temp);
convert_to_string(criteria);
add_assoc_stringl(temp, "filename", Z_STRVAL_P(criteria), Z_STRLEN_P(criteria), 1);
criteria = temp;
}
if (!options) {
MAKE_STD_ZVAL(options);
array_init(options);
options_created = 1;
}
/* { _id : 1 } */
MAKE_STD_ZVAL(zfields);
array_init(zfields);
add_assoc_long(zfields, "_id", 1);
/* cursor = db.fs.files.find(criteria, {_id : 1}); */
MAKE_STD_ZVAL(zcursor);
MONGO_METHOD2(MongoCollection, find, zcursor, getThis(), criteria, zfields);
zval_ptr_dtor(&zfields);
PHP_MONGO_CHECK_EXCEPTION3(&zcursor, &criteria, &options);
/* Chunk deletions should use the same write options as file deletions, but