This repository has been archived by the owner on Feb 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 326
/
collection.c
3266 lines (2682 loc) · 105 KB
/
collection.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 <zend_exceptions.h>
#include <ext/standard/php_smart_str.h>
#include "php_mongo.h"
#include "collection.h"
#include "command_cursor.h"
#include "cursor.h"
#include "cursor_shared.h"
#include "bson.h"
#include "db.h"
#include "types/code.h"
#include "types/db_ref.h"
#include "db.h"
#include "mcon/manager.h"
#include "mcon/utils.h"
#include "mcon/connections.h"
#include "log_stream.h"
#include "api/write.h"
#include "api/wire_version.h"
#include "contrib/php-json.h"
#undef fsync
extern zend_class_entry *mongo_ce_MongoClient, *mongo_ce_DB, *mongo_ce_Cursor;
extern zend_class_entry *mongo_ce_CommandCursor;
extern zend_class_entry *mongo_ce_Code, *mongo_ce_Exception, *mongo_ce_ResultException;
extern zend_class_entry *mongo_ce_CursorException;
extern zend_object_handlers mongo_default_handlers;
ZEND_EXTERN_MODULE_GLOBALS(mongo)
zend_class_entry *mongo_ce_Collection = NULL;
static int is_gle_op(zval *coll, zval *options, mongo_server_options *server_options, int silent TSRMLS_DC);
static void do_gle_op(mongo_con_manager *manager, mongo_connection *connection, zval *cursor_z, mongo_buffer *buf, zval *return_value TSRMLS_DC);
static zval* append_getlasterror(zval *coll, mongo_buffer *buf, zval *options, mongo_connection *connection TSRMLS_DC);
static char *to_index_string(zval *zkeys, int *key_len TSRMLS_DC);
/**
* Unsets an option if it exists.
*
* @param zval *options
* @param const char *name
*/
#define DELETE_OPTION_IF_EXISTS(options, name) do { \
zval **tmp_option; \
if (zend_hash_find(HASH_P(options), name, strlen(name) + 1, (void**)&tmp_option) == SUCCESS) { \
zend_hash_del(HASH_P(options), name, strlen(name) + 1); \
} \
} while(0);
static int is_valid_collectionname(char *colname, int colname_len TSRMLS_DC)
{
if (colname_len == 0) {
zend_throw_exception_ex(mongo_ce_Exception, 2 TSRMLS_CC, "Collection name cannot be empty");
return 0;
}
if (
/* strchr(colname, '$') != 0 || — we can not exclude this as we need it to run commands */
memchr(colname, '\0', colname_len) != 0
) {
zend_throw_exception_ex(mongo_ce_Exception, 2 TSRMLS_CC, "Collection name cannot contain null bytes: %s\\0...", colname);
return 0;
}
return 1;
}
void php_mongo_collection_construct(zval *this, zval *parent, char *name_str, int name_len TSRMLS_DC)
{
zval *name, *zns, *w, *wtimeout;
mongo_collection *c;
mongo_db *db;
char *ns;
/* check for empty and invalid collection names */
if (!is_valid_collectionname(name_str, name_len TSRMLS_CC)) {
return;
}
c = (mongo_collection*)zend_object_store_get_object(this TSRMLS_CC);
db = (mongo_db*)zend_object_store_get_object(parent TSRMLS_CC);
if (!(db->name)) {
zend_throw_exception(mongo_ce_Exception, "The MongoDB object has not been correctly initialized by its constructor", 0 TSRMLS_CC);
return;
}
c->link = db->link;
zval_add_ref(&db->link);
c->parent = parent;
zval_add_ref(&parent);
MAKE_STD_ZVAL(name);
ZVAL_STRINGL(name, name_str, name_len, 1);
c->name = name;
spprintf(&ns, 0, "%s.%s", Z_STRVAL_P(db->name), Z_STRVAL_P(name));
MAKE_STD_ZVAL(zns);
ZVAL_STRING(zns, ns, 0);
c->ns = zns;
mongo_read_preference_copy(&db->read_pref, &c->read_pref);
w = zend_read_property(mongo_ce_DB, parent, "w", strlen("w"), NOISY TSRMLS_CC);
if (Z_TYPE_P(w) == IS_STRING) {
zend_update_property_string(mongo_ce_Collection, this, "w", strlen("w"), Z_STRVAL_P(w) TSRMLS_CC);
} else {
convert_to_long(w);
zend_update_property_long(mongo_ce_Collection, this, "w", strlen("w"), Z_LVAL_P(w) TSRMLS_CC);
}
wtimeout = zend_read_property(mongo_ce_DB, parent, "wtimeout", strlen("wtimeout"), NOISY TSRMLS_CC);
convert_to_long(wtimeout);
zend_update_property_long(mongo_ce_Collection, this, "wtimeout", strlen("wtimeout"), Z_LVAL_P(wtimeout) TSRMLS_CC);
}
/* {{{ proto MongoCollection MongoCollection::__construct(MongoDB db, string name)
Initializes a new MongoCollection */
PHP_METHOD(MongoCollection, __construct)
{
zval *db;
char *name_str;
int name_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os", &db, mongo_ce_DB, &name_str, &name_len) == FAILURE) {
zval *object = getThis();
ZVAL_NULL(object);
return;
}
php_mongo_collection_construct(getThis(), db, name_str, name_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto string MongoCollection::__toString()
Returns the full namespace for this collection (includes database name) */
PHP_METHOD(MongoCollection, __toString)
{
mongo_collection *c;
PHP_MONGO_GET_COLLECTION(getThis());
RETURN_ZVAL(c->ns, 1, 0);
}
/* }}} */
/* {{{ proto string MongoCollection::getName()
Returns the collection name */
PHP_METHOD(MongoCollection, getName)
{
mongo_collection *c;
PHP_MONGO_GET_COLLECTION(getThis());
RETURN_ZVAL(c->name, 1, 0);
}
/* }}} */
/* {{{ proto bool MongoCollection::getSlaveOkay()
Returns the slaveOkay flag for this collection */
PHP_METHOD(MongoCollection, getSlaveOkay)
{
mongo_collection *c;
PHP_MONGO_GET_COLLECTION(getThis());
RETURN_BOOL(c->read_pref.type != MONGO_RP_PRIMARY);
}
/* }}} */
/* {{{ proto bool MongoCollection::setSlaveOkay([bool slave_okay = true])
Sets the slaveOkay flag for this collection and returns the previous value */
PHP_METHOD(MongoCollection, setSlaveOkay)
{
zend_bool slave_okay = 1;
mongo_collection *c;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &slave_okay) == FAILURE) {
return;
}
PHP_MONGO_GET_COLLECTION(getThis());
RETVAL_BOOL(c->read_pref.type != MONGO_RP_PRIMARY);
c->read_pref.type = slave_okay ? MONGO_RP_SECONDARY_PREFERRED : MONGO_RP_PRIMARY;
}
/* }}} */
/* {{{ proto array MongoCollection::getReadPreference()
Returns an array describing the read preference for this collection. Tag sets will be included if available. */
PHP_METHOD(MongoCollection, getReadPreference)
{
mongo_collection *c;
PHP_MONGO_GET_COLLECTION(getThis());
array_init(return_value);
add_assoc_string(return_value, "type", mongo_read_preference_type_to_name(c->read_pref.type), 1);
php_mongo_add_tagsets(return_value, &c->read_pref);
}
/* }}} */
/* {{{ proto bool MongoCollection::setReadPreference(string read_preference [, array tags ])
Sets the read preference for this collection */
PHP_METHOD(MongoCollection, setReadPreference)
{
char *read_preference;
int read_preference_len;
mongo_collection *c;
HashTable *tags = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|h", &read_preference, &read_preference_len, &tags) == FAILURE) {
return;
}
PHP_MONGO_GET_COLLECTION(getThis());
if (php_mongo_set_readpreference(&c->read_pref, read_preference, tags TSRMLS_CC)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ array MongoCollection::getWriteConcern()
* Get the MongoCollection write concern. */
PHP_METHOD(MongoCollection, getWriteConcern)
{
zval *write_concern, *wtimeout;
if (zend_parse_parameters_none()) {
return;
}
write_concern = zend_read_property(mongo_ce_DB, getThis(), "w", strlen("w"), 0 TSRMLS_CC);
wtimeout = zend_read_property(mongo_ce_DB, getThis(), "wtimeout", strlen("wtimeout"), 0 TSRMLS_CC);
Z_ADDREF_P(write_concern);
Z_ADDREF_P(wtimeout);
array_init(return_value);
add_assoc_zval(return_value, "w", write_concern);
add_assoc_zval(return_value, "wtimeout", wtimeout);
}
/* }}} */
/* {{{ bool MongoCollection::setWriteConcern(mixed w [, int wtimeout])
* Set the MongoCollection write concern. */
PHP_METHOD(MongoCollection, setWriteConcern)
{
zval *write_concern;
long wtimeout;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &write_concern, &wtimeout) == FAILURE) {
return;
}
if (Z_TYPE_P(write_concern) == IS_LONG) {
zend_update_property_long(mongo_ce_Collection, getThis(), "w", strlen("w"), Z_LVAL_P(write_concern) TSRMLS_CC);
} else if (Z_TYPE_P(write_concern) == IS_STRING) {
zend_update_property_stringl(mongo_ce_Collection, getThis(), "w", strlen("w"), Z_STRVAL_P(write_concern), Z_STRLEN_P(write_concern) TSRMLS_CC);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "expects parameter 1 to be an string or integer, %s given", zend_get_type_by_const(Z_TYPE_P(write_concern)));
RETURN_FALSE;
}
if (ZEND_NUM_ARGS() > 1) {
zend_update_property_long(mongo_ce_Collection, getThis(), "wtimeout", strlen("wtimeout"), wtimeout TSRMLS_CC);
}
RETURN_TRUE;
}
/* }}} */
void php_mongocollection_drop(zval *collection, zval *return_value TSRMLS_DC)
{
zval *cmd, *retval;
mongo_collection *c;
mongo_db *db;
PHP_MONGO_GET_COLLECTION(collection);
PHP_MONGO_GET_DB(c->parent);
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_zval(cmd, "drop", c->name);
zval_add_ref(&c->name);
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 (retval) {
RETURN_ZVAL(retval, 0, 1);
}
}
/* {{{ proto array MongoCollection::drop()
Drops the current collection and returns the database response */
PHP_METHOD(MongoCollection, drop)
{
php_mongocollection_drop(getThis(), return_value TSRMLS_CC);
}
/* }}} */
/* {{{ proto array MongoCollection::validate([bool scan_data])
Validates the current collection, optionally include the data, and returns the database response */
PHP_METHOD(MongoCollection, validate)
{
zval *cmd, *retval;
zend_bool scan_data = 0;
mongo_collection *c;
mongo_db *db;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &scan_data) == FAILURE) {
return;
}
PHP_MONGO_GET_COLLECTION(getThis());
PHP_MONGO_GET_DB(c->parent);
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_string(cmd, "validate", Z_STRVAL_P(c->name), 1);
add_assoc_bool(cmd, "full", scan_data);
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 (retval) {
RETURN_ZVAL(retval, 0, 1);
}
}
/* }}} */
/* This should probably be split into two methods... right now appends the
* getlasterror query to the buffer and alloc & inits the cursor zval. */
static zval* append_getlasterror(zval *coll, mongo_buffer *buf, zval *options, mongo_connection *connection TSRMLS_DC)
{
zval *cmd_ns_z, *cmd, *cursor_z, *timeout_p;
char *cmd_ns, *w_str = NULL;
mongo_cursor *cursor;
mongo_collection *c = (mongo_collection*)zend_object_store_get_object(coll TSRMLS_CC);
mongo_db *db = (mongo_db*)zend_object_store_get_object(c->parent TSRMLS_CC);
int response, w = 0, fsync = 0, journal = 0, timeout = -1;
mongoclient *link = (mongoclient*) zend_object_store_get_object(c->link TSRMLS_CC);
int max_document_size = connection->max_bson_size;
int max_message_size = connection->max_message_size;
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror");
timeout_p = zend_read_static_property(mongo_ce_Cursor, "timeout", strlen("timeout"), NOISY TSRMLS_CC);
convert_to_long(timeout_p);
/* The value hasn't been modified from what we registered it as originally, but we do
* need to set it to a real value */
if (Z_LVAL_P(timeout_p) == PHP_MONGO_STATIC_CURSOR_TIMEOUT_NOT_SET_INITIALIZER) {
timeout = link->servers->options.socketTimeoutMS;
} else {
/* The value was modified, bad user, bad user! Tell him its deprecated */
timeout = Z_LVAL_P(timeout_p);
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'MongoCursor::$timeout' static property is deprecated, please call MongoCursor->timeout() instead");
}
/* Read the default_* properties from the link */
if (link->servers->options.default_fsync != -1) {
fsync = link->servers->options.default_fsync;
}
if (link->servers->options.default_journal != -1) {
journal = link->servers->options.default_journal;
}
if (link->servers->options.default_w != -1) {
w = link->servers->options.default_w;
}
if (link->servers->options.default_wstring != NULL) {
w_str = link->servers->options.default_wstring;
}
/* This picks up the default "w" through the properties of MongoCollection
* and MongoDb, but only if w is still 1 - as otherwise it was perhaps
* overridden with the "w" (or "safe") option. */
{
zval *w_prop = zend_read_property(mongo_ce_Collection, coll, "w", strlen("w"), NOISY TSRMLS_CC);
if (Z_TYPE_P(w_prop) == IS_STRING) {
w_str = Z_STRVAL_P(w_prop);
} else {
convert_to_long(w_prop);
if (Z_LVAL_P(w_prop) != 1) {
w = Z_LVAL_P(w_prop);
w_str = NULL;
}
}
}
/* Fetch all the options from the options array */
if (options && IS_ARRAY_OR_OBJECT_P(options)) {
zval **gle_pp = NULL, **fsync_pp, **timeout_pp, **journal_pp;
/* First we try "w", and if that is not found we check for "safe" */
if (zend_hash_find(HASH_P(options), "w", strlen("w") + 1, (void**) &gle_pp) == SUCCESS) {
switch (Z_TYPE_PP(gle_pp)) {
case IS_STRING:
w_str = Z_STRVAL_PP(gle_pp);
break;
case IS_BOOL:
case IS_LONG:
w = Z_LVAL_PP(gle_pp); /* This is actually "wrong" for bools, but it works */
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The value of the 'w' option either needs to be a integer or string");
}
} else if (zend_hash_find(HASH_P(options), "safe", strlen("safe") + 1, (void**) &gle_pp) == SUCCESS) {
switch (Z_TYPE_PP(gle_pp)) {
case IS_STRING:
w_str = Z_STRVAL_PP(gle_pp);
break;
case IS_LONG:
w = Z_LVAL_PP(gle_pp);
break;
case IS_BOOL:
if (Z_BVAL_PP(gle_pp)) {
/* If we already provided Write Concern, do not overwrite it with w=1 */
if (!(w > 1 || w_str)) {
w = 1;
}
} else {
w = 0;
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The value of the 'safe' option either needs to be a integer or string");
}
}
if (SUCCESS == zend_hash_find(HASH_P(options), "fsync", strlen("fsync") + 1, (void**) &fsync_pp)) {
convert_to_boolean(*fsync_pp);
fsync = Z_BVAL_PP(fsync_pp);
}
if (zend_hash_find(HASH_P(options), "j", strlen("j") + 1, (void**) &journal_pp) == SUCCESS) {
convert_to_boolean(*journal_pp);
journal = Z_BVAL_PP(journal_pp);
}
if (SUCCESS == zend_hash_find(HASH_P(options), "socketTimeoutMS", strlen("socketTimeoutMS") + 1, (void**) &timeout_pp)) {
convert_to_long(*timeout_pp);
timeout = Z_LVAL_PP(timeout_pp);
} else if (SUCCESS == zend_hash_find(HASH_P(options), "timeout", strlen("timeout") + 1, (void**) &timeout_pp)) {
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'timeout' option is deprecated, please use 'socketTimeoutMS' instead");
convert_to_long(*timeout_pp);
timeout = Z_LVAL_PP(timeout_pp);
}
}
/* fsync forces "w" to be atleast 1, so don't touch it if it's
* already set to something else above while parsing "w" (and
* "safe") */
if (fsync && w == 0) {
w = 1;
}
/* get "db.$cmd" zval */
MAKE_STD_ZVAL(cmd_ns_z);
spprintf(&cmd_ns, 0, "%s.$cmd", Z_STRVAL_P(db->name));
ZVAL_STRING(cmd_ns_z, cmd_ns, 0);
/* get {"getlasterror" : 1} zval */
MAKE_STD_ZVAL(cmd);
array_init(cmd);
add_assoc_long(cmd, "getlasterror", 1);
/* if we have either a string, or w > 1, then we need to add "w" and
* perhaps "wtimeout" to GLE */
if (w_str || w > 1) {
zval *wtimeout, **wtimeout_pp;
if (w_str) {
add_assoc_string(cmd, "w", w_str, 1);
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added w='%s'", w_str);
} else {
add_assoc_long(cmd, "w", w);
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added w=%d", w);
}
if (options && zend_hash_find(HASH_P(options), "wTimeoutMS", strlen("wTimeoutMS") + 1, (void **)&wtimeout_pp) == SUCCESS) {
convert_to_long(*wtimeout_pp);
add_assoc_long(cmd, "wtimeout", Z_LVAL_PP(wtimeout_pp));
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added wtimeout=%d (wTimeoutMS from options array)", Z_LVAL_PP(wtimeout_pp));
} else if (options && zend_hash_find(HASH_P(options), "wtimeout", strlen("wtimeout") + 1, (void **)&wtimeout_pp) == SUCCESS) {
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'wtimeout' option is deprecated, please use 'wTimeoutMS' instead");
convert_to_long(*wtimeout_pp);
add_assoc_long(cmd, "wtimeout", Z_LVAL_PP(wtimeout_pp));
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added wtimeout=%d (wtimeout from options array)", Z_LVAL_PP(wtimeout_pp));
} else {
wtimeout = zend_read_property(mongo_ce_Collection, coll, "wtimeout", strlen("wtimeout"), NOISY TSRMLS_CC);
convert_to_long(wtimeout);
add_assoc_long(cmd, "wtimeout", Z_LVAL_P(wtimeout));
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added wtimeout=%d (from collection property)", Z_LVAL_P(wtimeout));
}
}
if (fsync == 1) {
add_assoc_bool(cmd, "fsync", 1);
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added fsync=1");
}
if (journal == 1) {
add_assoc_bool(cmd, "j", 1);
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "append_getlasterror: added j=1");
}
/* get cursor */
MAKE_STD_ZVAL(cursor_z);
object_init_ex(cursor_z, mongo_ce_Cursor);
cursor = (mongo_cursor*)zend_object_store_get_object(cursor_z TSRMLS_CC);
php_mongocursor_create(cursor, c->link, Z_STRVAL_P(cmd_ns_z), Z_STRLEN_P(cmd_ns_z), cmd, NULL TSRMLS_CC);
if (EG(exception)) {
zval_ptr_dtor(&cursor_z);
zval_ptr_dtor(&cmd_ns_z);
zval_ptr_dtor(&cmd);
return 0;
}
/* Make sure the "getLastError" also gets send to a primary. This should
* be refactored alongside with the getLastError redirection in
* db.c/MongoDB::command. The Cursor creation should be done through an
* init method otherwise a connection have to be requested twice. */
mongo_manager_log(link->manager, MLOG_CON, MLOG_INFO, "forcing primary for getlasterror");
php_mongo_cursor_force_primary(cursor);
cursor->limit = -1;
cursor->timeout = timeout;
zval_ptr_dtor(&cursor->query);
/* append the query */
response = php_mongo_write_query(buf, cursor, max_document_size, max_message_size TSRMLS_CC);
zval_ptr_dtor(&cmd_ns_z);
mongo_log_stream_query(connection, cursor TSRMLS_CC);
if (FAILURE == response) {
zval_ptr_dtor(&cursor_z);
return 0;
}
return cursor_z;
}
/* Returns a connection for the operation.
* Connection flags (connection_flags) are MONGO_CON_TYPE_READ and MONGO_CON_TYPE_WRITE. */
mongo_connection* php_mongo_collection_get_server(mongoclient *link, int connection_flags TSRMLS_DC)
{
mongo_connection *connection;
char *error_message = NULL;
if (!link) {
zend_throw_exception(mongo_ce_Exception, "The MongoCollection object has not been correctly initialized by its constructor", 17 TSRMLS_CC);
return NULL;
}
/* TODO: Fix better error message */
if ((connection = mongo_get_read_write_connection(link->manager, link->servers, connection_flags, (char **) &error_message)) == NULL) {
if (error_message) {
php_mongo_cursor_throw(mongo_ce_CursorException, NULL, 16 TSRMLS_CC, "Couldn't get connection: %s", error_message);
free(error_message);
} else {
php_mongo_cursor_throw(mongo_ce_CursorException, NULL, 16 TSRMLS_CC, "Couldn't get connection");
}
return NULL;
}
return connection;
}
/* Wrapper for sending and wrapping in a safe op */
static int send_message(zval *this_ptr, mongo_connection *connection, mongo_buffer *buf, zval *options, zval *return_value TSRMLS_DC)
{
int retval = 1;
char *error_message = NULL;
mongoclient *link;
mongo_collection *c;
c = (mongo_collection*)zend_object_store_get_object(this_ptr TSRMLS_CC);
if (!c->ns) {
zend_throw_exception(mongo_ce_Exception, "The MongoCollection object has not been correctly initialized by its constructor", 0 TSRMLS_CC);
return 0;
}
link = (mongoclient*)zend_object_store_get_object((c->link) TSRMLS_CC);
if (!link) {
zend_throw_exception(mongo_ce_Exception, "The MongoCollection object has not been correctly initialized by its constructor", 17 TSRMLS_CC);
return 0;
}
if (is_gle_op(this_ptr, options, &link->servers->options, NOISY TSRMLS_CC)) {
zval *cursor = append_getlasterror(this_ptr, buf, options, connection TSRMLS_CC);
if (cursor) {
do_gle_op(link->manager, connection, cursor, buf, return_value TSRMLS_CC);
zval_ptr_dtor(&cursor);
retval = -1;
} else {
retval = 0;
}
} else if (link->manager->send(connection, &link->servers->options, buf->start, buf->pos - buf->start, (char **) &error_message) == -1) {
/* TODO: Find out what to do with the error message here */
free(error_message);
retval = 0;
} else {
retval = 1;
}
return retval;
}
/* Determine if the operation should have a GLE command appended. This is based
* on whether a write concern ("w" or "safe") or fsync/journal options are
* specified.
*/
static int is_gle_op(zval *coll, zval *options, mongo_server_options *server_options, int silent TSRMLS_DC)
{
int gle_op = 0, default_fsync, default_journal, coll_w = 0;
zval *z_coll_w;
/* Get the fsync/journal defaults from the MongoClient server options */
default_fsync = server_options->default_fsync;
default_journal = server_options->default_journal;
/* Get the MongoCollection write concern instead of checking the MongoClient
* server options, since MongoCollection will have inherited any defaults
* through the MongoDB class. Additionally, this ensures that we respect a
* write concern set directly on the MongoCollection instance. */
z_coll_w = zend_read_property(mongo_ce_Collection, coll, "w", strlen("w"), NOISY TSRMLS_CC);
if (Z_TYPE_P(z_coll_w) == IS_STRING) {
/* We don't actually care what the string is, only that it was specified */
coll_w = 1;
} else {
convert_to_long(z_coll_w);
coll_w = Z_LVAL_P(z_coll_w);
}
/* Then we check the options array that could overwrite the default */
if (options && Z_TYPE_P(options) == IS_ARRAY) {
zval **gle_pp, **fsync_pp, **journal_pp;
/* Check for "w" in the options array. If it is not found, consult the
* "safe" option, followed by the MongoCollection write concern. */
if (zend_hash_find(HASH_P(options), "w", strlen("w") + 1, (void**) &gle_pp) == SUCCESS) {
switch (Z_TYPE_PP(gle_pp)) {
case IS_STRING:
gle_op = 1;
break;
case IS_BOOL:
case IS_LONG:
/* This is actually "wrong" for bools, but it works */
if (Z_LVAL_PP(gle_pp) >= 1) {
gle_op = 1;
}
break;
default:
if (silent == NOISY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The value of the 'w' option either needs to be a integer or string");
}
}
} else if (zend_hash_find(HASH_P(options), "safe", strlen("safe") + 1, (void**) &gle_pp) == SUCCESS) {
if (silent == NOISY) {
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'safe' option is deprecated, please use 'w' instead");
}
switch (Z_TYPE_PP(gle_pp)) {
case IS_STRING:
gle_op = 1;
break;
case IS_BOOL:
case IS_LONG:
/* This is actually "wrong" for bools, but it works */
if (Z_LVAL_PP(gle_pp) >= 1) {
gle_op = 1;
}
break;
default:
if (silent == NOISY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The value of the 'safe' option either needs to be a boolean or a string");
}
}
} else if (coll_w >= 1) {
gle_op = 1;
}
/* Check for "fsync" in the options array. If it is not found, respect
* the MongoClient "fsync" option. */
if (zend_hash_find(HASH_P(options), "fsync", strlen("fsync") + 1, (void**)&fsync_pp) == SUCCESS) {
convert_to_boolean_ex(fsync_pp);
if (Z_BVAL_PP(fsync_pp)) {
gle_op = 1;
}
} else if (default_fsync == 1) {
gle_op = 1;
}
/* Check for "j" in the options array. If it is not found, respect the
* MongoClient "journal" option. */
if (zend_hash_find(HASH_P(options), "j", strlen("j") + 1, (void**)&journal_pp) == SUCCESS) {
convert_to_boolean_ex(journal_pp);
if (Z_BVAL_PP(journal_pp)) {
gle_op = 1;
}
} else if (default_journal == 1) {
gle_op = 1;
}
} else {
gle_op = (coll_w >= 1 || default_fsync == 1 || default_journal == 1);
}
if (silent == NOISY) {
mongo_manager_log(MonGlo(manager), MLOG_IO, MLOG_FINE, "is_gle_op: %s", gle_op ? "yes" : "no");
}
return gle_op;
}
/* This wrapper temporarily turns off the exception throwing bit if it has been
* set (by calling php_mongo_cursor_throw() before). We can't call
* php_mongo_cursor_throw after deregister as it frees up bits of memory that
* php_mongo_cursor_throw uses to construct its error message.
*
* Without the disabling of the exception bit and when a user defined error
* handler is used on the PHP side, the notice would never been shown because
* the exception bubbles up before the notice can actually be shown. By turning
* the error handling mode to EH_NORMAL temporarily, we circumvent this
* problem. */
static void connection_deregister_wrapper(mongo_con_manager *manager, mongo_connection *connection TSRMLS_DC)
{
int orig_error_handling;
/* Save EG/PG(error_handling) so that we can show log messages when we have
* already thrown an exception */
orig_error_handling = EG(error_handling);
EG(error_handling) = EH_NORMAL;
mongo_manager_connection_deregister(manager, connection);
EG(error_handling) = orig_error_handling;
}
static void do_gle_op(mongo_con_manager *manager, mongo_connection *connection, zval *cursor_z, mongo_buffer *buf, zval *return_value TSRMLS_DC)
{
char *error_message;
mongo_cursor *cursor;
mongoclient *client;
cursor = (mongo_cursor*)zend_object_store_get_object(cursor_z TSRMLS_CC);
client = (mongoclient*)zend_object_store_get_object(cursor->zmongoclient TSRMLS_CC);
cursor->connection = connection;
if (-1 == manager->send(connection, &client->servers->options, buf->start, buf->pos - buf->start, (char **) &error_message)) {
mongo_manager_log(manager, MLOG_IO, MLOG_WARN, "do_gle_op: sending data failed, removing connection %s", connection->hash);
php_mongo_cursor_throw(mongo_ce_CursorException, connection, 16 TSRMLS_CC, "%s", error_message);
connection_deregister_wrapper(manager, connection TSRMLS_CC);
free(error_message);
cursor->connection = NULL;
return;
}
/* get reply */
if (FAILURE == php_mongo_get_reply(cursor TSRMLS_CC)) {
/* php_mongo_get_reply() throws exceptions */
mongo_manager_connection_deregister(manager, connection);
cursor->connection = NULL;
return;
}
cursor->started_iterating = 1;
php_mongocursor_load_current_element(cursor TSRMLS_CC);
/* MongoCursor::next() threw an exception */
if (EG(exception)) {
cursor->connection = NULL;
return;
}
/* Check if either the GLE command or the previous write operation failed */
php_mongo_trigger_error_on_gle(cursor->connection, cursor->current TSRMLS_CC);
RETVAL_ZVAL(cursor->current, 1, 0);
cursor->connection = NULL;
return;
}
int mongo_collection_insert_opcode(mongo_con_manager *manager, mongo_connection *connection, mongo_server_options *options, zval *write_options, zval *this_ptr, mongo_buffer *buf, char *namespace, int namespace_len, zval *document, zval *return_value TSRMLS_DC)
{
int retval = 0;
if (FAILURE == php_mongo_write_insert(buf, namespace, document, connection->max_bson_size, connection->max_message_size TSRMLS_CC)) {
return 0;
}
mongo_log_stream_insert(connection, document, write_options TSRMLS_CC);
/* retval == -1 means a GLE response was received, so send_message() has
* either set return_value or thrown an exception via do_gle_op(). */
retval = send_message(this_ptr, connection, buf, write_options, return_value TSRMLS_CC);
return retval;
}
void mongo_convert_write_api_return_to_legacy_retval(zval *return_value, php_mongo_write_types type, int write_concern TSRMLS_DC)
{
zval **ok, **err, **errmsg, **n;
if (write_concern < 1) {
/* Not kidding.. Surpress any exception thrown for w=0 */
zend_clear_exception(TSRMLS_C);
convert_to_boolean(return_value);
return;
}
if (SUCCESS == zend_hash_find(HASH_P(return_value), "ok", strlen("ok") + 1, (void**) &ok) && Z_TYPE_PP(ok) != IS_DOUBLE) {
convert_to_double(*ok);
}
if (FAILURE == zend_hash_find(HASH_P(return_value), "err", strlen("err") + 1, (void**) &err)) {
add_assoc_null(return_value, "err");
}
if (FAILURE == zend_hash_find(HASH_P(return_value), "errmsg", strlen("errmsg") + 1, (void**) &errmsg)) {
add_assoc_null(return_value, "errmsg");
}
switch (type) {
case MONGODB_API_COMMAND_INSERT:
if (SUCCESS == zend_hash_find(HASH_P(return_value), "n", strlen("n") + 1, (void**) &n)) {
/* "n" was always 0 for OP_INSERT gle. */
convert_to_long(*n);
Z_LVAL_PP(n) = 0;
}
break;
case MONGODB_API_COMMAND_UPDATE: {
int updatedExisting = 0;
if (SUCCESS == zend_hash_find(HASH_P(return_value), "n", strlen("n") + 1, (void**) &n)) {
zval **upserted;
convert_to_long_ex(n);
if (SUCCESS == zend_hash_find(HASH_P(return_value), "upserted", strlen("upserted") + 1, (void**) &upserted) && Z_TYPE_PP(upserted) == IS_ARRAY) {
zval **upserted_index;
if (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(upserted), (void **)&upserted_index)) {
zval **upserted_id;
/* upserted is an array of _ids in 2.6 */
if (SUCCESS == zend_hash_find(HASH_PP(upserted_index), "_id", strlen("_id") + 1, (void**) &upserted_id)) {
zval *id;
MAKE_STD_ZVAL(id);
MAKE_COPY_ZVAL(upserted_id, id);
zend_hash_del(HASH_OF(return_value), "upserted", strlen("upserted") + 1);
add_assoc_zval(return_value, "upserted", id);
}
}
}
else if (Z_LVAL_PP(n) > 0) {
/* updatedExisting needs to be set to true when existing documents were modified */
updatedExisting = 1;
}
}
add_assoc_bool(return_value, "updatedExisting", updatedExisting);
} break;
case MONGODB_API_COMMAND_DELETE:
break;
}
}
void mongo_apply_implicit_write_options(php_mongo_write_options *write_options, mongo_server_options *server_options, zval *collection TSRMLS_DC)
{
if (write_options->fsync == -1) {
write_options->fsync = server_options->default_fsync;
}
if (write_options->j == -1) {
write_options->j = server_options->default_journal;
}
if (write_options->wtimeout == -1) {
zval *wtimeout_prop;
write_options->wtimeout = server_options->default_wtimeout;
wtimeout_prop = zend_read_property(mongo_ce_Collection, collection, "wtimeout", strlen("wtimeout"), NOISY TSRMLS_CC);
convert_to_long(wtimeout_prop);
if (Z_LVAL_P(wtimeout_prop) != PHP_MONGO_DEFAULT_WTIMEOUT) {
write_options->wtimeout = Z_LVAL_P(wtimeout_prop);
}
}
if (write_options->wtype == -1) {
zval *w_prop = zend_read_property(mongo_ce_Collection, collection, "w", strlen("w"), NOISY TSRMLS_CC);
if (Z_TYPE_P(w_prop) == IS_LONG || Z_TYPE_P(w_prop) == IS_BOOL) {
if (Z_LVAL_P(w_prop) == 1) {
if (server_options->default_w != -1) {
write_options->write_concern.w = server_options->default_w;
write_options->wtype = 1;
} else if (server_options->default_wstring != NULL) {
write_options->write_concern.wstring = server_options->default_wstring;
write_options->wtype = 2;
} else {
write_options->write_concern.w = Z_LVAL_P(w_prop);
write_options->wtype = 1;
}
} else {
write_options->write_concern.w = Z_LVAL_P(w_prop);
write_options->wtype = 1;
}
} else {
convert_to_string(w_prop);
write_options->write_concern.wstring = Z_STRVAL_P(w_prop);
write_options->wtype = 2;
}
}
}
/*
* Returns the socket read timeout (in ms) from the specified write options
* ('socketTimeoutMS', with a deprecated fallback to 'timeout').
*/
int mongo_get_socket_read_timeout(mongo_server_options *server_options, zval *z_write_options TSRMLS_DC)
{
if (z_write_options && Z_TYPE_P(z_write_options) == IS_ARRAY) {
zval **timeout_pp;
if (SUCCESS == zend_hash_find(HASH_P(z_write_options), "socketTimeoutMS", strlen("socketTimeoutMS") + 1, (void**) &timeout_pp)) {
convert_to_long(*timeout_pp);
return Z_LVAL_PP(timeout_pp);
} else if (SUCCESS == zend_hash_find(HASH_P(z_write_options), "timeout", strlen("timeout") + 1, (void**) &timeout_pp)) {
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'timeout' option is deprecated, please use 'socketTimeoutMS' instead");
convert_to_long(*timeout_pp);
return Z_LVAL_PP(timeout_pp);
}
}
return server_options->socketTimeoutMS;
}
int mongo_collection_delete_api(mongo_con_manager *manager, mongo_connection *connection, mongo_server_options *server_options, int socket_read_timeout, php_mongo_write_delete_args *delete_options, php_mongo_write_options *write_options, char *dbname, zval *collection, zval *return_value TSRMLS_DC)
{
char *command_ns;
char *error_message;
int retval = 0;
int bytes_written = 0;
int request_id;
mongo_buffer buf;
mongo_collection *c = (mongo_collection*)zend_object_store_get_object(collection TSRMLS_CC);
spprintf(&command_ns, 0, "%s.$cmd", dbname);
CREATE_BUF(buf, INITIAL_BUF_SIZE);
request_id = php_mongo_api_delete_single(&buf, command_ns, Z_STRVAL_P(c->name), delete_options, write_options, connection TSRMLS_CC);
efree(command_ns);
if (request_id == 0) {
/* The document is greater then allowed limits, exception already thrown */
efree(buf.start);
return 0;
}
bytes_written = manager->send(connection, server_options, buf.start, buf.pos - buf.start, &error_message);
if (bytes_written < 1) {
/* Didn't write anything, something bad must have happened */
free(error_message);
efree(buf.start);
return 0;
}
array_init(return_value);
retval = php_mongo_api_get_reply(manager, connection, server_options, socket_read_timeout, request_id, &return_value TSRMLS_CC);
efree(buf.start);
if (retval != 0) {
mongo_manager_connection_deregister(manager, connection);
if (write_options->wtype == 1 && write_options->write_concern.w < 1) {