package.xml 0000644 0000765 0000024 00001017613 13572250761 012514 0 ustar alcaeus staff
mongodb
pecl.php.net
MongoDB driver for PHP
The purpose of this driver is to provide exceptionally thin glue between MongoDB
and PHP, implementing only fundamental and performance-critical components
necessary to build a fully-functional MongoDB driver.
Andreas Braun
alcaeus
alcaeus@php.net
yes
Jeremy Mikola
jmikola
jmikola@php.net
yes
Derick Rethans
derick
derick@php.net
no
Hannes Magnusson
bjori
bjori@php.net
no
Katherine Walker
kvwalker
kvwalker@php.net
no
2019-12-05
1.6.1
1.6.1
stable
stable
Apache License
** Bug
* [PHPC-1503] - Fix MONGOC_CC assignment in config.w32 for PHP 7.4
** Task
* [PHPC-1504] - Add PHP 7.4 to AppVeyor build matrix
* [PHPC-1505] - Update to libmongoc 1.15.2
5.6.0
7.99.99
1.4.8
mongodb
mongodb-1.6.1/scripts/autotools/libbson/CheckAtomics.m4 0000644 0000765 0000024 00000002112 13572250757 022424 0 ustar alcaeus staff AC_LANG_PUSH([C])
AC_MSG_CHECKING([for __sync_add_and_fetch_4])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]],
[[int32_t v = 1; return __sync_add_and_fetch_4 (&v, (int32_t)10);]])],
[AC_MSG_RESULT(yes)
have_sync_add_and_fetch_4=yes],
[AC_MSG_RESULT(no)
have_sync_add_and_fetch_4=no])
AS_IF([test "$have_sync_add_and_fetch_4" = "yes"],
[AC_SUBST(BSON_HAVE_ATOMIC_32_ADD_AND_FETCH, 1)],
[AC_SUBST(BSON_HAVE_ATOMIC_32_ADD_AND_FETCH, 0)])
AC_MSG_CHECKING([for __sync_add_and_fetch_8])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]],
[[int64_t v; return __sync_add_and_fetch_8 (&v, (int64_t)10);]])],
[AC_MSG_RESULT(yes)
have_sync_add_and_fetch_8=yes],
[AC_MSG_RESULT(no)
have_sync_add_and_fetch_8=no])
AS_IF([test "$have_sync_add_and_fetch_8" = "yes"],
[AC_SUBST(BSON_HAVE_ATOMIC_64_ADD_AND_FETCH, 1)],
[AC_SUBST(BSON_HAVE_ATOMIC_64_ADD_AND_FETCH, 0)])
AC_LANG_POP([C])
mongodb-1.6.1/scripts/autotools/libbson/CheckHeaders.m4 0000644 0000765 0000024 00000000421 13572250757 022401 0 ustar alcaeus staff AC_HEADER_STDBOOL
AC_SUBST(BSON_HAVE_STDBOOL_H, 0)
if test "$ac_cv_header_stdbool_h" = "yes"; then
AC_SUBST(BSON_HAVE_STDBOOL_H, 1)
fi
AC_CHECK_HEADER([strings.h],
[AC_SUBST(BSON_HAVE_STRINGS_H, 1)],
[AC_SUBST(BSON_HAVE_STRINGS_H, 0)])
mongodb-1.6.1/scripts/autotools/libbson/Endian.m4 0000644 0000765 0000024 00000000203 13572250757 021264 0 ustar alcaeus staff AC_C_BIGENDIAN
AC_SUBST(BSON_BYTE_ORDER, 1234)
if test "x$ac_cv_c_bigendian" = "xyes"; then
AC_SUBST(BSON_BYTE_ORDER, 4321)
fi
mongodb-1.6.1/scripts/autotools/libbson/FindDependencies.m4 0000644 0000765 0000024 00000007412 13572250757 023266 0 ustar alcaeus staff # Check for strnlen()
dnl AC_CHECK_FUNC isn't properly respecting _XOPEN_SOURCE for strnlen for unknown reason
AC_SUBST(BSON_HAVE_STRNLEN, 0)
AC_CACHE_CHECK([for strnlen],
bson_cv_have_strnlen,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
int strnlen () { return 0; }
]])],
[bson_cv_have_strnlen=no],
[bson_cv_have_strnlen=yes])])
if test "$bson_cv_have_strnlen" = yes; then
AC_SUBST(BSON_HAVE_STRNLEN, 1)
fi
# Check for reallocf() (BSD/Darwin)
AC_SUBST(BSON_HAVE_REALLOCF, 0)
AC_CACHE_CHECK([for reallocf],
bson_cv_have_reallocf,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
int reallocf () { return 0; }
]])],
[bson_cv_have_reallocf=no],
[bson_cv_have_reallocf=yes])])
if test "$bson_cv_have_reallocf" = yes; then
AC_SUBST(BSON_HAVE_REALLOCF, 1)
fi
# Check for syscall()
AC_SUBST(BSON_HAVE_SYSCALL_TID, 0)
AC_CACHE_CHECK([for syscall],
bson_cv_have_syscall_tid,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
#include
int syscall () { return 0; }
]])],
[bson_cv_have_syscall_tid=no],
[bson_cv_have_syscall_tid=yes])])
if test "$bson_cv_have_syscall_tid" = yes -a "$os_darwin" != "yes"; then
AC_CACHE_CHECK([for SYS_gettid],
bson_cv_have_sys_gettid_tid,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
#include
int gettid () { return SYS_gettid; }
]])],
[bson_cv_have_sys_gettid_tid=yes],
[bson_cv_have_sys_gettid_tid=no])])
if test "$bson_cv_have_sys_gettid_tid" = yes; then
AC_SUBST(BSON_HAVE_SYSCALL_TID, 1)
fi
fi
# Check for snprintf()
AC_SUBST(BSON_HAVE_SNPRINTF, 0)
AC_CHECK_FUNC(snprintf, [AC_SUBST(BSON_HAVE_SNPRINTF, 1)])
# Check for struct timespec
AC_SUBST(BSON_HAVE_TIMESPEC, 0)
AC_CHECK_TYPE([struct timespec], [AC_SUBST(BSON_HAVE_TIMESPEC, 1)], [], [#include ])
# Check for clock_gettime and if it needs -lrt
AC_SUBST(BSON_HAVE_CLOCK_GETTIME, 0)
AC_SEARCH_LIBS([clock_gettime], [rt], [AC_SUBST(BSON_HAVE_CLOCK_GETTIME, 1)])
# Check if math functions need -lm
AC_SEARCH_LIBS([floor], [m])
# Check for gmtime_r()
AC_SUBST(BSON_HAVE_GMTIME_R, 0)
AC_CHECK_FUNC(gmtime_r, [AC_SUBST(BSON_HAVE_GMTIME_R, 1)])
# Check for rand_r()
AC_SUBST(BSON_HAVE_RAND_R, 0)
AC_CHECK_FUNC(rand_r, [AC_SUBST(BSON_HAVE_RAND_R, 1)])
# Check for pthreads. We might need to make this better to handle mingw,
# but I actually think it is okay to just check for it even though we will
# use win32 primatives.
AX_PTHREAD([
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PTHREAD_CFLAGS"
PHP_EVAL_LIBLINE([$PTHREAD_LIBS],[MONGODB_SHARED_LIBADD])
# PTHREAD_CFLAGS may come back as "-pthread", which should also be used when
# linking. We can trust PHP_EVAL_LIBLINE to ignore other values.
PHP_EVAL_LIBLINE([$PTHREAD_CFLAGS],[MONGODB_SHARED_LIBADD])
],[
AC_MSG_ERROR([libbson requires pthreads on non-Windows platforms.])
])
# The following is borrowed from the guile configure script.
#
# On past versions of Solaris, believe 8 through 10 at least, you
# had to write "pthread_once_t foo = { PTHREAD_ONCE_INIT };".
# This is contrary to POSIX:
# http://www.opengroup.org/onlinepubs/000095399/functions/pthread_once.html
# Check here if this style is required.
#
# glibc (2.3.6 at least) works both with or without braces, so the
# test checks whether it works without.
#
AC_SUBST(BSON_PTHREAD_ONCE_INIT_NEEDS_BRACES, 0)
AC_CACHE_CHECK([whether PTHREAD_ONCE_INIT needs braces],
bson_cv_need_braces_on_pthread_once_init,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include
pthread_once_t foo = PTHREAD_ONCE_INIT;]])],
[bson_cv_need_braces_on_pthread_once_init=no],
[bson_cv_need_braces_on_pthread_once_init=yes])])
if test "$bson_cv_need_braces_on_pthread_once_init" = yes; then
AC_SUBST(BSON_PTHREAD_ONCE_INIT_NEEDS_BRACES, 1)
fi
mongodb-1.6.1/scripts/autotools/libbson/Versions.m4 0000644 0000765 0000024 00000001202 13572250757 021676 0 ustar alcaeus staff BSON_CURRENT_FILE=[]PHP_EXT_SRCDIR(mongodb)[/src/LIBMONGOC_VERSION_CURRENT]
BSON_VERSION=$(cat $BSON_CURRENT_FILE)
dnl Ensure newline for "cut" implementations that need it, e.g. HP-UX.
BSON_MAJOR_VERSION=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f1 )
BSON_MINOR_VERSION=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f2 )
BSON_MICRO_VERSION=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f3 )
BSON_PRERELEASE_VERSION=$(cut -s -d- -f2 $BSON_CURRENT_FILE)
AC_SUBST(BSON_VERSION)
AC_SUBST(BSON_MAJOR_VERSION)
AC_SUBST(BSON_MINOR_VERSION)
AC_SUBST(BSON_MICRO_VERSION)
AC_SUBST(BSON_PRERELEASE_VERSION)
mongodb-1.6.1/scripts/autotools/libmongoc/CheckCompression.m4 0000644 0000765 0000024 00000004126 13572250757 023656 0 ustar alcaeus staff found_snappy="no"
found_zlib="no"
bundled_zlib="no"
PKG_CHECK_MODULES([PHP_MONGODB_SNAPPY],[snappy],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SNAPPY_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SNAPPY_LIBS],[MONGODB_SHARED_LIBADD])
found_snappy="yes"
],[
PHP_CHECK_LIBRARY([snappy],
[snappy_uncompress],
[have_snappy_lib="yes"],
[have_snappy_lib="no"])
AC_CHECK_HEADER([snappy-c.h],
[have_snappy_headers=yes],
[have_snappy_headers=no])
if test "$have_snappy_lib" = "yes" -a "$have_snappy_headers" = "yes"; then
PHP_ADD_LIBRARY([snappy],,[MONGODB_SHARED_LIBADD])
found_snappy="yes"
fi
])
PKG_CHECK_MODULES([PHP_MONGODB_ZLIB],[zlib],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_ZLIB_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_ZLIB_LIBS],[MONGODB_SHARED_LIBADD])
found_zlib="yes"
],[
PHP_CHECK_LIBRARY([zlib],
[compress2],
[have_zlib_lib="yes"],
[have_zlib_lib="no"])
AC_CHECK_HEADER([zlib.h],
[have_zlib_headers=yes],
[have_zlib_headers=no])
if test "$have_zlib_lib" = "yes" -a "$have_zlib_headers" = "yes"; then
PHP_ADD_LIBRARY([z],,[MONGODB_SHARED_LIBADD])
found_zlib="yes"
fi
])
dnl If zlib was not found, use libmongoc's bundled version
AS_IF([test "$found_zlib" != "yes"],[
bundled_zlib="yes"
])
if test "$found_snappy" = "yes" -o "$found_zlib" = "yes" -o "$bundled_zlib" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION, 1)
if test "$found_snappy" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 1)
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 0)
fi
if test "$found_zlib" = "yes" -o "$bundled_zlib" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 1)
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 0)
fi
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION, 0)
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 0)
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 0)
fi
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZSTD, 0)
mongodb-1.6.1/scripts/autotools/libmongoc/CheckICU.m4 0000644 0000765 0000024 00000002256 13572250757 021777 0 ustar alcaeus staff PHP_ARG_WITH([mongodb-icu],
[whether to enable ICU for SASLPrep with SCRAM-SHA-256 authentication],
[AS_HELP_STRING([--with-mongodb-icu=@<:@auto/yes/no@:>@],
[MongoDB: Enable ICU for SASLPrep with SCRAM-SHA-256 authentication [default=auto]])],
[auto],
[no])
AS_IF([test "$PHP_MONGODB_ICU" = "auto" -o "$PHP_MONGODB_ICU" = "yes"],[
found_icu=no
PKG_CHECK_MODULES([PHP_MONGODB_ICU],[icu-uc],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_ICU_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_ICU_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_ICU="yes"
found_icu=yes
],[
found_icu=no
])
if test "$PHP_MONGODB_ICU" = "yes" -a "$found_icu" = "no"; then
AC_MSG_ERROR([ICU libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_ICU" = "auto"],[
PHP_MONGODB_ICU="no"
])
if test ! \( "$PHP_MONGODB_ICU" = "yes" -o "$PHP_MONGODB_ICU" = "no" \); then
AC_MSG_WARN([unsupported --with-mongodb-icu value: $PHP_MONGODB_ICU])
fi
if test "$PHP_MONGODB_ICU" = "yes"; then
AC_SUBST(MONGOC_ENABLE_ICU, 1)
else
AC_SUBST(MONGOC_ENABLE_ICU, 0)
fi
mongodb-1.6.1/scripts/autotools/libmongoc/CheckResolv.m4 0000644 0000765 0000024 00000004754 13572250757 022636 0 ustar alcaeus staff dnl Disable Windows DNSAPI
AC_SUBST(MONGOC_HAVE_DNSAPI, 0)
found_resolv="no"
old_LIBS="$LIBS"
LIBS="$LIBS -lresolv"
dnl Thread-safe DNS query function for _mongoc_client_get_srv.
dnl Could be a macro, not a function, so check with AC_LINK_IFELSE.
AC_MSG_CHECKING([for res_nsearch])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
int len;
unsigned char reply[1024];
res_state statep;
len = res_nsearch(
statep, "example.com", ns_c_in, ns_t_srv, reply, sizeof(reply));
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 0)
AC_SUBST(MONGOC_HAVE_RES_NSEARCH, 1)
found_resolv="yes"
dnl We have res_nsearch. Call res_ndestroy (BSD/Mac) or res_nclose (Linux)?
AC_MSG_CHECKING([for res_ndestroy])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
res_state statep;
res_ndestroy(statep);
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 1)
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 0)
AC_MSG_CHECKING([for res_nclose])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
res_state statep;
res_nclose(statep);
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 1)
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
])
])
],[
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NSEARCH, 0)
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 0)
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
dnl Thread-unsafe function.
AC_MSG_CHECKING([for res_search])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
int len;
unsigned char reply[1024];
len = res_search("example.com", ns_c_in, ns_t_srv, reply, sizeof(reply));
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 1)
found_resolv="yes"
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 0)
])
])
LIBS="$old_LIBS"
AS_IF([test "$found_resolv" = "yes"],[
PHP_ADD_LIBRARY([resolv],,[MONGODB_SHARED_LIBADD])
])
mongodb-1.6.1/scripts/autotools/libmongoc/CheckSSL.m4 0000644 0000765 0000024 00000021305 13572250757 022014 0 ustar alcaeus staff PHP_ARG_WITH([mongodb-ssl],
[whether to enable crypto and TLS],
[AS_HELP_STRING([--with-mongodb-ssl=@<:@auto/no/openssl/libressl/darwin@:>@],
[MongoDB: Enable TLS connections and SCRAM-SHA-1 authentication [default=auto]])],
[auto],
[no])
PHP_ARG_WITH([openssl-dir],
[deprecated option for OpenSSL library path],
[AS_HELP_STRING([--with-openssl-dir=@<:@auto/DIR@:>@],
[MongoDB: OpenSSL library path (deprecated for pkg-config) [default=auto]])],
[auto],
[no])
dnl PHP_ARG_WITH without a value assigns "yes". Treat it like "auto" but required.
AS_IF([test "$PHP_MONGODB_SSL" = "yes"],[
crypto_required="yes"
PHP_MONGODB_SSL="auto"
])
AS_IF([test "$PHP_MONGODB_SSL" = "darwin" -o \( "$PHP_MONGODB_SSL" = "auto" -a "$os_darwin" = "yes" \)],[
AC_MSG_NOTICE([checking whether Darwin SSL is available])
if test "$os_darwin" = "no"; then
AC_MSG_ERROR([Darwin SSL is only supported on macOS])
fi
dnl PHP_FRAMEWORKS is only used for SAPI builds, so use MONGODB_SHARED_LIBADD for shared builds
if test "$ext_shared" = "yes"; then
MONGODB_SHARED_LIBADD="-framework Security -framework CoreFoundation $MONGODB_SHARED_LIBADD"
else
PHP_ADD_FRAMEWORK([Security])
PHP_ADD_FRAMEWORK([CoreFoundation])
fi
PHP_MONGODB_SSL="darwin"
])
AS_IF([test "$PHP_MONGODB_SSL" = "openssl" -o "$PHP_MONGODB_SSL" = "auto"],[
AC_MSG_NOTICE([checking whether OpenSSL is available])
found_openssl="no"
PKG_CHECK_MODULES([PHP_MONGODB_SSL],[openssl],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SSL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SSL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="openssl"
found_openssl="yes"
old_CFLAGS="$CFLAGS"
CFLAGS="$PHP_MONGODB_SSL_CFLAGS $CFLAGS"
AC_CHECK_DECLS([ASN1_STRING_get0_data],
[have_ASN1_STRING_get0_data="yes"],
[have_ASN1_STRING_get0_data="no"],
[[#include ]])
CFLAGS="$old_CFLAGS"
],[
unset OPENSSL_INCDIR
unset OPENSSL_LIBDIR
dnl Use a list of directories from PHP_SETUP_OPENSSL by default.
dnl Support documented "auto" and older, undocumented "yes" options
if test "$PHP_OPENSSL_DIR" = "auto" -o "$PHP_OPENSSL_DIR" = "yes"; then
PHP_OPENSSL_DIR="/usr/local/ssl /usr/local /usr /usr/local/openssl"
fi
for i in $PHP_OPENSSL_DIR; do
if test -r $i/include/openssl/evp.h; then
OPENSSL_INCDIR="$i/include"
fi
if test -r $i/$PHP_LIBDIR/libssl.a -o -r $i/$PHP_LIBDIR/libssl.$SHLIB_SUFFIX_NAME; then
OPENSSL_LIBDIR="$i/$PHP_LIBDIR"
fi
test -n "$OPENSSL_INCDIR" && test -n "$OPENSSL_LIBDIR" && break
done
if test -n "$OPENSSL_LIBDIR"; then
OPENSSL_LIBDIR_LDFLAG="-L$OPENSSL_LIBDIR"
fi
PHP_CHECK_LIBRARY([crypto],
[EVP_DigestInit_ex],
[have_crypto_lib="yes"],
[have_crypto_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG])
AC_MSG_NOTICE([checking whether OpenSSL >= 1.1.0 is available])
PHP_CHECK_LIBRARY([ssl],
[OPENSSL_init_ssl],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG -lcrypto])
if test "$have_ssl_lib" = "no"; then
AC_MSG_NOTICE([checking whether OpenSSL < 1.1.0 is available])
PHP_CHECK_LIBRARY([ssl],
[SSL_library_init],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG -lcrypto])
fi
if test "$have_ssl_lib" = "yes" -a "$have_crypto_lib" = "yes"; then
PHP_ADD_LIBRARY([ssl],,[MONGODB_SHARED_LIBADD])
PHP_ADD_LIBRARY([crypto],,[MONGODB_SHARED_LIBADD])
if test -n "$OPENSSL_LIBDIR"; then
PHP_ADD_LIBPATH([$OPENSSL_LIBDIR],[MONGODB_SHARED_LIBADD])
fi
if test -n "$OPENSSL_INCDIR"; then
PHP_ADD_INCLUDE($OPENSSL_INCDIR)
fi
old_CFLAGS="$CFLAGS"
CFLAGS="-I$OPENSSL_INCDIR $CFLAGS"
AC_CHECK_DECLS([ASN1_STRING_get0_data],
[have_ASN1_STRING_get0_data="yes"],
[have_ASN1_STRING_get0_data="no"],
[[#include ]])
CFLAGS="$old_CFLAGS"
PHP_MONGODB_SSL="openssl"
found_openssl="yes"
fi
])
if test "$PHP_MONGODB_SSL" = "openssl" -a "$found_openssl" != "yes"; then
AC_MSG_ERROR([OpenSSL libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_SSL" = "libressl" -o "$PHP_MONGODB_SSL" = "auto"],[
AC_MSG_NOTICE([checking whether LibreSSL is available])
found_libressl="no"
PKG_CHECK_MODULES([PHP_MONGODB_SSL],[libtls libcrypto],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SSL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SSL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="libressl"
found_libressl="yes"
],[
PHP_CHECK_LIBRARY([crypto],
[EVP_DigestInit_ex],
[have_crypto_lib="yes"],
[have_crypto_lib="no"])
PHP_CHECK_LIBRARY([tls],
[tls_init],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[-lcrypto])
if test "$have_ssl_lib" = "yes" -a "$have_crypto_lib" = "yes"; then
PHP_ADD_LIBRARY([tls],,[MONGODB_SHARED_LIBADD])
PHP_ADD_LIBRARY([crypto],,[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="libressl"
found_libressl="yes"
fi
])
if test "$PHP_MONGODB_SSL" = "libressl" -a "$found_libressl" != "yes"; then
AC_MSG_ERROR([LibreSSL libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_SSL" = "auto"],[
if test "x$crypto_required" = "xyes"; then
AC_MSG_ERROR([crypto and TLS libraries not found])
fi
PHP_MONGODB_SSL="no"
])
AC_MSG_CHECKING([which TLS library to use])
AC_MSG_RESULT([$PHP_MONGODB_SSL])
dnl Disable Windows SSL and crypto
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_CHANNEL, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_CNG, 0)
if test "$PHP_MONGODB_SSL" = "openssl" -o "$PHP_MONGODB_SSL" = "libressl" -o "$PHP_MONGODB_SSL" = "darwin"; then
AC_SUBST(MONGOC_ENABLE_SSL, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO, 1)
if test "$PHP_MONGODB_SSL" = "darwin"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 1)
elif test "$PHP_MONGODB_SSL" = "openssl"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 1)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
elif test "$PHP_MONGODB_SSL" = "libressl"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 1)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
fi
else
AC_SUBST(MONGOC_ENABLE_SSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
fi
if test "x$have_ASN1_STRING_get0_data" = "xyes"; then
AC_SUBST(MONGOC_HAVE_ASN1_STRING_GET0_DATA, 1)
else
AC_SUBST(MONGOC_HAVE_ASN1_STRING_GET0_DATA, 0)
fi
PHP_ARG_ENABLE([mongodb-crypto-system-profile],
[whether to use system crypto profile],
[AS_HELP_STRING([--enable-mongodb-crypto-system-profile],
[MongoDB: Use system crypto profile (OpenSSL only) [default=no]])],
[no],
[no])
PHP_ARG_WITH([system-ciphers],
[deprecated option for whether to use system crypto profile],
AS_HELP_STRING([--enable-system-ciphers],
[MongoDB: whether to use system crypto profile (deprecated for --enable-mongodb-crypto-system-profile) [default=no]]),
[no],
[no])
dnl Also consider the deprecated --enable-system-ciphers option
if test "$PHP_MONGODB_CRYPTO_SYSTEM_PROFILE" = "yes" -o "$PHP_SYSTEM_CIPHERS" = "yes"; then
if test "$PHP_MONGODB_SSL" = "openssl"; then
AC_SUBST(MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE, 1)
else
AC_MSG_ERROR([System crypto profile is only available with OpenSSL])
fi
else
AC_SUBST(MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE, 0)
fi
mongodb-1.6.1/scripts/autotools/libmongoc/CheckSasl.m4 0000644 0000765 0000024 00000005107 13572250757 022257 0 ustar alcaeus staff PHP_ARG_WITH([mongodb-sasl],
[whether to enable SASL for Kerberos authentication],
[AS_HELP_STRING([--with-mongodb-sasl=@<:@auto/no/cyrus@:>@],
[MongoDB: Enable SASL for Kerberos authentication [default=auto]])],
[auto],
[no])
dnl PHP_ARG_WITH without a value assigns "yes". Treat it like "auto" but required.
AS_IF([test "$PHP_MONGODB_SASL" = "cyrus" -o "$PHP_MONGODB_SASL" = "auto" -o "$PHP_MONGODB_SASL" = "yes"],[
found_cyrus="no"
PKG_CHECK_MODULES([PHP_MONGODB_SASL],[libsasl2],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SASL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SASL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SASL="cyrus"
found_cyrus="yes"
],[
PHP_CHECK_LIBRARY([sasl2],
[sasl_client_init],
[have_sasl2_lib="yes"],
[have_sasl2_lib="no"])
AC_CHECK_HEADER([sasl/sasl.h],
[have_sasl_headers=yes],
[have_sasl_headers=no])
if test "$have_sasl2_lib" = "yes" -a "$have_sasl_headers" = "yes"; then
PHP_ADD_LIBRARY([sasl2],,[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SASL="cyrus"
found_cyrus="yes"
fi
])
if test "$found_cyrus" = "yes"; then
PHP_CHECK_LIBRARY([sasl2],
[sasl_client_done],
[have_sasl_client_done=yes],
[have_sasl_client_done=no],
$MONGODB_SHARED_LIBADD)
fi
if test \( "$PHP_MONGODB_SASL" = "cyrus" -o "$PHP_MONGODB_SASL" = "yes" \) -a "$found_cyrus" != "yes"; then
AC_MSG_ERROR([Cyrus SASL libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_SASL" = "auto"],[
PHP_MONGODB_SASL="no"
])
dnl Warn for unsupported values (e.g. Cyrus SASL search path)
if test ! \( "$PHP_MONGODB_SASL" = "cyrus" -o "$PHP_MONGODB_SASL" = "no" \); then
AC_MSG_WARN([unsupported --with-mongodb-sasl value: $PHP_MONGODB_SASL])
fi
AC_MSG_CHECKING([which SASL library to use])
AC_MSG_RESULT([$PHP_MONGODB_SASL])
dnl Disable Windows SSPI and GSSAPI
AC_SUBST(MONGOC_ENABLE_SASL_SSPI, 0)
AC_SUBST(MONGOC_ENABLE_SASL_GSSAPI, 0)
if test "$PHP_MONGODB_SASL" = "cyrus"; then
AC_SUBST(MONGOC_ENABLE_SASL, 1)
AC_SUBST(MONGOC_ENABLE_SASL_CYRUS, 1)
if test "x$have_sasl_client_done" = "xyes"; then
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 1)
else
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 0)
fi
else
AC_SUBST(MONGOC_ENABLE_SASL, 0)
AC_SUBST(MONGOC_ENABLE_SASL_CYRUS, 0)
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 0)
fi
mongodb-1.6.1/scripts/autotools/libmongoc/FindDependencies.m4 0000644 0000765 0000024 00000003117 13572250757 023605 0 ustar alcaeus staff # Solaris needs to link against socket libs
if test "$os_solaris" = "yes"; then
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D__EXTENSIONS__"
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D_XOPEN_SOURCE=1"
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D_XOPEN_SOURCE_EXTENDED=1"
PHP_ADD_LIBRARY([socket],,[MONGODB_SHARED_LIBADD])
PHP_ADD_LIBRARY([nsl],,[MONGODB_SHARED_LIBADD])
fi
# Check for shm functions
AC_CHECK_FUNCS([shm_open],[],[
AC_CHECK_LIB([rt],
[shm_open],
[PHP_ADD_LIBRARY([rt],,[MONGODB_SHARED_LIBADD])],
[])
])
# Check for sched_getcpu
AC_CHECK_FUNC([sched_getcpu],
[AC_SUBST(MONGOC_HAVE_SCHED_GETCPU, 1)],
[AC_SUBST(MONGOC_HAVE_SCHED_GETCPU, 0)])
AC_CHECK_TYPE([socklen_t],
[AC_SUBST(MONGOC_HAVE_SOCKLEN, 1)],
[AC_SUBST(MONGOC_HAVE_SOCKLEN, 0)],
[#include ])
# Check for pthreads. libmongoc's original FindDependencies.m4 script did not
# require pthreads, but it does appear to be necessary on non-Windows platforms
# based on mongoc-openssl.c and mongoc-thread-private.h.
AX_PTHREAD([
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PTHREAD_CFLAGS"
PHP_EVAL_LIBLINE([$PTHREAD_LIBS],[MONGODB_SHARED_LIBADD])
# PTHREAD_CFLAGS may come back as "-pthread", which should also be used when
# linking. We can trust PHP_EVAL_LIBLINE to ignore other values.
PHP_EVAL_LIBLINE([$PTHREAD_CFLAGS],[MONGODB_SHARED_LIBADD])
],[
AC_MSG_ERROR([libmongoc requires pthreads on non-Windows platforms.])
])
mongodb-1.6.1/scripts/autotools/libmongoc/PlatformFlags.m4 0000644 0000765 0000024 00000001623 13572250757 023157 0 ustar alcaeus staff dnl Ignore OpenSSL deprecation warnings on OSX
AS_IF([test "$os_darwin" = "yes"],
[AX_CHECK_COMPILE_FLAG([-Wno-deprecated-declarations], [STD_CFLAGS="$STD_CFLAGS -Wno-deprecated-declarations"])])
dnl We know there are some cast-align issues on OSX
AS_IF([test "$os_darwin" = "yes"],
[AX_CHECK_COMPILE_FLAG([-Wno-cast-align], [STD_CFLAGS="$STD_CFLAGS -Wno-cast-align"])])
AS_IF([test "$os_darwin" = "yes"],
[AX_CHECK_COMPILE_FLAG([-Wno-unneeded-internal-declaration], [STD_CFLAGS="$STD_CFLAGS -Wno-unneeded-internal-declaration"])])
AS_IF([test "$os_darwin" = "yes"],
[AX_CHECK_COMPILE_FLAG([-Wno-error=unused-command-line-argument], [STD_CFLAGS="$STD_CFLAGS -Wno-error=unused-command-line-argument"])])
dnl We know there are some cast-align issues on Solaris
AS_IF([test "$os_solaris" = "yes"],
[AX_CHECK_COMPILE_FLAG([-Wno-cast-align], [STD_CFLAGS="$STD_CFLAGS -Wno-cast-align"])])
mongodb-1.6.1/scripts/autotools/libmongoc/Versions.m4 0000644 0000765 0000024 00000001242 13572250757 022223 0 ustar alcaeus staff MONGOC_CURRENT_FILE=[]PHP_EXT_SRCDIR(mongodb)[/src/LIBMONGOC_VERSION_CURRENT]
MONGOC_VERSION=$(cat $MONGOC_CURRENT_FILE)
dnl Ensure newline for "cut" implementations that need it, e.g. HP-UX.
MONGOC_MAJOR_VERSION=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f1 )
MONGOC_MINOR_VERSION=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f2 )
MONGOC_MICRO_VERSION=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f3 )
MONGOC_PRERELEASE_VERSION=$(cut -s -d- -f2 $MONGOC_CURRENT_FILE)
AC_SUBST(MONGOC_VERSION)
AC_SUBST(MONGOC_MAJOR_VERSION)
AC_SUBST(MONGOC_MINOR_VERSION)
AC_SUBST(MONGOC_MICRO_VERSION)
AC_SUBST(MONGOC_PRERELEASE_VERSION)
mongodb-1.6.1/scripts/autotools/libmongoc/WeakSymbols.m4 0000644 0000765 0000024 00000000401 13572250757 022647 0 ustar alcaeus staff AC_MSG_CHECKING(if weak symbols are supported)
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
__attribute__((weak)) void __dummy(void *x) { }
void f(void *x) { __dummy(x); }
]], [[ ]]
)],
[AC_MSG_RESULT(yes)
AC_SUBST(MONGOC_HAVE_WEAK_SYMBOLS, 1)],
[AC_MSG_RESULT(no)])
mongodb-1.6.1/scripts/autotools/m4/as_var_copy.m4 0000644 0000765 0000024 00000000402 13572250757 021264 0 ustar alcaeus staff dnl AS_VAR_COPY is available in AC 2.64 and on, but we only require 2.59.
dnl If we're on an older version, we define it ourselves:
m4_ifndef([AS_VAR_COPY],
[m4_define([AS_VAR_COPY],
[AS_LITERAL_IF([$1[]$2], [$1=$$2], [eval $1=\$$2])])])
mongodb-1.6.1/scripts/autotools/m4/ax_check_compile_flag.m4 0000644 0000765 0000024 00000006251 13572250757 023235 0 ustar alcaeus staff # ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS])
#
# DESCRIPTION
#
# Check whether the given FLAG works with the current language's compiler
# or gives an error. (Warnings, however, are ignored)
#
# ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on
# success/failure.
#
# If EXTRA-FLAGS is defined, it is added to the current language's default
# flags (e.g. CFLAGS) when the check is done. The check is thus made with
# the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to
# force the compiler to issue an error when a bad flag is given.
#
# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this
# macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG.
#
# LICENSE
#
# Copyright (c) 2008 Guido U. Draheim
# Copyright (c) 2011 Maarten Bosmans
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 2
AC_DEFUN([AX_CHECK_COMPILE_FLAG],
[AC_PREREQ(2.59)dnl for _AC_LANG_PREFIX
AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl
AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [
ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS
_AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM()],
[AS_VAR_SET(CACHEVAR,[yes])],
[AS_VAR_SET(CACHEVAR,[no])])
_AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags])
AS_IF([test x"AS_VAR_GET(CACHEVAR)" = xyes],
[m4_default([$2], :)],
[m4_default([$3], :)])
AS_VAR_POPDEF([CACHEVAR])dnl
])dnl AX_CHECK_COMPILE_FLAGS
mongodb-1.6.1/scripts/autotools/m4/ax_prototype.m4 0000644 0000765 0000024 00000017267 13572250757 021535 0 ustar alcaeus staff # ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_prototype.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PROTOTYPE(function, includes, code, TAG1, values1 [, TAG2, values2 [...]])
#
# DESCRIPTION
#
# Try all the combinations of , ... to successfully compile
# . , , ... are substituted in and with
# values found in , , ... respectively. ,
# , ... contain a list of possible values for each corresponding
# tag and all combinations are tested. When AC_TRY_COMPILE(include, code)
# is successfull for a given substitution, the macro stops and defines the
# following macros: FUNCTION_TAG1, FUNCTION_TAG2, ... using AC_DEFINE()
# with values set to the current values of , , ... If no
# combination is successfull the configure script is aborted with a
# message.
#
# Intended purpose is to find which combination of argument types is
# acceptable for a given function . It is recommended to list
# the most specific types first. For instance ARG1, [size_t, int] instead
# of ARG1, [int, size_t].
#
# Generic usage pattern:
#
# 1) add a call in configure.in
#
# AX_PROTOTYPE(...)
#
# 2) call autoheader to see which symbols are not covered
#
# 3) add the lines in acconfig.h
#
# /* Type of Nth argument of function */
# #undef FUNCTION_ARGN
#
# 4) Within the code use FUNCTION_ARGN instead of an hardwired type
#
# Complete example:
#
# 1) configure.in
#
# AX_PROTOTYPE(getpeername,
# [
# #include
# #include
# ],
# [
# int a = 0;
# ARG2 * b = 0;
# ARG3 * c = 0;
# getpeername(a, b, c);
# ],
# ARG2, [struct sockaddr, void],
# ARG3, [socklen_t, size_t, int, unsigned int, long unsigned int])
#
# 2) call autoheader
#
# autoheader: Symbol `GETPEERNAME_ARG2' is not covered by ./acconfig.h
# autoheader: Symbol `GETPEERNAME_ARG3' is not covered by ./acconfig.h
#
# 3) acconfig.h
#
# /* Type of second argument of getpeername */
# #undef GETPEERNAME_ARG2
#
# /* Type of third argument of getpeername */
# #undef GETPEERNAME_ARG3
#
# 4) in the code
#
# ...
# GETPEERNAME_ARG2 name;
# GETPEERNAME_ARG3 namelen;
# ...
# ret = getpeername(socket, &name, &namelen);
# ...
#
# Implementation notes: generating all possible permutations of the
# arguments is not easily done with the usual mixture of shell and m4,
# that is why this macro is almost 100% m4 code. It generates long but
# simple to read code.
#
# LICENSE
#
# Copyright (c) 2009 Loic Dachary
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 6
AU_ALIAS([AC_PROTOTYPE], [AX_PROTOTYPE])
AC_DEFUN([AX_PROTOTYPE],[
dnl
dnl Upper case function name
dnl
pushdef([function],translit([$1], [a-z], [A-Z]))
dnl
dnl Collect tags that will be substituted
dnl
pushdef([tags],[AX_PROTOTYPE_TAGS(builtin([shift],builtin([shift],builtin([shift],$@))))])
dnl
dnl Wrap in a 1 time loop, when a combination is found break to stop the combinatory exploration
dnl
for i in 1
do
AX_PROTOTYPE_LOOP(AX_PROTOTYPE_REVERSE($1, AX_PROTOTYPE_SUBST($2,tags),AX_PROTOTYPE_SUBST($3,tags),builtin([shift],builtin([shift],builtin([shift],$@)))))
AC_MSG_ERROR($1 unable to find a working combination)
done
popdef([tags])
popdef([function])
])
dnl
dnl AX_PROTOTYPE_REVERSE(list)
dnl
dnl Reverse the order of the
dnl
AC_DEFUN([AX_PROTOTYPE_REVERSE],[ifelse($#,0,,$#,1,[[$1]],[AX_PROTOTYPE_REVERSE(builtin([shift],$@)),[$1]])])
dnl
dnl AX_PROTOTYPE_SUBST(string, tag)
dnl
dnl Substitute all occurence of in with _VAL.
dnl Assumes that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_SUBST],[ifelse($2,,[$1],[AX_PROTOTYPE_SUBST(patsubst([$1],[$2],[$2[]_VAL]),builtin([shift],builtin([shift],$@)))])])
dnl
dnl AX_PROTOTYPE_TAGS([tag, values, [tag, values ...]])
dnl
dnl Generate a list of by skipping .
dnl
AC_DEFUN([AX_PROTOTYPE_TAGS],[ifelse($1,,[],[$1, AX_PROTOTYPE_TAGS(builtin([shift],builtin([shift],$@)))])])
dnl
dnl AX_PROTOTYPE_DEFINES(tags)
dnl
dnl Generate a AC_DEFINE(function_tag, tag_VAL) for each tag in list
dnl Assumes that function is a macro containing the name of the function in upper case
dnl and that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_DEFINES],[ifelse($1,,[],
[AC_DEFINE(function[]_$1, $1_VAL, [ ])
AC_SUBST(function[]_$1, "$1_VAL")
AX_PROTOTYPE_DEFINES(builtin([shift],$@))])])
dnl
dnl AX_PROTOTYPE_STATUS(tags)
dnl
dnl Generates a message suitable for argument to AC_MSG_* macros. For each tag
dnl in the list the message tag => tag_VAL is generated.
dnl Assumes that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_STATUS],[ifelse($1,,[],[$1 => $1_VAL AX_PROTOTYPE_STATUS(builtin([shift],$@))])])
dnl
dnl AX_PROTOTYPE_EACH(tag, values)
dnl
dnl Call AX_PROTOTYPE_LOOP for each values and define the macro tag_VAL to
dnl the current value.
dnl
AC_DEFUN([AX_PROTOTYPE_EACH],[
ifelse($2,, [
], [
pushdef([$1_VAL], $2)
AX_PROTOTYPE_LOOP(rest)
popdef([$1_VAL])
AX_PROTOTYPE_EACH($1, builtin([shift], builtin([shift], $@)))
])
])
dnl
dnl AX_PROTOTYPE_LOOP([tag, values, [tag, values ...]], code, include, function)
dnl
dnl If there is a tag/values pair, call AX_PROTOTYPE_EACH with it.
dnl If there is no tag/values pair left, tries to compile the code and include
dnl using AC_TRY_COMPILE. If it compiles, AC_DEFINE all the tags to their
dnl current value and exit with success.
dnl
AC_DEFUN([AX_PROTOTYPE_LOOP],[
ifelse(builtin([eval], $# > 3), 1,
[
pushdef([rest],[builtin([shift],builtin([shift],$@))])
AX_PROTOTYPE_EACH($2,$1)
popdef([rest])
], [
AC_MSG_CHECKING($3 AX_PROTOTYPE_STATUS(tags))
dnl
dnl Activate fatal warnings if possible, gives better guess
dnl
ac_save_CPPFLAGS="$CPPFLAGS"
if test "$GCC" = "yes" ; then CPPFLAGS="$CPPFLAGS -Werror" ; fi
AC_TRY_COMPILE($2, $1, [
CPPFLAGS="$ac_save_CPPFLAGS"
AC_MSG_RESULT(ok)
AX_PROTOTYPE_DEFINES(tags)
break;
], [
CPPFLAGS="$ac_save_CPPFLAGS"
AC_MSG_RESULT(not ok)
])
]
)
])
mongodb-1.6.1/scripts/autotools/m4/ax_pthread.m4 0000644 0000765 0000024 00000033030 13572250757 021101 0 ustar alcaeus staff # ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_pthread.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
# This macro figures out how to build C programs using POSIX threads. It
# sets the PTHREAD_LIBS output variable to the threads library and linker
# flags, and the PTHREAD_CFLAGS output variable to any special C compiler
# flags that are needed. (The user can also force certain compiler
# flags/libs to be tested by setting these environment variables.)
#
# Also sets PTHREAD_CC to any special C compiler that is needed for
# multi-threaded programs (defaults to the value of CC otherwise). (This
# is necessary on AIX to use the special cc_r compiler alias.)
#
# NOTE: You are assumed to not only compile your program with these flags,
# but also link it with them as well. e.g. you should link with
# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#
# If you are only building threads programs, you may wish to use these
# variables in your default LIBS, CFLAGS, and CC:
#
# LIBS="$PTHREAD_LIBS $LIBS"
# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# CC="$PTHREAD_CC"
#
# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
# has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name
# (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
#
# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
# PTHREAD_PRIO_INHERIT symbol is defined when compiling with
# PTHREAD_CFLAGS.
#
# ACTION-IF-FOUND is a list of shell commands to run if a threads library
# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
# is not found. If ACTION-IF-FOUND is not specified, the default action
# will define HAVE_PTHREAD.
#
# Please let the authors know if this macro fails on any platform, or if
# you have any other suggestions or comments. This macro was based on work
# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
# Alejandro Forero Cuervo to the autoconf macro repository. We are also
# grateful for the helpful feedback of numerous users.
#
# Updated for Autoconf 2.68 by Daniel Richard G.
#
# LICENSE
#
# Copyright (c) 2008 Steven G. Johnson
# Copyright (c) 2011 Daniel Richard G.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 21
AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
AC_DEFUN([AX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_LANG_PUSH([C])
ax_pthread_ok=no
# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on True64 or Sequent).
# It gets checked for in the link test anyway.
# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
AC_TRY_LINK_FUNC([pthread_join], [ax_pthread_ok=yes])
AC_MSG_RESULT([$ax_pthread_ok])
if test x"$ax_pthread_ok" = xno; then
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
fi
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
fi
# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).
# Create a list of thread flags to try. Items starting with a "-" are
# C compiler flags, and other items are library names, except for "none"
# which indicates that we try without any flags at all, and "pthread-config"
# which is a program returning the flags for the Pth emulation library.
ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
# The ordering *is* (sometimes) important. Some notes on the
# individual items follow:
# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
# other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
# -pthreads: Solaris/gcc
# -mthreads: Mingw32/gcc, Lynx/gcc
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
# doesn't hurt to check since this sometimes defines pthreads too;
# also defines -D_REENTRANT)
# ... -mt is also the pthreads flag for HP/aCC
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)
case ${host_os} in
solaris*)
# On Solaris (at least, for some versions), libc contains stubbed
# (non-functional) versions of the pthreads routines, so link-based
# tests will erroneously succeed. (We need to link with -pthreads/-mt/
# -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
# a function called by this macro, so we could check for that, but
# who knows whether they'll stub that too in a future libc.) So,
# we'll just look for -pthreads and -lpthread first:
ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
;;
darwin*)
if test "$c_compiler" != "clang"; then
ax_pthread_flags="-pthread $ax_pthread_flags"
fi
;;
esac
# Clang doesn't consider unrecognized options an error unless we specify
# -Werror. We throw in some extra Clang-specific options to ensure that
# this doesn't happen for GCC, which also accepts -Werror.
AC_MSG_CHECKING([if compiler needs -Werror to reject unknown flags])
save_CFLAGS="$CFLAGS"
ax_pthread_extra_flags="-Werror"
CFLAGS="$CFLAGS $ax_pthread_extra_flags -Wunknown-warning-option -Wsizeof-array-argument"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([int foo(void);],[foo()])],
[AC_MSG_RESULT([yes])],
[ax_pthread_extra_flags=
AC_MSG_RESULT([no])])
CFLAGS="$save_CFLAGS"
if test x"$ax_pthread_ok" = xno; then
for flag in $ax_pthread_flags; do
case $flag in
none)
AC_MSG_CHECKING([whether pthreads work without any flags])
;;
-*)
AC_MSG_CHECKING([whether pthreads work with $flag])
PTHREAD_CFLAGS="$flag"
;;
pthread-config)
AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
if test x"$ax_pthread_config" = xno; then continue; fi
PTHREAD_CFLAGS="`pthread-config --cflags`"
PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
;;
*)
AC_MSG_CHECKING([for the pthreads library -l$flag])
PTHREAD_LIBS="-l$flag"
;;
esac
save_LIBS="$LIBS"
save_CFLAGS="$CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS $ax_pthread_extra_flags"
# Check for various functions. We must include pthread.h,
# since some functions may be macros. (On the Sequent, we
# need a special flag -Kthread to make this header compile.)
# We check for pthread_join because it is in -lpthread on IRIX
# while pthread_create is in libc. We check for pthread_attr_init
# due to DEC craziness with -lpthreads. We check for
# pthread_cleanup_push because it is one of the few pthread
# functions on Solaris that doesn't have a non-functional libc stub.
# We try pthread_create on general principles.
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include
static void routine(void *a) { a = 0; }
static void *start_routine(void *a) { return a; }],
[pthread_t th; pthread_attr_t attr;
pthread_create(&th, 0, start_routine, 0);
pthread_join(th, 0);
pthread_attr_init(&attr);
pthread_cleanup_push(routine, 0);
pthread_cleanup_pop(0) /* ; */])],
[ax_pthread_ok=yes],
[])
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
AC_MSG_RESULT([$ax_pthread_ok])
if test "x$ax_pthread_ok" = xyes; then
break;
fi
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
done
fi
# Various other checks:
if test "x$ax_pthread_ok" = xyes; then
save_LIBS="$LIBS"
LIBS="$PTHREAD_LIBS $LIBS"
save_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
AC_MSG_CHECKING([for joinable pthread attribute])
attr_name=unknown
for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ],
[int attr = $attr; return attr /* ; */])],
[attr_name=$attr; break],
[])
done
AC_MSG_RESULT([$attr_name])
if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE], [$attr_name],
[Define to necessary symbol if this constant
uses a non-standard name on your system.])
fi
AC_MSG_CHECKING([if more special flags are required for pthreads])
flag=no
case ${host_os} in
aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
osf* | hpux*) flag="-D_REENTRANT";;
solaris*)
if test "$GCC" = "yes"; then
flag="-D_REENTRANT"
else
# TODO: What about Clang on Solaris?
flag="-mt -D_REENTRANT"
fi
;;
esac
AC_MSG_RESULT([$flag])
if test "x$flag" != xno; then
PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
fi
AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
[ax_cv_PTHREAD_PRIO_INHERIT], [
AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]],
[[int i = PTHREAD_PRIO_INHERIT;]])],
[ax_cv_PTHREAD_PRIO_INHERIT=yes],
[ax_cv_PTHREAD_PRIO_INHERIT=no])
])
AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"],
[AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])])
LIBS="$save_LIBS"
CFLAGS="$save_CFLAGS"
# More AIX lossage: compile with *_r variant
if test "x$GCC" != xyes; then
case $host_os in
aix*)
AS_CASE(["x/$CC"],
[x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
[#handle absolute path differently from PATH based program lookup
AS_CASE(["x$CC"],
[x/*],
[AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])],
[AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])])])
;;
esac
fi
fi
test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
AC_SUBST([PTHREAD_LIBS])
AC_SUBST([PTHREAD_CFLAGS])
AC_SUBST([PTHREAD_CC])
# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test x"$ax_pthread_ok" = xyes; then
ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
:
else
ax_pthread_ok=no
$2
fi
AC_LANG_POP
])dnl AX_PTHREAD
mongodb-1.6.1/scripts/autotools/m4/php_mongodb.m4 0000644 0000765 0000024 00000002617 13572250757 021265 0 ustar alcaeus staff dnl
dnl PHP_MONGODB_ADD_SOURCES(source-path, sources [, special-flags])
dnl
dnl Adds sources which are located relative to source-path. source-path should
dnl be relative to the extension directory (i.e. PHP_EXT_DIR). special-flags
dnl will be passed to the compiler.
dnl
dnl This macro will call PHP_ADD_SOURCES or PHP_ADD_SOURCES_X depending on
dnl whether the extension is being built statically or as a shared module.
dnl
AC_DEFUN([PHP_MONGODB_ADD_SOURCES],[
_src_path=PHP_EXT_DIR(mongodb)
dnl Join extension directory and source path
case $_src_path in
""[)] _src_path="$1" ;;
*/[)] _src_path="$_src_path$1" ;;
*[)] _src_path="$_src_path/$1" ;;
esac
dnl Trim trailing slash from source path
case $_src_path in
*/[)] _src_path=${_src_path%?}
esac
if test "$ext_shared" = "no"; then
PHP_ADD_SOURCES($_src_path, [$2], [$3])
else
PHP_ADD_SOURCES_X($_src_path, [$2], [$3], shared_objects_mongodb, yes)
fi
])
dnl
dnl PHP_MONGODB_ADD_INCLUDE(path)
dnl
dnl Adds an include path relative to the extension source directory (i.e.
dnl PHP_EXT_SRCDIR).
dnl
AC_DEFUN([PHP_MONGODB_ADD_INCLUDE],[
PHP_ADD_INCLUDE(PHP_EXT_SRCDIR(mongodb)[/][$1])
])
dnl
dnl PHP_MONGODB_ADD_BUILD_DIR(path)
dnl
dnl Adds a build directory relative to the extension build directory (i.e.
dnl PHP_EXT_BUILDDIR).
dnl
AC_DEFUN([PHP_MONGODB_ADD_BUILD_DIR],[
PHP_ADD_BUILD_DIR(PHP_EXT_BUILDDIR(mongodb)[/][$1])
])
mongodb-1.6.1/scripts/autotools/m4/pkg.m4 0000644 0000765 0000024 00000016231 13572250757 017547 0 ustar alcaeus staff # pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
# serial 1 (pkg-config-0.24)
#
# Copyright © 2004 Scott James Remnant .
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])# PKG_PROG_PKG_CONFIG
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists. Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
# only at the first occurence in configure.ac, so if the first place
# it's called might be skipped (such as if it is within an "if", you
# have to call PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_default([$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$$1"; then
pkg_cv_[]$1="$$1"
elif test -n "$PKG_CONFIG"; then
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
test "x$?" != "x0" && pkg_failed=yes ],
[pkg_failed=yes])
else
pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG
# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $1])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
AC_MSG_RESULT([no])
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
m4_default([$4], [AC_MSG_ERROR(
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT])[]dnl
])
elif test $pkg_failed = untried; then
AC_MSG_RESULT([no])
m4_default([$4], [AC_MSG_FAILURE(
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see .])[]dnl
])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
$3
fi[]dnl
])# PKG_CHECK_MODULES
# PKG_INSTALLDIR(DIRECTORY)
# -------------------------
# Substitutes the variable pkgconfigdir as the location where a module
# should install pkg-config .pc files. By default the directory is
# $libdir/pkgconfig, but the default can be changed by passing
# DIRECTORY. The user can override through the --with-pkgconfigdir
# parameter.
AC_DEFUN([PKG_INSTALLDIR],
[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
m4_pushdef([pkg_description],
[pkg-config installation directory @<:@]pkg_default[@:>@])
AC_ARG_WITH([pkgconfigdir],
[AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
[with_pkgconfigdir=]pkg_default)
AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
m4_popdef([pkg_default])
m4_popdef([pkg_description])
]) dnl PKG_INSTALLDIR
# PKG_NOARCH_INSTALLDIR(DIRECTORY)
# -------------------------
# Substitutes the variable noarch_pkgconfigdir as the location where a
# module should install arch-independent pkg-config .pc files. By
# default the directory is $datadir/pkgconfig, but the default can be
# changed by passing DIRECTORY. The user can override through the
# --with-noarch-pkgconfigdir parameter.
AC_DEFUN([PKG_NOARCH_INSTALLDIR],
[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
m4_pushdef([pkg_description],
[pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
AC_ARG_WITH([noarch-pkgconfigdir],
[AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
[with_noarch_pkgconfigdir=]pkg_default)
AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
m4_popdef([pkg_default])
m4_popdef([pkg_description])
]) dnl PKG_NOARCH_INSTALLDIR
mongodb-1.6.1/scripts/autotools/CheckCompiler.m4 0000644 0000765 0000024 00000005237 13572250757 021162 0 ustar alcaeus staff # If CFLAGS and CXXFLAGS are unset, default to empty.
# This is to tell automake not to include '-g' if C{XX,}FLAGS is not set.
# For more info - http://www.gnu.org/software/automake/manual/autoconf.html#C_002b_002b-Compiler
if test -z "$CXXFLAGS"; then
CXXFLAGS=""
fi
if test -z "$CFLAGS"; then
CFLAGS=""
fi
AC_PROG_CC
AC_PROG_CXX
# Check that an appropriate C compiler is available.
c_compiler="unknown"
AC_LANG_PUSH([C])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if !(defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER))
#error Not a supported GCC compiler
#endif
#if defined(__GNUC__)
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40100
#error Not a supported GCC compiler
#endif
#endif
])], [c_compiler="gcc"], [])
# If our BEGIN_IGNORE_DEPRECATIONS macro won't work, pass
# -Wno-deprecated-declarations
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if !defined(__clang__) && defined(__GNUC__)
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40600
#error Does not support deprecation warning pragmas
#endif
#endif
])], [], [STD_CFLAGS="$STD_CFLAGS -Wno-deprecated-declarations"])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if defined(__clang__)
#define CLANG_VERSION (__clang_major__ * 10000 \
+ __clang_minor__ * 100 \
+ __clang_patchlevel__)
#if CLANG_VERSION < 30300
#error Not a supported Clang compiler
#endif
#endif
])], [c_compiler="clang"], [])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if !(defined(__SUNPRO_C))
#error Not a supported Sun compiler
#endif
])], [c_compiler="sun"], [])
# The type of parameters for accept, getpeername, getsockname, getsockopt
# all vary the same way by platform.
AX_PROTOTYPE(accept, [
#include
#include
], [
int a = 0;
ARG2 *b = 0;
ARG3 *c = 0;
accept (a, b, c);],
ARG2, [struct sockaddr, void],
ARG3, [socklen_t, size_t, int])
MONGOC_SOCKET_ARG2="$ACCEPT_ARG2"
AC_SUBST(MONGOC_SOCKET_ARG2)
MONGOC_SOCKET_ARG3="$ACCEPT_ARG3"
AC_SUBST(MONGOC_SOCKET_ARG3)
AC_LANG_POP([C])
if test "$c_compiler" = "unknown"; then
AC_MSG_ERROR([Compiler GCC >= 4.1 or Clang >= 3.3 is required for C compilation])
fi
# GLibc 2.19 complains about both _BSD_SOURCE and _GNU_SOURCE. The _GNU_SOURCE
# contains everything anyway. So just use that.
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
#ifndef __GLIBC__
#error not glibc
#endif
]], [])],
LIBC_FEATURES="-D_GNU_SOURCE",
LIBC_FEATURES="-D_BSD_SOURCE")
AC_SUBST(LIBC_FEATURES)
AC_C_CONST
AC_C_INLINE
AC_C_TYPEOF
mongodb-1.6.1/scripts/autotools/CheckHost.m4 0000644 0000765 0000024 00000001644 13572250757 020323 0 ustar alcaeus staff AC_CANONICAL_HOST
os_win32=no
os_netbsd=no
os_freebsd=no
os_openbsd=no
os_hpux=no
os_linux=no
os_solaris=no
os_darwin=no
os_gnu=no
case "$host" in
*-mingw*|*-*-cygwin*)
os_win32=yes
TARGET_OS=windows
;;
*-*-*netbsd*)
os_netbsd=yes
TARGET_OS=unix
;;
*-*-*freebsd*)
os_freebsd=yes
TARGET_OS=unix
;;
*-*-*openbsd*)
os_openbsd=yes
TARGET_OS=unix
;;
*-*-hpux*)
os_hpux=yes
TARGET_OS=unix
;;
*-*-linux*)
os_linux=yes
os_gnu=yes
TARGET_OS=unix
;;
*-*-solaris*)
os_solaris=yes
TARGET_OS=unix
;;
*-*-darwin*)
os_darwin=yes
TARGET_OS=unix
;;
gnu*|k*bsd*-gnu*)
os_gnu=yes
TARGET_OS=unix
;;
*)
AC_MSG_WARN([*** Please add $host to configure.ac checks!])
;;
esac
mongodb-1.6.1/scripts/centos/ldap/Domain.ldif 0000644 0000765 0000024 00000000127 13572250757 020432 0 ustar alcaeus staff dn: dc=10gen,dc=me
objectClass: dcObject
objectClass: organization
dc: 10gen
o : 10gen
mongodb-1.6.1/scripts/centos/ldap/Users.ldif 0000644 0000765 0000024 00000000106 13572250757 020321 0 ustar alcaeus staff dn: ou=Users,dc=10gen,dc=me
ou: Users
objectClass: organizationalUnit
mongodb-1.6.1/scripts/centos/ldap/basics.ldif 0000644 0000765 0000024 00000000244 13572250757 020467 0 ustar alcaeus staff dn: dc=10gen,dc=me
objectclass: dcObject
objectclass: organization
o: MongoDB
dc: 10gen
dn: cn=Manager,dc=10gen,dc=me
objectclass: organizationalRole
cn: Manager
mongodb-1.6.1/scripts/centos/ldap/install.sh 0000644 0000765 0000024 00000001141 13572250757 020362 0 ustar alcaeus staff yum -y update
yum -y install openldap-servers openldap-clients openldap-devel python-devel gcc cyrus-sasl-plain xfsprogs net-snmp ps-misc wget python-ldap
service slapd stop
service slapd start
#just in case
sleep 10
ldapadd -Y EXTERNAL -H ldapi:/// -f /phongo/scripts/centos/ldap/pw.ldif
# Add our specifics
ldapadd -x -D "cn=Manager,dc=10gen,dc=me" -w password -f /phongo/scripts/centos/ldap/Domain.ldif
ldapadd -x -D "cn=Manager,dc=10gen,dc=me" -w password -f /phongo/scripts/centos/ldap/Users.ldif
# Add the users
python /phongo/scripts/centos/ldap/ldapconfig.py -f /phongo/scripts/centos/ldap/users
mongodb-1.6.1/scripts/centos/ldap/ldapconfig.py 0000644 0000765 0000024 00000003750 13572250757 021050 0 ustar alcaeus staff #!/usr/bin/python
import optparse
import ldap
import ldap.modlist as modlist
def main():
parser = optparse.OptionParser(usage="""\
%prog [options]
Add users to LDAP """)
# add in command line options. Add mongo host/port combo later
parser.add_option("-f", "--filename", dest="fname",
help="name of file with user names",
default=None)
(options, args) = parser.parse_args()
if options.fname is None:
print "\nERROR: Must specify name of file to import\n"
sys.exit(-1)
# Open a connection
l = ldap.initialize("ldap://localhost")
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("cn=Manager,dc=10gen,dc=me","password")
for uname in open(options.fname, 'r'):
try:
# The dn of our new entry/object
print "adding ", uname
dn= 'uid=' + uname.lower() + ',ou=Users,dc=10gen,dc=me'
ldif = configUser(uname.rstrip('\r\n'))
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
except ldap.LDAPError, e:
print e.message['info']
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
# Do the tld configuration for the ldap tree
def configDC():
# A dict to help build the "body" of the object
attrs = {}
attrs['objectclass'] = ['organization','dcObject']
attrs['dn'] = 'dc=10gen,dc=me'
attrs['dc'] = '10gen'
attrs['o'] = '10gen'
# Convert our dict to nice syntax for the add-function using modlist
ldif = modlist.addModlist(attrs)
def configOU():
# A dict to help build the "body" of the object
attrs = {}
attrs['dn'] = 'dc=10gen,dc=me'
attrs['objectclass'] = ['organiationalUnit']
attrs['ou'] = 'Users'
ldif = modlist.addModlist(attrs)
def configUser( uname ):
attrs = {}
# attrs['dn'] = ['cn=' + uname + 'ou=Users,dc=10gen,dc=me']
attrs['cn'] = [uname]
# attrs['uid'] = [uname]
attrs['sn'] = 'TestUser'
attrs['objectclass'] = ['inetOrgPerson']
attrs['userPassword'] = 'password'
return modlist.addModlist(attrs)
if __name__ == "__main__":
main()
mongodb-1.6.1/scripts/centos/ldap/mongod.ldif 0000644 0000765 0000024 00000010272 13572250757 020510 0 ustar alcaeus staff #
# See slapd-config(5) for details on configuration options.
# This file should NOT be world readable.
#
dn: cn=config
objectClass: olcGlobal
cn: config
olcArgsFile: /var/run/openldap/slapd.args
olcPidFile: /var/run/openldap/slapd.pid
#
# TLS settings
#
olcTLSCACertificatePath: /etc/openldap/certs
olcTLSCertificateFile: "OpenLDAP Server"
olcTLSCertificateKeyFile: /etc/openldap/certs/password
#
# Do not enable referrals until AFTER you have a working directory
# service AND an understanding of referrals.
#
#olcReferral: ldap://root.openldap.org
#
# Sample security restrictions
# Require integrity protection (prevent hijacking)
# Require 112-bit (3DES or better) encryption for updates
# Require 64-bit encryption for simple bind
#
#olcSecurity: ssf=1 update_ssf=112 simple_bind=64
#
# Load dynamic backend modules:
# - modulepath is architecture dependent value (32/64-bit system)
# - back_sql.la backend requires openldap-servers-sql package
# - dyngroup.la and dynlist.la cannot be used at the same time
#
#dn: cn=module,cn=config
#objectClass: olcModuleList
#cn: module
#olcModulepath: /usr/lib/openldap
#olcModulepath: /usr/lib64/openldap
#olcModuleload: accesslog.la
#olcModuleload: auditlog.la
#olcModuleload: back_dnssrv.la
#olcModuleload: back_ldap.la
#olcModuleload: back_mdb.la
#olcModuleload: back_meta.la
#olcModuleload: back_null.la
#olcModuleload: back_passwd.la
#olcModuleload: back_relay.la
#olcModuleload: back_shell.la
#olcModuleload: back_sock.la
#olcModuleload: collect.la
#olcModuleload: constraint.la
#olcModuleload: dds.la
#olcModuleload: deref.la
#olcModuleload: dyngroup.la
#olcModuleload: dynlist.la
#olcModuleload: memberof.la
#olcModuleload: pcache.la
#olcModuleload: ppolicy.la
#olcModuleload: refint.la
#olcModuleload: retcode.la
#olcModuleload: rwm.la
#olcModuleload: seqmod.la
#olcModuleload: smbk5pwd.la
#olcModuleload: sssvlv.la
#olcModuleload: syncprov.la
#olcModuleload: translucent.la
#olcModuleload: unique.la
#olcModuleload: valsort.la
#
# Schema settings
#
dn: cn=schema,cn=config
objectClass: olcSchemaConfig
cn: schema
include: file:///etc/openldap/schema/core.ldif
include: file:///etc/openldap/schema/corba.schema
include: file:///etc/openldap/schema/cosine.ldif
include: file:///etc/openldap/schema/duaconf.schema
include: file:///etc/openldap/schema/dyngroup.schema
include: file:///etc/openldap/schema/inetorgperson.ldif
include: file:///etc/openldap/schema/java.schema
include: file:///etc/openldap/schema/misc.schema
include: file:///etc/openldap/schema/nis.ldif
include: file:///etc/openldap/schema/openldap.ldif
include: file:///etc/openldap/schema/ppolicy.schema
include: file:///etc/openldap/schema/collective.schema
#
# Frontend settings
#
dn: olcDatabase=frontend,cn=config
objectClass: olcDatabaseConfig
olcDatabase: frontend
#
# Sample global access control policy:
# Root DSE: allow anyone to read it
# Subschema (sub)entry DSE: allow anyone to read it
# Other DSEs:
# Allow self write access
# Allow authenticated users read access
# Allow anonymous users to authenticate
#
#olcAccess: to dn.base="" by * read
#olcAccess: to dn.base="cn=Subschema" by * read
#olcAccess: to *
# by self write
# by users read
# by anonymous auth
#
# if no access controls are present, the default policy
# allows anyone and everyone to read anything but restricts
# updates to rootdn. (e.g., "access to * by * read")
#
# rootdn can always read and write EVERYTHING!
#
#
# Configuration database
#
dn: olcDatabase=config,cn=config
objectClass: olcDatabaseConfig
olcDatabase: config
olcAccess: to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,c
n=auth" manage by * none
#
# Server status monitoring
#
dn: olcDatabase=monitor,cn=config
objectClass: olcDatabaseConfig
olcDatabase: monitor
olcAccess: to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,c
n=auth" read by dn.base="cn=Manager,dc=10gen,dc=me" read by * none
#
# Backend database definitions
#
dn: olcDatabase=hdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcHdbConfig
olcDatabase: hdb
olcSuffix: dc=10gen,dc=me
olcRootDN: cn=Manager,dc=10gen,dc=me
olcRootPW: {SSHA}t3hTZGC4FTOS6AnTa76aX7HRtt1IDqFM
olcDbDirectory: /var/lib/ldap
olcDbIndex: objectClass eq,pres
olcDbIndex: ou,cn,mail,surname,givenname eq,pres,sub
mongodb-1.6.1/scripts/centos/ldap/pw.ldif 0000644 0000765 0000024 00000001173 13572250757 017653 0 ustar alcaeus staff dn: olcDatabase={0}config,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}t3hTZGC4FTOS6AnTa76aX7HRtt1IDqFM
-
replace: olcRootDN
olcRootDN: cn=Manager,dc=10gen,dc=me
dn: olcDatabase={2}bdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}t3hTZGC4FTOS6AnTa76aX7HRtt1IDqFM
-
replace: olcSuffix
olcSuffix: dc=10gen,dc=me
-
replace: olcRootDN
olcRootDN: cn=Manager,dc=10gen,dc=me
dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read by dn.base="cn=Manager,dc=10gen,dc=me" read by * none
mongodb-1.6.1/scripts/centos/ldap/saslauthd.conf 0000644 0000765 0000024 00000000143 13572250757 021220 0 ustar alcaeus staff ldap_servers: ldap://localhost:389
ldap_search_base: ou=Users,dc=10gen,dc=me
ldap_filter: (uid=%u)
mongodb-1.6.1/scripts/centos/ldap/users 0000644 0000765 0000024 00000000026 13572250757 017445 0 ustar alcaeus staff bugs
features
dbadmin
mongodb-1.6.1/scripts/centos/essentials.sh 0000644 0000765 0000024 00000000362 13572250757 020152 0 ustar alcaeus staff # Tools you can't live without
sudo yum install -y git vim
# I can't stand emacs
echo 'set -o vi' | sudo tee /etc/profile.d/vishell.sh
# Who knows how to configure RHEL at all anyway?
sudo service iptables stop
sudo chkconfig iptables off
mongodb-1.6.1/scripts/freebsd/essentials.sh 0000644 0000765 0000024 00000000575 13572250757 020277 0 ustar alcaeus staff # Update ports
sudo portsnap fetch extract update
# Minimum required PHP install + pecl
sudo pkg install -y pcre php56 php56-openssl php56-json php56-zlib pear autoconf pkgconf cyrus-sasl
# We need vim. git requires curl. mongoc requires libtool and automake
sudo pkg install -y vim git curl libtool automake
# I can't stand emacs
echo 'set -o vi' | sudo tee -a /etc/profile
mongodb-1.6.1/scripts/freebsd/phongo.sh 0000644 0000765 0000024 00000000473 13572250757 017414 0 ustar alcaeus staff ls -1 /phongo/mongodb*.tgz | sort -n -r | xargs sudo pecl install -f 2>&1 > /phongo/.build
if test $? -eq 0; then
php -m | grep -q mongodb || echo "extension=mongodb.so" | sudo tee -a /usr/local/etc/php/extensions.ini
pecl run-tests -q -p mongodb 2>&1 > /phongo/.tests
else
tail -n50 /phongo/.build
exit 3
fi
mongodb-1.6.1/scripts/presets/replicaset-30.json 0000644 0000765 0000024 00000004036 13572250757 021106 0 ustar alcaeus staff {
"id": "REPLICASET_30",
"name": "mongod",
"members": [
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3100/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3100/mongod.log",
"journal": true,
"nssize": 1,
"port": 3100,
"bind_ip": "::,0.0.0.0",
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 99,
"tags": {
"ordinal": "one",
"dc": "pa"
}
},
"server_id": "RS-30-one"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3101/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3101/mongod.log",
"journal": true,
"nssize": 1,
"port": 3101,
"bind_ip": "::,0.0.0.0",
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 1.1,
"tags": {
"ordinal": "two",
"dc": "nyc"
}
},
"server_id": "RS-30-two"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3102/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3002/mongod.log",
"journal": true,
"nssize": 1,
"port": 3102,
"bind_ip": "::,0.0.0.0",
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"arbiterOnly": true
},
"server_id": "RS-30-arbiter"
}
],
"version": "30-release"
}
mongodb-1.6.1/scripts/presets/replicaset-dns.json 0000644 0000765 0000024 00000003411 13572250757 021444 0 ustar alcaeus staff {
"id": "REPLICASET_DNS",
"name": "mongod",
"members": [
{
"procParams": {
"dbpath": "/tmp/REPLICASET/27017/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/27017/mongod.log",
"journal": true,
"nssize": 1,
"port": 27017,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 1
},
"server_id": "DNS-one"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/27018/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/27018/mongod.log",
"journal": true,
"nssize": 1,
"port": 27018,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 1
},
"server_id": "DNS-two"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/27019/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/27019/mongod.log",
"journal": true,
"nssize": 1,
"port": 27019,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 1
},
"server_id": "DNS-three"
}
]
}
mongodb-1.6.1/scripts/presets/replicaset.json 0000644 0000765 0000024 00000003751 13572250757 020671 0 ustar alcaeus staff {
"id": "REPLICASET",
"name": "mongod",
"members": [
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3000/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3000/mongod.log",
"journal": true,
"nssize": 1,
"port": 3000,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 99,
"tags": {
"ordinal": "one",
"dc": "pa"
}
},
"server_id": "RS-one"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3001/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3001/mongod.log",
"journal": true,
"nssize": 1,
"port": 3001,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"priority": 1.1,
"tags": {
"ordinal": "two",
"dc": "nyc"
}
},
"server_id": "RS-two"
},
{
"procParams": {
"dbpath": "/tmp/REPLICASET/3002/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/REPLICASET/3002/mongod.log",
"journal": true,
"nssize": 1,
"port": 3002,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"rsParams": {
"arbiterOnly": true
},
"server_id": "RS-arbiter"
}
]
}
mongodb-1.6.1/scripts/presets/standalone-30.json 0000644 0000765 0000024 00000000656 13572250757 021107 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE_30",
"procParams": {
"dbpath": "/tmp/standalone-30/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone-30/mongod.log",
"journal": true,
"nssize": 1,
"port": 2700,
"bind_ip": "::,0.0.0.0",
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"version": "30-release"
}
mongodb-1.6.1/scripts/presets/standalone-auth.json 0000644 0000765 0000024 00000000725 13572250757 021623 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE_AUTH",
"auth_key": "secret",
"login": "root",
"password": "toor",
"procParams": {
"dbpath": "/tmp/standalone-auth/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone-auth/m.log",
"journal": true,
"nssize": 1,
"port": 2200,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
}
}
mongodb-1.6.1/scripts/presets/standalone-plain.json 0000644 0000765 0000024 00000001064 13572250757 021762 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE_PLAIN",
"auth_key": "secret",
"login": "root",
"password": "toor",
"procParams": {
"dbpath": "/tmp/standalone-plain/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone-plain/m.log",
"journal": true,
"nssize": 1,
"port": 2400,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1, "saslauthdPath": "/var/run/saslauthd/mux", "authenticationMechanisms": "SCRAM-SHA-1,PLAIN"}
}
}
mongodb-1.6.1/scripts/presets/standalone-ssl.json 0000644 0000765 0000024 00000001153 13572250757 021457 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE_SSL",
"procParams": {
"dbpath": "/tmp/standalone-ssl/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone-ssl/m.log",
"journal": true,
"nssize": 1,
"port": 2100,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
},
"sslParams": {
"sslMode": "requireSSL",
"sslCAFile": "/phongo/scripts/ssl/ca.pem",
"sslPEMKeyFile": "/phongo/scripts/ssl/server.pem",
"sslAllowConnectionsWithoutCertificates": true
}
}
mongodb-1.6.1/scripts/presets/standalone-x509.json 0000644 0000765 0000024 00000001402 13572250757 021360 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE_X509",
"authSource": "$external",
"login": "C=US,ST=New York,L=New York City,O=MongoDB,OU=KernelUser,CN=client",
"procParams": {
"dbpath": "/tmp/standalone-x509/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone-x509/m.log",
"journal": true,
"nssize": 1,
"port": 2300,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1, "authenticationMechanisms": "MONGODB-X509"}
},
"sslParams": {
"sslMode": "requireSSL",
"sslCAFile": "/phongo/scripts/ssl/ca.pem",
"sslPEMKeyFile": "/phongo/scripts/ssl/server.pem",
"sslWeakCertificateValidation": true
}
}
mongodb-1.6.1/scripts/presets/standalone.json 0000644 0000765 0000024 00000000604 13572250757 020660 0 ustar alcaeus staff {
"name": "mongod",
"id" : "STANDALONE",
"procParams": {
"dbpath": "/tmp/standalone/",
"ipv6": true,
"logappend": true,
"logpath": "/tmp/standalone/mongod.log",
"journal": true,
"nssize": 1,
"port": 2000,
"bind_ip_all": true,
"smallfiles": true,
"setParameter": {"enableTestCommands": 1}
}
}
mongodb-1.6.1/scripts/ssl/ca.pem 0000644 0000765 0000024 00000002370 13572250757 016041 0 ustar alcaeus staff -----BEGIN CERTIFICATE-----
MIIDfzCCAmegAwIBAgIDB1MGMA0GCSqGSIb3DQEBCwUAMHkxGzAZBgNVBAMTEkRy
aXZlcnMgVGVzdGluZyBDQTEQMA4GA1UECxMHRHJpdmVyczEQMA4GA1UEChMHTW9u
Z29EQjEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTERMA8GA1UECBMITmV3IFlvcmsx
CzAJBgNVBAYTAlVTMB4XDTE5MDUyMjIwMjMxMVoXDTM5MDUyMjIwMjMxMVoweTEb
MBkGA1UEAxMSRHJpdmVycyBUZXN0aW5nIENBMRAwDgYDVQQLEwdEcml2ZXJzMRAw
DgYDVQQKEwdNb25nb0RCMRYwFAYDVQQHEw1OZXcgWW9yayBDaXR5MREwDwYDVQQI
EwhOZXcgWW9yazELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQCl7VN+WsQfHlwapcOpTLZVoeMAl1LTbWTFuXSAavIyy0W1Ytky1UP/
bxCSW0mSWwCgqoJ5aXbAvrNRp6ArWu3LsTQIEcD3pEdrFIVQhYzWUs9fXqPyI9k+
QNNQ+MRFKeGteTPYwF2eVEtPzUHU5ws3+OKp1m6MCLkwAG3RBFUAfddUnLvGoZiT
pd8/eNabhgHvdrCw+tYFCWvSjz7SluEVievpQehrSEPKe8DxJq/IM3tSl3tdylzT
zeiKNO7c7LuQrgjAfrZl7n2SriHIlNmqiDR/kdd8+TxBuxjFlcf2WyHCO3lIcIgH
KXTlhUCg50KfHaxHu05Qw0x8869yIzqbAgMBAAGjEDAOMAwGA1UdEwQFMAMBAf8w
DQYJKoZIhvcNAQELBQADggEBAEHuhTL8KQZcKCTSJbYA9MgZj7U32arMGBbc1hiq
VBREwvdVz4+9tIyWMzN9R/YCKmUTnCq8z3wTlC8kBtxYn/l4Tj8nJYcgLJjQ0Fwe
gT564CmvkUat8uXPz6olOCdwkMpJ9Sj62i0mpgXJdBfxKQ6TZ9yGz6m3jannjZpN
LchB7xSAEWtqUgvNusq0dApJsf4n7jZ+oBZVaQw2+tzaMfaLqHgMwcu1FzA8UKCD
sxCgIsZUs8DdxaD418Ot6nPfheOTqe24n+TTa+Z6O0W0QtnofJBx7tmAo1aEc57i
77s89pfwIJetpIlhzNSMKurCAocFCJMJLAASJFuu6dyDvPo=
-----END CERTIFICATE----- mongodb-1.6.1/scripts/ssl/client.pem 0000644 0000765 0000024 00000005614 13572250757 016740 0 ustar alcaeus staff -----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAsNS8UEuin7/K29jXfIOLpIoh1jEyWVqxiie2Onx7uJJKcoKo
khA3XeUnVN0k6X5MwYWcN52xcns7LYtyt06nRpTG2/emoV44w9uKTuHsvUbiOwSV
m/ToKQQ4FUFZoqorXH+ZmJuIpJNfoW+3CkE1vEDCIecIq6BNg5ySsPtvSuSJHGjp
mc7/5ZUDvFE2aJ8QbJU3Ws0HXiEb6ymi048LlzEL2VKX3w6mqqh+7dcZGAy7qYk2
5FZ9ktKvCeQau7mTyU1hsPrKFiKtMN8Q2ZAItX13asw5/IeSTq2LgLFHlbj5Kpq4
GmLdNCshzH5X7Ew3IYM8EHmsX8dmD6mhv7vpVwIDAQABAoIBABOdpb4qhcG+3twA
c/cGCKmaASLnljQ/UU6IFTjrsjXJVKTbRaPeVKX/05sgZQXZ0t3s2mV5AsQ2U1w8
Cd+3w+qaemzQThW8hAOGCROzEDX29QWi/o2sX0ydgTMqaq0Wv3SlWv6I0mGfT45y
/BURIsrdTCvCmz2erLqa1dL4MWJXRFjT9UTs5twlecIOM2IHKoGGagFhymRK4kDe
wTRC9fpfoAgyfus3pCO/wi/F8yKGPDEwY+zgkhrJQ+kSeki7oKdGD1H540vB8gRt
EIqssE0Y6rEYf97WssQlxJgvoJBDSftOijS6mwvoasDUwfFqyyPiirawXWWhHXkc
DjIi/XECgYEA5xfjilw9YyM2UGQNESbNNunPcj7gDZbN347xJwmYmi9AUdPLt9xN
3XaMqqR22k1DUOxC/5hH0uiXir7mDfqmC+XS/ic/VOsa3CDWejkEnyGLiwSHY502
wD/xWgHwUiGVAG9HY64vnDGm6L3KGXA2oqxanL4V0+0+Ht49pZ16i8sCgYEAw+Ox
CHGtpkzjCP/z8xr+1VTSdpc/4CP2HONnYopcn48KfQnf7Nale69/1kZpypJlvQSG
eeA3jMGigNJEkb8/kaVoRLCisXcwLc0XIfCTeiK6FS0Ka30D/84Qm8UsHxRdpGkM
kYITAa2r64tgRL8as4/ukeXBKE+oOhX43LeEfyUCgYBkf7IX2Ndlhsm3GlvIarxy
NipeP9PGdR/hKlPbq0OvQf9R1q7QrcE7H7Q6/b0mYNV2mtjkOQB7S2WkFDMOP0P5
BqDEoKLdNkV/F9TOYH+PCNKbyYNrodJOt0Ap6Y/u1+Xpw3sjcXwJDFrO+sKqX2+T
PStG4S+y84jBedsLbDoAEwKBgQCTz7/KC11o2yOFqv09N+WKvBKDgeWlD/2qFr3w
UU9K5viXGVhqshz0k5z25vL09Drowf1nAZVpFMO2SPOMtq8VC6b+Dfr1xmYIaXVH
Gu1tf77CM9Zk/VSDNc66e7GrUgbHBK2DLo+A+Ld9aRIfTcSsMbNnS+LQtCrQibvb
cG7+MQKBgQCY11oMT2dUekoZEyW4no7W5D74lR8ztMjp/fWWTDo/AZGPBY6cZoZF
IICrzYtDT/5BzB0Jh1f4O9ZQkm5+OvlFbmoZoSbMzHL3oJCBOY5K0/kdGXL46WWh
IRJSYakNU6VIS7SjDpKgm9D8befQqZeoSggSjIIULIiAtYgS80vmGA==
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDgzCCAmugAwIBAgIDAxOUMA0GCSqGSIb3DQEBCwUAMHkxGzAZBgNVBAMTEkRy
aXZlcnMgVGVzdGluZyBDQTEQMA4GA1UECxMHRHJpdmVyczEQMA4GA1UEChMHTW9u
Z29EQjEWMBQGA1UEBxMNTmV3IFlvcmsgQ2l0eTERMA8GA1UECBMITmV3IFlvcmsx
CzAJBgNVBAYTAlVTMB4XDTE5MDUyMjIzNTU1NFoXDTM5MDUyMjIzNTU1NFowaTEP
MA0GA1UEAxMGY2xpZW50MRAwDgYDVQQLEwdEcml2ZXJzMQwwCgYDVQQKEwNNREIx
FjAUBgNVBAcTDU5ldyBZb3JrIENpdHkxETAPBgNVBAgTCE5ldyBZb3JrMQswCQYD
VQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALDUvFBLop+/
ytvY13yDi6SKIdYxMllasYontjp8e7iSSnKCqJIQN13lJ1TdJOl+TMGFnDedsXJ7
Oy2LcrdOp0aUxtv3pqFeOMPbik7h7L1G4jsElZv06CkEOBVBWaKqK1x/mZibiKST
X6FvtwpBNbxAwiHnCKugTYOckrD7b0rkiRxo6ZnO/+WVA7xRNmifEGyVN1rNB14h
G+spotOPC5cxC9lSl98Opqqofu3XGRgMu6mJNuRWfZLSrwnkGru5k8lNYbD6yhYi
rTDfENmQCLV9d2rMOfyHkk6ti4CxR5W4+SqauBpi3TQrIcx+V+xMNyGDPBB5rF/H
Zg+pob+76VcCAwEAAaMkMCIwCwYDVR0PBAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
BwMCMA0GCSqGSIb3DQEBCwUAA4IBAQAqRcLAGvYMaGYOV4HJTzNotT2qE0I9THNQ
wOV1fBg69x6SrUQTQLjJEptpOA288Wue6Jt3H+p5qAGV5GbXjzN/yjCoItggSKxG
Xg7279nz6/C5faoIKRjpS9R+MsJGlttP9nUzdSxrHvvqm62OuSVFjjETxD39DupE
YPFQoHOxdFTtBQlc/zIKxVdd20rs1xJeeU2/L7jtRBSPuR/Sk8zot7G2/dQHX49y
kHrq8qz12kj1T6XDXf8KZawFywXaz0/Ur+fUYKmkVk1T0JZaNtF4sKqDeNE4zcns
p3xLVDSl1Q5Gwj7bgph9o4Hxs9izPwiqjmNaSjPimGYZ399zcurY
-----END CERTIFICATE-----
mongodb-1.6.1/scripts/ssl/crl.pem 0000644 0000765 0000024 00000001317 13572250757 016236 0 ustar alcaeus staff -----BEGIN X509 CRL-----
MIIB6jCB0wIBATANBgkqhkiG9w0BAQsFADB5MRswGQYDVQQDExJEcml2ZXJzIFRl
c3RpbmcgQ0ExEDAOBgNVBAsTB0RyaXZlcnMxEDAOBgNVBAoTB01vbmdvREIxFjAU
BgNVBAcTDU5ldyBZb3JrIENpdHkxETAPBgNVBAgTCE5ldyBZb3JrMQswCQYDVQQG
EwJVUxcNMTkwNTIyMjI0NTUzWhcNMTkwNjIxMjI0NTUzWjAVMBMCAncVFw0xOTA1
MjIyMjQ1MzJaoA8wDTALBgNVHRQEBAICEAAwDQYJKoZIhvcNAQELBQADggEBACwQ
W9OF6ExJSzzYbpCRroznkfdLG7ghNSxIpBQUGtcnYbkP4em6TdtAj5K3yBjcKn4a
hnUoa5EJGr2Xgg0QascV/1GuWEJC9rsYYB9boVi95l1CrkS0pseaunM086iItZ4a
hRVza8qEMBc3rdsracA7hElYMKdFTRLpIGciJehXzv40yT5XFBHGy/HIT0CD50O7
BDOHzA+rCFCvxX8UY9myDfb1r1zUW7Gzjn241VT7bcIJmhFE9oV0popzDyqr6GvP
qB2t5VmFpbnSwkuc4ie8Jizip1P8Hg73lut3oVAHACFGPpfaNIAp4GcSH61zJmff
9UBe3CJ1INwqyiuqGeA=
-----END X509 CRL-----
mongodb-1.6.1/scripts/ssl/server.pem 0000644 0000765 0000024 00000005641 13572250757 016770 0 ustar alcaeus staff -----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAhNrB0E6GY/kFSd8/vNpu/t952tbnOsD5drV0XPvmuy7SgKDY
a/S+xb/jPnlZKKehdBnH7qP/gYbv34ZykzcDFZscjPLiGc2cRGP+NQCSFK0d2/7d
y15zSD3zhj14G8+MkpAejTU+0/qFNZMc5neDvGanTe0+8aWa0DXssM0MuTxIv7j6
CtsMWeqLLofN7a1Kw2UvmieCHfHMuA/08pJwRnV/+5T9WONBPJja2ZQRrG1BjpI4
81zSPUZesIqi8yDlExdvgNaRZIEHi/njREqwVgJOZomUY57zmKypiMzbz48dDTsV
gUStxrEqbaP+BEjQYPX5+QQk4GdMjkLf52LR6QIDAQABAoIBAHSs+hHLJNOf2zkp
S3y8CUblVMsQeTpsR6otaehPgi9Zy50TpX4KD5D0GMrBH8BIl86y5Zd7h+VlcDzK
gs0vPxI2izhuBovKuzaE6rf5rFFkSBjxGDCG3o/PeJOoYFdsS3RcBbjVzju0hFCs
xnDQ/Wz0anJRrTnjyraY5SnQqx/xuhLXkj/lwWoWjP2bUqDprnuLOj16soNu60Um
JziWbmWx9ty0wohkI/8DPBl9FjSniEEUi9pnZXPElFN6kwPkgdfT5rY/TkMH4lsu
ozOUc5xgwlkT6kVjXHcs3fleuT/mOfVXLPgNms85JKLucfd6KiV7jYZkT/bXIjQ+
7CZEn0ECgYEA5QiKZgsfJjWvZpt21V/i7dPje2xdwHtZ8F9NjX7ZUFA7mUPxUlwe
GiXxmy6RGzNdnLOto4SF0/7ebuF3koO77oLup5a2etL+y/AnNAufbu4S5D72sbiz
wdLzr3d5JQ12xeaEH6kQNk2SD5/ShctdS6GmTgQPiJIgH0MIdi9F3v0CgYEAlH84
hMWcC+5b4hHUEexeNkT8kCXwHVcUjGRaYFdSHgovvWllApZDHSWZ+vRcMBdlhNPu
09Btxo99cjOZwGYJyt20QQLGc/ZyiOF4ximQzabTeFgLkTH3Ox6Mh2Rx9yIruYoX
nE3UfMDkYELanEJUv0zenKpZHw7tTt5yXXSlEF0CgYBSsEOvVcKYO/eoluZPYQAA
F2jgzZ4HeUFebDoGpM52lZD+463Dq2hezmYtPaG77U6V3bUJ/TWH9VN/Or290vvN
v83ECcC2FWlSXdD5lFyqYx/E8gqE3YdgqfW62uqM+xBvoKsA9zvYLydVpsEN9v8m
6CSvs/2btA4O21e5u5WBTQKBgGtAb6vFpe0gHRDs24SOeYUs0lWycPhf+qFjobrP
lqnHpa9iPeheat7UV6BfeW3qmBIVl/s4IPE2ld4z0qqZiB0Tf6ssu/TpXNPsNXS6
dLFz+myC+ufFdNEoQUtQitd5wKbjTCZCOGRaVRgJcSdG6Tq55Fa22mOKPm+mTmed
ZdKpAoGAFsTYBAHPxs8nzkCJCl7KLa4/zgbgywO6EcQgA7tfelB8bc8vcAMG5o+8
YqAfwxrzhVSVbJx0fibTARXROmbh2pn010l2wj3+qUajM8NiskCPFbSjGy7HSUze
P8Kt1uMDJdj55gATzn44au31QBioZY2zXleorxF21cr+BZCJgfA=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDlTCCAn2gAwIBAgICdxUwDQYJKoZIhvcNAQELBQAweTEbMBkGA1UEAxMSRHJp
dmVycyBUZXN0aW5nIENBMRAwDgYDVQQLEwdEcml2ZXJzMRAwDgYDVQQKEwdNb25n
b0RCMRYwFAYDVQQHEw1OZXcgWW9yayBDaXR5MREwDwYDVQQIEwhOZXcgWW9yazEL
MAkGA1UEBhMCVVMwHhcNMTkwNTIyMjIzMjU2WhcNMzkwNTIyMjIzMjU2WjBwMRIw
EAYDVQQDEwlsb2NhbGhvc3QxEDAOBgNVBAsTB0RyaXZlcnMxEDAOBgNVBAoTB01v
bmdvREIxFjAUBgNVBAcTDU5ldyBZb3JrIENpdHkxETAPBgNVBAgTCE5ldyBZb3Jr
MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAITa
wdBOhmP5BUnfP7zabv7fedrW5zrA+Xa1dFz75rsu0oCg2Gv0vsW/4z55WSinoXQZ
x+6j/4GG79+GcpM3AxWbHIzy4hnNnERj/jUAkhStHdv+3ctec0g984Y9eBvPjJKQ
Ho01PtP6hTWTHOZ3g7xmp03tPvGlmtA17LDNDLk8SL+4+grbDFnqiy6Hze2tSsNl
L5ongh3xzLgP9PKScEZ1f/uU/VjjQTyY2tmUEaxtQY6SOPNc0j1GXrCKovMg5RMX
b4DWkWSBB4v540RKsFYCTmaJlGOe85isqYjM28+PHQ07FYFErcaxKm2j/gRI0GD1
+fkEJOBnTI5C3+di0ekCAwEAAaMwMC4wLAYDVR0RBCUwI4IJbG9jYWxob3N0hwR/
AAABhxAAAAAAAAAAAAAAAAAAAAABMA0GCSqGSIb3DQEBCwUAA4IBAQBol8+YH7MA
HwnIh7KcJ8h87GkCWsjOJCDJWiYBJArQ0MmgDO0qdx+QEtvLMn3XNtP05ZfK0WyX
or4cWllAkMFYaFbyB2hYazlD1UAAG+22Rku0UP6pJMLbWe6pnqzx+RL68FYdbZhN
fCW2xiiKsdPoo2VEY7eeZKrNr/0RFE5EKXgzmobpTBQT1Dl3Ve4aWLoTy9INlQ/g
z40qS7oq1PjjPLgxINhf4ncJqfmRXugYTOnyFiVXLZTys5Pb9SMKdToGl3NTYWLL
2AZdjr6bKtT+WtXyHqO0cQ8CkAW0M6VOlMluACllcJxfrtdlQS2S4lUIj76QKBdZ
khBHXq/b8MFX
-----END CERTIFICATE-----
mongodb-1.6.1/scripts/ubuntu/ldap/install.sh 0000644 0000765 0000024 00000001006 13572250757 020411 0 ustar alcaeus staff sudo apt-get -y install ldap-utils libsasl2-modules-ldap sasl2-bin
# setup saslauthd
sudo sed -i 's/MECHANISMS="pam"/MECHANISMS="ldap"/' /etc/default/saslauthd
sudo sed -i 's/START=no/START="yes"/' /etc/default/saslauthd
sudo cp /phongo/scripts/ubuntu/ldap/saslauthd.conf /etc/
sudo service saslauthd restart
testsaslauthd -u bugs -p password -s mongod -f /var/run/saslauthd/mux
#ldapsearch -x -LLL -b dc=10gen,dc=me -h 192.168.112.20
#ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts -h 192.168.112.20
mongodb-1.6.1/scripts/ubuntu/ldap/saslauthd.conf 0000644 0000765 0000024 00000000150 13572250757 021245 0 ustar alcaeus staff ldap_servers: ldap://192.168.112.20:389
ldap_search_base: ou=Users,dc=10gen,dc=me
ldap_filter: (uid=%u)
mongodb-1.6.1/scripts/ubuntu/essentials.sh 0000644 0000765 0000024 00000000365 13572250757 020204 0 ustar alcaeus staff if [ ! -e ".provisioned" ]; then
# Tools you can't live without
apt-get update
apt-get install -y build-essential git vim libtool autoconf
# I can't stand emacs
echo 'set -o vi' | sudo tee /etc/profile.d/vishell.sh
touch .provisioned
fi
mongodb-1.6.1/scripts/ubuntu/mongo-orchestration.sh 0000644 0000765 0000024 00000002720 13572250757 022030 0 ustar alcaeus staff # 3.0
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
# 3.6
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
# 4.0
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 68818C72E52529D4
echo 'deb http://repo.mongodb.com/apt/ubuntu trusty/mongodb-enterprise/3.0 multiverse' | tee /etc/apt/sources.list.d/mongodb-enterprise-3.0.list
echo 'deb http://repo.mongodb.com/apt/ubuntu trusty/mongodb-enterprise/3.6 multiverse' | tee /etc/apt/sources.list.d/mongodb-enterprise-3.6.list
echo 'deb http://repo.mongodb.com/apt/ubuntu trusty/mongodb-enterprise/testing multiverse' | tee /etc/apt/sources.list.d/mongodb-enterprise-4.0.list
apt-get update
apt-get install -y libsnmp30 libgsasl7 libcurl4-openssl-dev
apt-get download mongodb-enterprise-server=3.0.15
apt-get download mongodb-enterprise-server=3.6.1
apt-get download mongodb-enterprise-mongos=3.6.1
apt-get download mongodb-enterprise-server=4.0.0~rc5
dpkg -x mongodb-enterprise-server_3.0.15_amd64.deb 3.0
dpkg -x mongodb-enterprise-server_3.6.1_amd64.deb 3.6
dpkg -x mongodb-enterprise-mongos_3.6.1_amd64.deb 3.6
dpkg -x mongodb-enterprise-server_4.0.0~rc5_amd64.deb 4.0
# Python stuff for mongo-orchestration
apt-get install -y python python-dev
python get-pip.py
pip install --upgrade mongo-orchestration
# Launch mongo-orchestration
mongo-orchestration -f mongo-orchestration-config.json -b 192.168.112.10 --enable-majority-read-concern start
mongodb-1.6.1/scripts/ubuntu/phongo.sh 0000644 0000765 0000024 00000000566 13572250757 017327 0 ustar alcaeus staff apt-get install -y php-pear php5-dbg gdb
apt-get install -y libssl-dev libsasl2-dev libpcre3-dev pkg-config
ls -1 /phongo/mongodb*.tgz | sort -n -r | xargs sudo pecl install -f 2>&1 > /phongo/.build
php -m | grep -q mongodb || echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
pecl run-tests -q -p mongodb 2>&1 > /phongo/.tests
mongodb-1.6.1/scripts/vmware/kernel.sh 0000644 0000765 0000024 00000000466 13572250757 017273 0 ustar alcaeus staff # Ensure that VMWare Tools recompiles kernel modules
# when we update the linux images
sed -i.bak 's/answer AUTO_KMODS_ENABLED_ANSWER no/answer AUTO_KMODS_ENABLED_ANSWER yes/g' /etc/vmware-tools/locations
sed -i.bak 's/answer AUTO_KMODS_ENABLED no/answer AUTO_KMODS_ENABLED yes/g' /etc/vmware-tools/locations
mongodb-1.6.1/scripts/clang-format.sh 0000755 0000765 0000024 00000002053 13572250757 017061 0 ustar alcaeus staff #!/bin/sh
if test x"$1" = x; then
FILES1=`git ls-files | grep -v "src/contrib" | grep '\.[ch]$'`
FILES2=`git ls-files --others --exclude-standard | grep -v "src/contrib" | grep '\.[ch]$'`
FILES="$FILES1 $FILES2"
fi
if test x"$1" = xchanged; then
FILES1=`git diff --name-only | grep -v "src/contrib" | grep '\.[ch]$'`
FILES2=`git diff --cached --name-only | grep -v "src/contrib" | grep '\.[ch]$'`
FILES3=`git ls-files --others --exclude-standard | grep '\.[ch]$'`
FILES="$FILES1 $FILES2 $FILES3"
fi
# Find clang-format, we prefer -6.0, but also allow binaries without -suffix as
# long as they're >= 6.0.0
CLANG_FORMAT=`which clang-format-6.0`
if [ -z "$CLANG_FORMAT" ]; then
CLANG_FORMAT=`which clang-format`
fi
if [ -z "$CLANG_FORMAT" ]; then
echo "Couldn't find clang-format"
exit
fi
VERSION=`$CLANG_FORMAT -version | cut -d " " -f 3`
VERSION_MAJOR=`echo $VERSION | cut -d "." -f 1`
if [ $VERSION_MAJOR -lt 6 ]; then
echo "Found clang-format $VERSION but we need >= 6.0.0"
exit
fi
# Run formatter
for i in $FILES; do
$CLANG_FORMAT -i $i
done
mongodb-1.6.1/scripts/convert-bson-corpus-tests.php 0000644 0000765 0000024 00000027756 13572250757 021772 0 ustar alcaeus staff 'Variation in double\'s string representation (SPEC-850)',
'Double type: -1.23456789012345677E+18' => 'Variation in double\'s string representation (SPEC-850)',
'Int64 type: -1' => 'PHP encodes integers as 32-bit if range allows',
'Int64 type: 0' => 'PHP encodes integers as 32-bit if range allows',
'Int64 type: 1' => 'PHP encodes integers as 32-bit if range allows',
'Javascript Code with Scope: bad scope doc (field has bad string length)' => 'Depends on PHPC-889',
'Javascript Code with Scope: Unicode and embedded null in code string, empty scope' => 'Embedded null in code string is not supported in libbson (CDRIVER-1879)',
'Multiple types within the same document: All BSON types' => 'PHP encodes integers as 32-bit if range allows',
'Top-level document validity: Bad $date (number, not string or hash)' => 'Legacy extended JSON $date syntax uses numbers (CDRIVER-2223)',
];
$for64bitOnly = [
/* Note: Although 64-bit integers be represented by the Int64 class, these
* tests fail on 32-bit platforms due to json_canonicalize() roundtripping
* values through PHP, which converts large integers to floats. */
'Int64 type: MinValue' => "Can't represent 64-bit ints on a 32-bit platform",
'Int64 type: MaxValue' => "Can't represent 64-bit ints on a 32-bit platform",
];
$outputPath = realpath(__DIR__ . '/../tests') . '/bson-corpus/';
if ( ! is_dir($outputPath) && ! mkdir($outputPath, 0755, true)) {
printf("Error creating output path: %s\n", $outputPath);
}
foreach (array_slice($argv, 1) as $inputFile) {
if ( ! is_readable($inputFile) || ! is_file($inputFile)) {
printf("Error reading %s\n", $inputFile);
continue;
}
$test = json_decode(file_get_contents($inputFile), true);
if (json_last_error() !== JSON_ERROR_NONE) {
printf("Error decoding %s: %s\n", $inputFile, json_last_error_msg());
continue;
}
if ( ! isset($test['description'])) {
printf("Skipping test file without \"description\" field: %s\n", $inputFile);
continue;
}
if ( ! empty($test['valid'])) {
foreach ($test['valid'] as $i => $case) {
$outputFile = sprintf('%s-valid-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForValid($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing valid[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing valid[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
if ( ! empty($test['decodeErrors'])) {
foreach ($test['decodeErrors'] as $i => $case) {
$outputFile = sprintf('%s-decodeError-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForDecodeError($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing decodeErrors[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing decodeErrors[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
if ( ! empty($test['parseErrors'])) {
foreach ($test['parseErrors'] as $i => $case) {
$outputFile = sprintf('%s-parseError-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForParseError($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing parseErrors[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing parseErrors[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
}
function getParamsForValid(array $test, array $case)
{
foreach (['description', 'canonical_bson', 'canonical_extjson'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = '';
$expect = '';
$lossy = isset($case['lossy']) ? (boolean) $case['lossy'] : false;
$canonicalBson = $case['canonical_bson'];
$expectedCanonicalBson = strtolower($canonicalBson);
$code .= sprintf('$canonicalBson = hex2bin(%s);', var_export($canonicalBson, true)) . "\n";
if (isset($case['degenerate_bson'])) {
$degenerateBson = $case['degenerate_bson'];
$expectedDegenerateBson = strtolower($degenerateBson);
$code .= sprintf('$degenerateBson = hex2bin(%s);', var_export($degenerateBson, true)) . "\n";
}
if (isset($case['converted_bson'])) {
$convertedBson = $case['converted_bson'];
$expectedConvertedBson = strtolower($convertedBson);
$code .= sprintf('$convertedBson = hex2bin(%s);', var_export($convertedBson, true)) . "\n";
}
$canonicalExtJson = $case['canonical_extjson'];
$expectedCanonicalExtJson = json_canonicalize($canonicalExtJson);
$code .= sprintf('$canonicalExtJson = %s;', var_export($canonicalExtJson, true)) . "\n";
if (isset($case['relaxed_extjson'])) {
$relaxedExtJson = $case['relaxed_extjson'];
$expectedRelaxedExtJson = json_canonicalize($relaxedExtJson);
$code .= sprintf('$relaxedExtJson = %s;', var_export($relaxedExtJson, true)) . "\n";
}
if (isset($case['degenerate_extjson'])) {
$degenerateExtJson = $case['degenerate_extjson'];
$expectedDegenerateExtJson = json_canonicalize($degenerateExtJson);
$code .= sprintf('$degenerateExtJson = %s;', var_export($degenerateExtJson, true)) . "\n";
}
if (isset($case['converted_extjson'])) {
$convertedExtJson = $case['converted_extjson'];
$expectedConvertedExtJson = json_canonicalize($convertedExtJson);
$code .= sprintf('$convertedExtJson = %s;', var_export($convertedExtJson, true)) . "\n";
}
$code .= "\n// Canonical BSON -> Native -> Canonical BSON \n";
$code .= 'echo bin2hex(fromPHP(toPHP($canonicalBson))), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
$code .= "\n// Canonical BSON -> Canonical extJSON \n";
$code .= 'echo json_canonicalize(toCanonicalExtendedJSON($canonicalBson)), "\n";' . "\n";;
$expect .= $expectedCanonicalExtJson . "\n";
if (isset($relaxedExtJson)) {
$code .= "\n// Canonical BSON -> Relaxed extJSON \n";
$code .= 'echo json_canonicalize(toRelaxedExtendedJSON($canonicalBson)), "\n";' . "\n";;
$expect .= $expectedRelaxedExtJson . "\n";
}
if (!$lossy) {
$code .= "\n// Canonical extJSON -> Canonical BSON \n";
$code .= 'echo bin2hex(fromJSON($canonicalExtJson)), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
}
if (isset($degenerateBson)) {
$code .= "\n// Degenerate BSON -> Native -> Canonical BSON \n";
$code .= 'echo bin2hex(fromPHP(toPHP($degenerateBson))), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
$code .= "\n// Degenerate BSON -> Canonical extJSON \n";
$code .= 'echo json_canonicalize(toCanonicalExtendedJSON($degenerateBson)), "\n";' . "\n";;
$expect .= $expectedCanonicalExtJson . "\n";
if (isset($relaxedExtJson)) {
$code .= "\n// Degenerate BSON -> Relaxed extJSON \n";
$code .= 'echo json_canonicalize(toRelaxedExtendedJSON($degenerateBson)), "\n";' . "\n";;
$expect .= $expectedRelaxedExtJson . "\n";
}
}
if (isset($degenerateExtJson) && !$lossy) {
$code .= "\n// Degenerate extJSON -> Canonical BSON \n";
$code .= 'echo bin2hex(fromJSON($degenerateExtJson)), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
}
if (isset($relaxedExtJson)) {
$code .= "\n// Relaxed extJSON -> BSON -> Relaxed extJSON \n";
$code .= 'echo json_canonicalize(toRelaxedExtendedJSON(fromJSON($relaxedExtJson))), "\n";' . "\n";
$expect .= $expectedRelaxedExtJson . "\n";
}
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function getParamsForDecodeError(array $test, array $case)
{
foreach (['description', 'bson'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = sprintf('$bson = hex2bin(%s);', var_export($case['bson'], true)) . "\n\n";
$code .= "throws(function() use (\$bson) {\n";
$code .= " var_dump(toPHP(\$bson));\n";
$code .= "}, 'MongoDB\Driver\Exception\UnexpectedValueException');";
/* We do not test for the exception message, since that may differ based on
* the nature of the decoding error. */
$expect = "OK: Got MongoDB\Driver\Exception\UnexpectedValueException";
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function getParamsForParseError(array $test, array $case)
{
foreach (['description', 'string'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = '';
$expect = '';
switch ($test['bson_type']) {
case '0x00': // Top-level document
$code = "throws(function() {\n";
$code .= sprintf(" fromJSON(%s);\n", var_export($case['string'], true));
$code .= "}, 'MongoDB\Driver\Exception\UnexpectedValueException');";
/* We do not test for the exception message, since that may differ
* based on the nature of the parse error. */
$expect = "OK: Got MongoDB\Driver\Exception\UnexpectedValueException";
break;
case '0x13': // Decimal128
$code = "throws(function() {\n";
$code .= sprintf(" new MongoDB\BSON\Decimal128(%s);\n", var_export($case['string'], true));
$code .= "}, 'MongoDB\Driver\Exception\InvalidArgumentException');";
/* We do not test for the exception message, since that may differ
* based on the nature of the parse error. */
$expect = "OK: Got MongoDB\Driver\Exception\InvalidArgumentException";
break;
default:
throw new UnexpectedValueException(sprintf("Parse errors not supported for BSON type: %s", $test['bson_type']));
}
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function renderPhpt(array $params, array $expectedFailures, array $for64bitOnly)
{
$params['%XFAIL%'] = isset($expectedFailures[$params['%NAME%']])
? "--XFAIL--\n" . $expectedFailures[$params['%NAME%']] . "\n"
: '';
$params['%SKIPIF%'] = isset($for64bitOnly[$params['%NAME%']])
? "--SKIPIF--\n" . "" . "\n"
: '';
$template = <<< 'TEMPLATE'
--TEST--
%NAME%
%XFAIL%%SKIPIF%--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php
DO NOT EDIT THIS FILE
--FILE--
===DONE===
--EXPECT--
%EXPECT%
===DONE===
TEMPLATE;
return str_replace(array_keys($params), array_values($params), $template);
}
mongodb-1.6.1/scripts/list-servers.php 0000644 0000765 0000024 00000000340 13572250757 017320 0 ustar alcaeus staff $uri) {
printf("%-20s \t %s\n", $serverid, $uri);
}
mongodb-1.6.1/scripts/run-tests-on.sh 0000644 0000765 0000024 00000000461 13572250757 017063 0 ustar alcaeus staff #!/bin/sh
VMNAME=$1
vagrant status $VMNAME | grep -q "$VMNAME.*running"
if test $? -eq 0; then
vagrant provision $VMNAME > .$VMNAME
else
vagrant up $VMNAME > .$VMNAME
fi
cat .tests | grep -q -E "FAIL|WARN"
if test $? -eq 0; then
echo "$VMNAME FAILED"
cat .tests
exit 2
else
echo "$VMNAME OK"
fi
mongodb-1.6.1/scripts/start-servers.php 0000644 0000765 0000024 00000020474 13572250757 017514 0 ustar alcaeus staff [
"scripts/presets/standalone.json",
"scripts/presets/standalone-30.json",
"scripts/presets/standalone-ssl.json",
"scripts/presets/standalone-auth.json",
"scripts/presets/standalone-x509.json",
"scripts/presets/standalone-plain.json",
],
"replicasets" => [
"scripts/presets/replicaset.json",
"scripts/presets/replicaset-30.json",
"scripts/presets/replicaset-dns.json",
],
];
function make_ctx($preset, $method = "POST") {
$opts = [
"http" => [
"timeout" => 60,
"method" => $method,
"header" => "Accept: application/json\r\n" .
"Content-type: application/x-www-form-urlencoded",
"content" => json_encode(array("preset" => $preset)),
"ignore_errors" => true,
],
];
$ctx = stream_context_create($opts);
return $ctx;
}
function failed()
{
printf("\nLast operation took: %.2f secs\n", lap());
exit(1);
}
function mo_http_request($uri, $context) {
global $http_response_header;
$result = file_get_contents($uri, false, $context);
if ($result === false) {
printf("HTTP request to %s failed:\n", $uri);
var_dump($http_response_header);
failed();
}
return $result;
}
function json_decode_or_fail(...$args)
{
$decoded = json_decode(...$args);
if ($decoded === NULL && json_last_error() !== JSON_ERROR_NONE) {
printf("\njson_decode() failed: %s\n", json_last_error_msg());
var_dump(func_get_arg(0));
failed();
}
return $decoded;
}
printf("Cleaning out previous processes, if any ");
lap();
/* Remove all pre-existing ReplicaSets */
$replicasets = mo_http_request(getMOUri() . "/replica_sets", make_ctx(getMOPresetBase(), "GET"));
$replicasets = json_decode_or_fail($replicasets, true);
foreach($replicasets["replica_sets"] as $replicaset) {
$uri = getMOUri() . "/replica_sets/" . $replicaset["id"];
mo_http_request($uri, make_ctx(getMOPresetBase(), "DELETE"));
echo ".";
}
echo " ";
/* Remove all pre-existing servers */
$servers = mo_http_request(getMOUri() . "/servers", make_ctx(getMOPresetBase(), "GET"));
$servers = json_decode_or_fail($servers, true);
foreach($servers["servers"] as $server) {
$uri = getMOUri() . "/servers/" . $server["id"];
mo_http_request($uri, make_ctx(getMOPresetBase(), "DELETE"));
echo ".";
}
printf("\t(took: %.2f secs)\n", lap());
foreach($PRESETS["standalone"] as $preset) {
lap();
$json = json_decode_or_fail(file_get_contents($preset), true);
printf("Starting %-20s ... ", $json["id"]);
$result = mo_http_request(getMOUri() . "/servers", make_ctx(getMOPresetBase() . $preset));
$decode = json_decode_or_fail($result, true);
if (!isset($decode["id"])) {
printf("\"id\" field not found in server response:\n%s\n", $decode);
failed();
}
$SERVERS[$decode["id"]] = isset($decode["mongodb_auth_uri"]) ? $decode["mongodb_auth_uri"] : $decode["mongodb_uri"];
printf("'%s'\t(took: %.2f secs)\n", $SERVERS[$decode["id"]], lap());
}
echo "---\n";
foreach($PRESETS["replicasets"] as $preset) {
lap();
$json = json_decode_or_fail(file_get_contents($preset), true);
printf("Starting %-20s ... ", $json["id"]);
$result = mo_http_request(getMOUri() . "/replica_sets", make_ctx(getMOPresetBase() . $preset));
$decode = json_decode_or_fail($result, true);
if (!isset($decode["id"])) {
printf("\"id\" field not found in replica set response:\n%s\n", $decode);
failed();
}
$SERVERS[$decode["id"]] = isset($decode["mongodb_auth_uri"]) ? $decode["mongodb_auth_uri"] : $decode["mongodb_uri"];
printf("'%s'\t(took: %.2f secs)\n", $SERVERS[$decode["id"]], lap());
}
file_put_contents($FILENAME, json_encode($SERVERS, JSON_PRETTY_PRINT));
/*
wget --body-data='' --method='GET' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE-AUTH
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE-26
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/RS-two
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/RS-arbiter
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE-PLAIN
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE-X509
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/RS-one
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers/STANDALONE-SSL
wget --body-data='' --method='GET' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/replica_sets
wget --body-data='' --method='DELETE' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/replica_sets/REPLICASET
wget --body-data='' --method='GET' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/
wget --body-data='' --method='GET' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='' --method='GET' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/replica_sets
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone-26.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone-ssl.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone-auth.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone-x509.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/standalone-plain.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/servers
wget --body-data='{"preset":"\/phongo\/\/scripts\/presets\/replicaset.json"}' --method='POST' --header='Accept: application/json' --header='Content-type: application/x-www-form-urlencoded' http://192.168.112.10:8889/replica_sets
*/
mongodb-1.6.1/src/BSON/Binary.c 0000644 0000765 0000024 00000036244 13572250757 015412 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#define PHONGO_BINARY_UUID_SIZE 16
zend_class_entry* php_phongo_binary_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_binary_init(php_phongo_binary_t* intern, const char* data, phongo_zpp_char_len data_len, phongo_long type TSRMLS_DC) /* {{{ */
{
if (type < 0 || type > UINT8_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected type to be an unsigned 8-bit integer, %" PHONGO_LONG_FORMAT " given", type);
return false;
}
if ((type == BSON_SUBTYPE_UUID_DEPRECATED || type == BSON_SUBTYPE_UUID) && data_len != PHONGO_BINARY_UUID_SIZE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected UUID length to be %d bytes, %d given", PHONGO_BINARY_UUID_SIZE, data_len);
return false;
}
intern->data = estrndup(data, data_len);
intern->data_len = data_len;
intern->type = (uint8_t) type;
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_binary_init_from_hash(php_phongo_binary_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *data, *type;
if ((data = zend_hash_str_find(props, "data", sizeof("data") - 1)) && Z_TYPE_P(data) == IS_STRING &&
(type = zend_hash_str_find(props, "type", sizeof("type") - 1)) && Z_TYPE_P(type) == IS_LONG) {
return php_phongo_binary_init(intern, Z_STRVAL_P(data), Z_STRLEN_P(data), Z_LVAL_P(type) TSRMLS_CC);
}
#else
zval **data, **type;
if (zend_hash_find(props, "data", sizeof("data"), (void**) &data) == SUCCESS && Z_TYPE_PP(data) == IS_STRING &&
zend_hash_find(props, "type", sizeof("type"), (void**) &type) == SUCCESS && Z_TYPE_PP(type) == IS_LONG) {
return php_phongo_binary_init(intern, Z_STRVAL_PP(data), Z_STRLEN_PP(data), Z_LVAL_PP(type) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"data\" string and \"type\" integer fields", ZSTR_VAL(php_phongo_binary_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\Binary::__construct(string $data, int $type)
Construct a new BSON binary type */
static PHP_METHOD(Binary, __construct)
{
php_phongo_binary_t* intern;
zend_error_handling error_handling;
char* data;
phongo_zpp_char_len data_len;
phongo_long type;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_BINARY_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &data, &data_len, &type) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_binary_init(intern, data, data_len, type TSRMLS_CC);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Binary::__set_state(array $properties)
*/
static PHP_METHOD(Binary, __set_state)
{
php_phongo_binary_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_binary_ce);
intern = Z_BINARY_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_binary_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Binary::__toString()
Return the Binary's data string. */
static PHP_METHOD(Binary, __toString)
{
php_phongo_binary_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_BINARY_OBJ_P(getThis());
PHONGO_RETURN_STRINGL(intern->data, intern->data_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Binary::getData()
*/
static PHP_METHOD(Binary, getData)
{
php_phongo_binary_t* intern;
intern = Z_BINARY_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRINGL(intern->data, intern->data_len);
} /* }}} */
/* {{{ proto integer MongoDB\BSON\Binary::getType()
*/
static PHP_METHOD(Binary, getType)
{
php_phongo_binary_t* intern;
intern = Z_BINARY_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->type);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Binary::jsonSerialize()
*/
static PHP_METHOD(Binary, jsonSerialize)
{
php_phongo_binary_t* intern;
char type[3];
int type_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_BINARY_OBJ_P(getThis());
array_init_size(return_value, 2);
#if PHP_VERSION_ID >= 70000
{
zend_string* data = php_base64_encode((unsigned char*) intern->data, intern->data_len);
ADD_ASSOC_STRINGL(return_value, "$binary", ZSTR_VAL(data), ZSTR_LEN(data));
zend_string_free(data);
}
#else
{
int data_len = 0;
unsigned char* data = php_base64_encode((unsigned char*) intern->data, intern->data_len, &data_len);
ADD_ASSOC_STRINGL(return_value, "$binary", (char*) data, data_len);
efree(data);
}
#endif
type_len = snprintf(type, sizeof(type), "%02x", intern->type);
ADD_ASSOC_STRINGL(return_value, "$type", type, type_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Binary::serialize()
*/
static PHP_METHOD(Binary, serialize)
{
php_phongo_binary_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_BINARY_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "data", intern->data, intern->data_len);
ADD_ASSOC_LONG_EX(&retval, "type", intern->type);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "data", intern->data, intern->data_len);
ADD_ASSOC_LONG_EX(retval, "type", intern->type);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Binary::unserialize(string $serialized)
*/
static PHP_METHOD(Binary, unserialize)
{
php_phongo_binary_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_BINARY_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_binary_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_binary_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_binary_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Binary function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Binary___construct, 0, 0, 2)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Binary___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Binary_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Binary_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_binary_me[] = {
/* clang-format off */
PHP_ME(Binary, __construct, ai_Binary___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, __set_state, ai_Binary___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(Binary, __toString, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, jsonSerialize, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, serialize, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, unserialize, ai_Binary_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, getData, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Binary, getType, ai_Binary_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Binary object handlers */
static zend_object_handlers php_phongo_handler_binary;
static void php_phongo_binary_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_binary_t* intern = Z_OBJ_BINARY(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->data) {
efree(intern->data);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_binary_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_binary_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_binary_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_binary;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_binary_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_binary;
return retval;
}
#endif
} /* }}} */
static int php_phongo_binary_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_binary_t *intern1, *intern2;
intern1 = Z_BINARY_OBJ_P(o1);
intern2 = Z_BINARY_OBJ_P(o2);
/* MongoDB compares binary types first by the data length, then by the type
* byte, and finally by the binary data itself. */
if (intern1->data_len != intern2->data_len) {
return intern1->data_len < intern2->data_len ? -1 : 1;
}
if (intern1->type != intern2->type) {
return intern1->type < intern2->type ? -1 : 1;
}
return zend_binary_strcmp(intern1->data, intern1->data_len, intern2->data, intern2->data_len);
} /* }}} */
static HashTable* php_phongo_binary_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_BINARY_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_binary_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_binary_t* intern;
HashTable* props;
intern = Z_BINARY_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->data) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval data, type;
ZVAL_STRINGL(&data, intern->data, intern->data_len);
zend_hash_str_update(props, "data", sizeof("data") - 1, &data);
ZVAL_LONG(&type, intern->type);
zend_hash_str_update(props, "type", sizeof("type") - 1, &type);
}
#else
{
zval *data, *type;
MAKE_STD_ZVAL(data);
ZVAL_STRINGL(data, intern->data, intern->data_len, 1);
zend_hash_update(props, "data", sizeof("data"), &data, sizeof(data), NULL);
MAKE_STD_ZVAL(type);
ZVAL_LONG(type, intern->type);
zend_hash_update(props, "type", sizeof("type"), &type, sizeof(type), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_binary_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_binary_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_binary_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_binary_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_binary_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Binary", php_phongo_binary_me);
php_phongo_binary_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_binary_ce->create_object = php_phongo_binary_create_object;
PHONGO_CE_FINAL(php_phongo_binary_ce);
zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_binary_interface_ce);
zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_binary_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_binary, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_binary.compare_objects = php_phongo_binary_compare_objects;
php_phongo_handler_binary.get_debug_info = php_phongo_binary_get_debug_info;
php_phongo_handler_binary.get_gc = php_phongo_binary_get_gc;
php_phongo_handler_binary.get_properties = php_phongo_binary_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_binary.free_obj = php_phongo_binary_free_object;
php_phongo_handler_binary.offset = XtOffsetOf(php_phongo_binary_t, std);
#endif
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_GENERIC"), BSON_SUBTYPE_BINARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_FUNCTION"), BSON_SUBTYPE_FUNCTION TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_OLD_BINARY"), BSON_SUBTYPE_BINARY_DEPRECATED TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_OLD_UUID"), BSON_SUBTYPE_UUID_DEPRECATED TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_UUID"), BSON_SUBTYPE_UUID TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_MD5"), BSON_SUBTYPE_MD5 TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_binary_ce, ZEND_STRL("TYPE_USER_DEFINED"), BSON_SUBTYPE_USER TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/BinaryInterface.c 0000644 0000765 0000024 00000003201 13572250757 017216 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_binary_interface_ce;
/* {{{ MongoDB\BSON\BinaryInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_BinaryInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_binary_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(BinaryInterface, getData, ai_BinaryInterface_void)
ZEND_ABSTRACT_ME(BinaryInterface, getType, ai_BinaryInterface_void)
ZEND_ABSTRACT_ME(BinaryInterface, __toString, ai_BinaryInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_binary_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "BinaryInterface", php_phongo_binary_interface_me);
php_phongo_binary_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/DBPointer.c 0000644 0000765 0000024 00000030030 13572250757 015777 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_dbpointer_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_dbpointer_init(php_phongo_dbpointer_t* intern, const char* ref, phongo_zpp_char_len ref_len, const char* id, phongo_zpp_char_len id_len TSRMLS_DC) /* {{{ */
{
if (strlen(ref) != (size_t) ref_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Ref cannot contain null bytes");
return false;
}
if (!bson_oid_is_valid(id, id_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing ObjectId string: %s", id);
return false;
}
intern->ref = estrndup(ref, ref_len);
intern->ref_len = ref_len;
strncpy(intern->id, id, sizeof(intern->id));
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_dbpointer_init_from_hash(php_phongo_dbpointer_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *ref, *id;
if ((ref = zend_hash_str_find(props, "ref", sizeof("ref") - 1)) && Z_TYPE_P(ref) == IS_STRING &&
(id = zend_hash_str_find(props, "id", sizeof("id") - 1)) && Z_TYPE_P(id) == IS_STRING) {
return php_phongo_dbpointer_init(intern, Z_STRVAL_P(ref), Z_STRLEN_P(ref), Z_STRVAL_P(id), Z_STRLEN_P(id) TSRMLS_CC);
}
#else
zval **ref, **id;
if (zend_hash_find(props, "ref", sizeof("ref"), (void**) &ref) == SUCCESS && Z_TYPE_PP(ref) == IS_STRING &&
zend_hash_find(props, "id", sizeof("id"), (void**) &id) == SUCCESS && Z_TYPE_PP(id) == IS_STRING) {
return php_phongo_dbpointer_init(intern, Z_STRVAL_PP(ref), Z_STRLEN_PP(ref), Z_STRVAL_PP(id), Z_STRLEN_PP(id) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"ref\" and \"id\" string fields", ZSTR_VAL(php_phongo_dbpointer_ce->name));
return false;
} /* }}} */
/* {{{ proto string MongoDB\BSON\DBPointer::__toString()
Return the DBPointer's namespace string and ObjectId. */
static PHP_METHOD(DBPointer, __toString)
{
php_phongo_dbpointer_t* intern;
char* retval;
int retval_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_DBPOINTER_OBJ_P(getThis());
retval_len = spprintf(&retval, 0, "[%s/%s]", intern->ref, intern->id);
PHONGO_RETVAL_STRINGL(retval, retval_len);
efree(retval);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Symbol::jsonSerialize()
*/
static PHP_METHOD(DBPointer, jsonSerialize)
{
php_phongo_dbpointer_t* intern;
ZVAL_RETVAL_TYPE zdb_pointer;
ZVAL_RETVAL_TYPE zoid;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_DBPOINTER_OBJ_P(getThis());
#if PHP_VERSION_ID >= 70000
array_init_size(&zdb_pointer, 2);
array_init_size(&zoid, 1);
ADD_ASSOC_STRINGL(&zdb_pointer, "$ref", intern->ref, intern->ref_len);
ADD_ASSOC_STRING(&zoid, "$oid", intern->id);
ADD_ASSOC_ZVAL(&zdb_pointer, "$id", &zoid);
array_init_size(return_value, 1);
ADD_ASSOC_ZVAL(return_value, "$dbPointer", &zdb_pointer);
#else
ALLOC_INIT_ZVAL(zdb_pointer);
ALLOC_INIT_ZVAL(zoid);
array_init_size(zdb_pointer, 2);
array_init_size(zoid, 1);
ADD_ASSOC_STRINGL(zdb_pointer, "$ref", intern->ref, intern->ref_len);
ADD_ASSOC_STRING(zoid, "$oid", intern->id);
ADD_ASSOC_ZVAL(zdb_pointer, "$id", zoid);
array_init_size(return_value, 1);
ADD_ASSOC_ZVAL(return_value, "$dbPointer", zdb_pointer);
#endif
} /* }}} */
/* {{{ proto string MongoDB\BSON\DBPointer::serialize()
*/
static PHP_METHOD(DBPointer, serialize)
{
php_phongo_dbpointer_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_DBPOINTER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "ref", intern->ref, intern->ref_len);
ADD_ASSOC_STRING(&retval, "id", intern->id);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "ref", intern->ref, intern->ref_len);
ADD_ASSOC_STRING(retval, "id", intern->id);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\DBPointer::unserialize(string $serialized)
*/
static PHP_METHOD(DBPointer, unserialize)
{
php_phongo_dbpointer_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_DBPOINTER_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_dbpointer_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_dbpointer_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_dbpointer_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\DBPointer function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_DBPointer_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_DBPointer_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_dbpointer_me[] = {
/* clang-format off */
/* __set_state intentionally missing */
PHP_ME(DBPointer, __toString, ai_DBPointer_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(DBPointer, jsonSerialize, ai_DBPointer_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(DBPointer, serialize, ai_DBPointer_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(DBPointer, unserialize, ai_DBPointer_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_DBPointer_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\DBPointer object handlers */
static zend_object_handlers php_phongo_handler_dbpointer;
static void php_phongo_dbpointer_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_dbpointer_t* intern = Z_OBJ_DBPOINTER(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->ref) {
efree(intern->ref);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
phongo_create_object_retval php_phongo_dbpointer_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_dbpointer_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_dbpointer_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_dbpointer;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_dbpointer_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_dbpointer;
return retval;
}
#endif
} /* }}} */
static int php_phongo_dbpointer_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_dbpointer_t *intern1, *intern2;
int retval;
intern1 = Z_DBPOINTER_OBJ_P(o1);
intern2 = Z_DBPOINTER_OBJ_P(o2);
retval = strcmp(intern1->ref, intern2->ref);
if (retval != 0) {
return retval;
}
return strcmp(intern1->id, intern2->id);
} /* }}} */
static HashTable* php_phongo_dbpointer_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_DBPOINTER_OBJ_P(object)->properties;
} /* }}} */
HashTable* php_phongo_dbpointer_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_dbpointer_t* intern;
HashTable* props;
intern = Z_DBPOINTER_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->ref) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval ref, id;
ZVAL_STRING(&ref, intern->ref);
ZVAL_STRING(&id, intern->id);
zend_hash_str_update(props, "ref", sizeof("ref") - 1, &ref);
zend_hash_str_update(props, "id", sizeof("id") - 1, &id);
}
#else
{
zval *ref, *id;
MAKE_STD_ZVAL(ref);
ZVAL_STRING(ref, intern->ref, 1);
MAKE_STD_ZVAL(id);
ZVAL_STRING(id, intern->id, 1);
zend_hash_update(props, "ref", sizeof("ref"), &ref, sizeof(ref), NULL);
zend_hash_update(props, "id", sizeof("id"), &id, sizeof(id), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_dbpointer_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_dbpointer_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_dbpointer_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_dbpointer_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_dbpointer_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "DBPointer", php_phongo_dbpointer_me);
php_phongo_dbpointer_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_dbpointer_ce->create_object = php_phongo_dbpointer_create_object;
PHONGO_CE_FINAL(php_phongo_dbpointer_ce);
zend_class_implements(php_phongo_dbpointer_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_dbpointer_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_dbpointer_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_dbpointer, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_dbpointer.compare_objects = php_phongo_dbpointer_compare_objects;
php_phongo_handler_dbpointer.get_debug_info = php_phongo_dbpointer_get_debug_info;
php_phongo_handler_dbpointer.get_gc = php_phongo_dbpointer_get_gc;
php_phongo_handler_dbpointer.get_properties = php_phongo_dbpointer_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_dbpointer.free_obj = php_phongo_dbpointer_free_object;
php_phongo_handler_dbpointer.offset = XtOffsetOf(php_phongo_dbpointer_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Decimal128.c 0000644 0000765 0000024 00000027465 13572250757 015764 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_decimal128_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_decimal128_init(php_phongo_decimal128_t* intern, const char* value TSRMLS_DC) /* {{{ */
{
if (!bson_decimal128_from_string(value, &intern->decimal)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing Decimal128 string: %s", value);
return false;
}
intern->initialized = true;
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_decimal128_init_from_hash(php_phongo_decimal128_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* dec;
if ((dec = zend_hash_str_find(props, "dec", sizeof("dec") - 1)) && Z_TYPE_P(dec) == IS_STRING) {
return php_phongo_decimal128_init(intern, Z_STRVAL_P(dec) TSRMLS_CC);
}
#else
zval** dec;
if (zend_hash_find(props, "dec", sizeof("dec"), (void**) &dec) == SUCCESS && Z_TYPE_PP(dec) == IS_STRING) {
return php_phongo_decimal128_init(intern, Z_STRVAL_PP(dec) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"dec\" string field", ZSTR_VAL(php_phongo_decimal128_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\Decimal128::__construct(string $value)
Construct a new BSON Decimal128 type */
static PHP_METHOD(Decimal128, __construct)
{
php_phongo_decimal128_t* intern;
zend_error_handling error_handling;
char* value;
phongo_zpp_char_len value_len;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_DECIMAL128_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &value, &value_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_decimal128_init(intern, value TSRMLS_CC);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Decimal128::__set_state(array $properties)
*/
static PHP_METHOD(Decimal128, __set_state)
{
php_phongo_decimal128_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_decimal128_ce);
intern = Z_DECIMAL128_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_decimal128_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Decimal128::__toString()
*/
static PHP_METHOD(Decimal128, __toString)
{
php_phongo_decimal128_t* intern;
char outbuf[BSON_DECIMAL128_STRING];
intern = Z_DECIMAL128_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
bson_decimal128_to_string(&intern->decimal, outbuf);
PHONGO_RETURN_STRING(outbuf);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Decimal128::jsonSerialize()
*/
static PHP_METHOD(Decimal128, jsonSerialize)
{
php_phongo_decimal128_t* intern;
char outbuf[BSON_DECIMAL128_STRING] = "";
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_DECIMAL128_OBJ_P(getThis());
array_init_size(return_value, 1);
bson_decimal128_to_string(&intern->decimal, outbuf);
ADD_ASSOC_STRING(return_value, "$numberDecimal", outbuf);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Decimal128::serialize()
*/
static PHP_METHOD(Decimal128, serialize)
{
php_phongo_decimal128_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
char outbuf[BSON_DECIMAL128_STRING];
intern = Z_DECIMAL128_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
bson_decimal128_to_string(&intern->decimal, outbuf);
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 1);
ADD_ASSOC_STRING(&retval, "dec", outbuf);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 1);
ADD_ASSOC_STRING(retval, "dec", outbuf);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Decimal128::unserialize(string $serialized)
*/
static PHP_METHOD(Decimal128, unserialize)
{
php_phongo_decimal128_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_DECIMAL128_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_decimal128_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_decimal128_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_decimal128_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Decimal128 function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Decimal128___construct, 0, 0, 1)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Decimal128___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Decimal128_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Decimal128_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_decimal128_me[] = {
/* clang-format off */
PHP_ME(Decimal128, __construct, ai_Decimal128___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Decimal128, __set_state, ai_Decimal128___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(Decimal128, __toString, ai_Decimal128_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Decimal128, jsonSerialize, ai_Decimal128_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Decimal128, serialize, ai_Decimal128_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Decimal128, unserialize, ai_Decimal128_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Decimal128 object handlers */
static zend_object_handlers php_phongo_handler_decimal128;
static void php_phongo_decimal128_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_decimal128_t* intern = Z_OBJ_DECIMAL128(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_decimal128_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_decimal128_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_decimal128_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_decimal128;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_decimal128_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_decimal128;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_decimal128_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_DECIMAL128_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_decimal128_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_decimal128_t* intern;
HashTable* props;
char outbuf[BSON_DECIMAL128_STRING] = "";
intern = Z_DECIMAL128_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 1);
if (!intern->initialized) {
return props;
}
bson_decimal128_to_string(&intern->decimal, outbuf);
#if PHP_VERSION_ID >= 70000
{
zval dec;
ZVAL_STRING(&dec, outbuf);
zend_hash_str_update(props, "dec", sizeof("dec") - 1, &dec);
}
#else
{
zval* dec;
MAKE_STD_ZVAL(dec);
ZVAL_STRING(dec, outbuf, 1);
zend_hash_update(props, "dec", sizeof("dec"), &dec, sizeof(dec), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_decimal128_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_decimal128_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_decimal128_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_decimal128_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_decimal128_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Decimal128", php_phongo_decimal128_me);
php_phongo_decimal128_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_decimal128_ce->create_object = php_phongo_decimal128_create_object;
PHONGO_CE_FINAL(php_phongo_decimal128_ce);
zend_class_implements(php_phongo_decimal128_ce TSRMLS_CC, 1, php_phongo_decimal128_interface_ce);
zend_class_implements(php_phongo_decimal128_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_decimal128_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_decimal128_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_decimal128, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_decimal128.get_debug_info = php_phongo_decimal128_get_debug_info;
php_phongo_handler_decimal128.get_gc = php_phongo_decimal128_get_gc;
php_phongo_handler_decimal128.get_properties = php_phongo_decimal128_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_decimal128.free_obj = php_phongo_decimal128_free_object;
php_phongo_handler_decimal128.offset = XtOffsetOf(php_phongo_decimal128_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Decimal128Interface.c 0000644 0000765 0000024 00000003037 13572250757 017572 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_decimal128_interface_ce;
/* {{{ MongoDB\BSON\Decimal128Interface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Decimal128Interface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_decimal128_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(Decimal128Interface, __toString, ai_Decimal128Interface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_decimal128_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Decimal128Interface", php_phongo_decimal128_interface_me);
php_phongo_decimal128_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Int64.c 0000644 0000765 0000024 00000026406 13572250757 015071 0 ustar alcaeus staff /*
* Copyright 2018-present 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_int64_ce;
/* Initialize the object and return whether it was successful. */
static bool php_phongo_int64_init(php_phongo_int64_t* intern, int64_t integer) /* {{{ */
{
intern->integer = integer;
intern->initialized = true;
return true;
} /* }}} */
/* Initialize the object from a numeric string and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_int64_init_from_string(php_phongo_int64_t* intern, const char* s_integer, phongo_zpp_char_len s_integer_len TSRMLS_DC) /* {{{ */
{
int64_t integer;
char* endptr = NULL;
/* bson_ascii_strtoll() sets errno if conversion fails. If conversion
* succeeds, we still want to ensure that the entire string was parsed. */
integer = bson_ascii_strtoll(s_integer, &endptr, 10);
if (errno || (endptr && endptr != ((const char*) s_integer + s_integer_len))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing \"%s\" as 64-bit integer for %s initialization", s_integer, ZSTR_VAL(php_phongo_int64_ce->name));
return false;
}
return php_phongo_int64_init(intern, integer);
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_int64_init_from_hash(php_phongo_int64_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* value;
if ((value = zend_hash_str_find(props, "integer", sizeof("integer") - 1)) && Z_TYPE_P(value) == IS_STRING) {
return php_phongo_int64_init_from_string(intern, Z_STRVAL_P(value), Z_STRLEN_P(value) TSRMLS_CC);
}
#else
zval** value;
if (zend_hash_find(props, "integer", sizeof("integer"), (void**) &value) == SUCCESS && Z_TYPE_PP(value) == IS_STRING) {
return php_phongo_int64_init_from_string(intern, Z_STRVAL_PP(value), Z_STRLEN_PP(value) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"integer\" string field", ZSTR_VAL(php_phongo_int64_ce->name));
return false;
} /* }}} */
/* {{{ proto string MongoDB\BSON\Int64::__toString()
Return the Int64's value as a string. */
static PHP_METHOD(Int64, __toString)
{
php_phongo_int64_t* intern;
char s_integer[24];
int s_integer_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_INT64_OBJ_P(getThis());
s_integer_len = snprintf(s_integer, sizeof(s_integer), "%" PRId64, intern->integer);
PHONGO_RETVAL_STRINGL(s_integer, s_integer_len);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Int64::jsonSerialize()
*/
static PHP_METHOD(Int64, jsonSerialize)
{
php_phongo_int64_t* intern;
char s_integer[24];
int s_integer_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_INT64_OBJ_P(getThis());
s_integer_len = snprintf(s_integer, sizeof(s_integer), "%" PRId64, intern->integer);
array_init_size(return_value, 1);
ADD_ASSOC_STRINGL(return_value, "$numberLong", s_integer, s_integer_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Int64::serialize()
*/
static PHP_METHOD(Int64, serialize)
{
php_phongo_int64_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
char s_integer[24];
int s_integer_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_INT64_OBJ_P(getThis());
s_integer_len = snprintf(s_integer, sizeof(s_integer), "%" PRId64, intern->integer);
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 1);
ADD_ASSOC_STRINGL(&retval, "integer", s_integer, s_integer_len);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 1);
ADD_ASSOC_STRINGL(retval, "integer", s_integer, s_integer_len);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Int64::unserialize(string $serialized)
*/
static PHP_METHOD(Int64, unserialize)
{
php_phongo_int64_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_INT64_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_int64_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_int64_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_int64_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Int64 function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Int64_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Int64_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_int64_me[] = {
/* clang-format off */
/* __set_state intentionally missing */
PHP_ME(Int64, __toString, ai_Int64_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Int64, jsonSerialize, ai_Int64_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Int64, serialize, ai_Int64_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Int64, unserialize, ai_Int64_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Int64_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Int64 object handlers */
static zend_object_handlers php_phongo_handler_int64;
static void php_phongo_int64_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_int64_t* intern = Z_OBJ_INT64(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
phongo_create_object_retval php_phongo_int64_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_int64_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_int64_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_int64;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_int64_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_int64;
return retval;
}
#endif
} /* }}} */
static int php_phongo_int64_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_int64_t *intern1, *intern2;
intern1 = Z_INT64_OBJ_P(o1);
intern2 = Z_INT64_OBJ_P(o2);
if (intern1->integer != intern2->integer) {
return intern1->integer < intern2->integer ? -1 : 1;
}
return 0;
} /* }}} */
static HashTable* php_phongo_int64_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_INT64_OBJ_P(object)->properties;
} /* }}} */
HashTable* php_phongo_int64_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_int64_t* intern;
HashTable* props;
char s_integer[24];
int s_integer_len;
intern = Z_INT64_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->initialized) {
return props;
}
s_integer_len = snprintf(s_integer, sizeof(s_integer), "%" PRId64, intern->integer);
#if PHP_VERSION_ID >= 70000
{
zval value;
ZVAL_STRINGL(&value, s_integer, s_integer_len);
zend_hash_str_update(props, "integer", sizeof("integer") - 1, &value);
}
#else
{
zval* value;
MAKE_STD_ZVAL(value);
ZVAL_STRINGL(value, s_integer, s_integer_len, 1);
zend_hash_update(props, "integer", sizeof("integer"), &value, sizeof(value), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_int64_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_int64_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_int64_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_int64_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_int64_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Int64", php_phongo_int64_me);
php_phongo_int64_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_int64_ce->create_object = php_phongo_int64_create_object;
PHONGO_CE_FINAL(php_phongo_int64_ce);
zend_class_implements(php_phongo_int64_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_int64_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_int64_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_int64, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_int64.compare_objects = php_phongo_int64_compare_objects;
php_phongo_handler_int64.get_debug_info = php_phongo_int64_get_debug_info;
php_phongo_handler_int64.get_gc = php_phongo_int64_get_gc;
php_phongo_handler_int64.get_properties = php_phongo_int64_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_int64.free_obj = php_phongo_int64_free_object;
php_phongo_handler_int64.offset = XtOffsetOf(php_phongo_int64_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Javascript.c 0000644 0000765 0000024 00000041153 13572250757 016267 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_javascript_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_javascript_init(php_phongo_javascript_t* intern, const char* code, phongo_zpp_char_len code_len, zval* scope TSRMLS_DC) /* {{{ */
{
if (scope && Z_TYPE_P(scope) != IS_OBJECT && Z_TYPE_P(scope) != IS_ARRAY && Z_TYPE_P(scope) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected scope to be array or object, %s given", zend_get_type_by_const(Z_TYPE_P(scope)));
return false;
}
if (strlen(code) != (size_t) code_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Code cannot contain null bytes");
return false;
}
intern->code = estrndup(code, code_len);
intern->code_len = code_len;
if (scope && (Z_TYPE_P(scope) == IS_OBJECT || Z_TYPE_P(scope) == IS_ARRAY)) {
intern->scope = bson_new();
php_phongo_zval_to_bson(scope, PHONGO_BSON_NONE, intern->scope, NULL TSRMLS_CC);
} else {
intern->scope = NULL;
}
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_javascript_init_from_hash(php_phongo_javascript_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *code, *scope;
if ((code = zend_hash_str_find(props, "code", sizeof("code") - 1)) && Z_TYPE_P(code) == IS_STRING) {
scope = zend_hash_str_find(props, "scope", sizeof("scope") - 1);
return php_phongo_javascript_init(intern, Z_STRVAL_P(code), Z_STRLEN_P(code), scope TSRMLS_CC);
}
#else
zval **code, **scope;
if (zend_hash_find(props, "code", sizeof("code"), (void**) &code) == SUCCESS && Z_TYPE_PP(code) == IS_STRING) {
zval* tmp = zend_hash_find(props, "scope", sizeof("scope"), (void**) &scope) == SUCCESS ? *scope : NULL;
return php_phongo_javascript_init(intern, Z_STRVAL_PP(code), Z_STRLEN_PP(code), tmp TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"code\" string field", ZSTR_VAL(php_phongo_javascript_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\Javascript::__construct(string $code[, array|object $scope])
Construct a new BSON Javascript type. The scope is a document mapping
identifiers and values, representing the scope in which the code string will
be evaluated. Note that this type cannot be represented as Extended JSON. */
static PHP_METHOD(Javascript, __construct)
{
php_phongo_javascript_t* intern;
zend_error_handling error_handling;
char* code;
phongo_zpp_char_len code_len;
zval* scope = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_JAVASCRIPT_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|A!", &code, &code_len, &scope) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_javascript_init(intern, code, code_len, scope TSRMLS_CC);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Javascript::__set_state(array $properties)
*/
static PHP_METHOD(Javascript, __set_state)
{
php_phongo_javascript_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_javascript_ce);
intern = Z_JAVASCRIPT_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_javascript_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Javascript::__toString()
Return the Javascript's code string. */
static PHP_METHOD(Javascript, __toString)
{
php_phongo_javascript_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_JAVASCRIPT_OBJ_P(getThis());
PHONGO_RETURN_STRINGL(intern->code, intern->code_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Javascript::getCode()
*/
static PHP_METHOD(Javascript, getCode)
{
php_phongo_javascript_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_JAVASCRIPT_OBJ_P(getThis());
PHONGO_RETURN_STRINGL(intern->code, intern->code_len);
} /* }}} */
/* {{{ proto object|null MongoDB\BSON\Javascript::getScope()
*/
static PHP_METHOD(Javascript, getScope)
{
php_phongo_javascript_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_JAVASCRIPT_OBJ_P(getThis());
if (!intern->scope) {
RETURN_NULL();
}
if (intern->scope->len) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} else {
RETURN_NULL();
}
} /* }}} */
/* {{{ proto array MongoDB\BSON\Javascript::jsonSerialize()
*/
static PHP_METHOD(Javascript, jsonSerialize)
{
php_phongo_javascript_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_JAVASCRIPT_OBJ_P(getThis());
array_init_size(return_value, 2);
ADD_ASSOC_STRINGL(return_value, "$code", intern->code, intern->code_len);
if (intern->scope && intern->scope->len) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
if (php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state)) {
#if PHP_VERSION_ID >= 70000
Z_ADDREF(state.zchild);
ADD_ASSOC_ZVAL_EX(return_value, "$scope", &state.zchild);
#else
Z_ADDREF_P(state.zchild);
ADD_ASSOC_ZVAL_EX(return_value, "$scope", state.zchild);
#endif
}
zval_ptr_dtor(&state.zchild);
}
} /* }}} */
/* {{{ proto string MongoDB\BSON\Javascript::serialize()
*/
static PHP_METHOD(Javascript, serialize)
{
php_phongo_javascript_t* intern;
ZVAL_RETVAL_TYPE retval;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_JAVASCRIPT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
if (intern->scope && intern->scope->len) {
if (!php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state)) {
return;
}
Z_ADDREF(state.zchild);
} else {
ZVAL_NULL(&state.zchild);
}
#else
if (intern->scope && intern->scope->len) {
if (!php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state)) {
return;
}
Z_ADDREF_P(state.zchild);
} else {
MAKE_STD_ZVAL(state.zchild);
ZVAL_NULL(state.zchild);
Z_ADDREF_P(state.zchild);
}
#endif
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "code", intern->code, intern->code_len);
ADD_ASSOC_ZVAL(&retval, "scope", &state.zchild);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "code", intern->code, intern->code_len);
ADD_ASSOC_ZVAL(retval, "scope", state.zchild);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
zval_ptr_dtor(&state.zchild);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Javascript::unserialize(string $serialized)
*/
static PHP_METHOD(Javascript, unserialize)
{
php_phongo_javascript_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_JAVASCRIPT_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_javascript_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_javascript_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_javascript_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Javascript function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Javascript___construct, 0, 0, 1)
ZEND_ARG_INFO(0, javascript)
ZEND_ARG_INFO(0, scope)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Javascript___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Javascript_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Javascript_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_javascript_me[] = {
/* clang-format off */
PHP_ME(Javascript, __construct, ai_Javascript___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, __set_state, ai_Javascript___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(Javascript, __toString, ai_Javascript_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, jsonSerialize, ai_Javascript_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, serialize, ai_Javascript_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, unserialize, ai_Javascript_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, getCode, ai_Javascript_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Javascript, getScope, ai_Javascript_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Javascript object handlers */
static zend_object_handlers php_phongo_handler_javascript;
static void php_phongo_javascript_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t* intern = Z_OBJ_JAVASCRIPT(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->code) {
efree(intern->code);
}
if (intern->scope) {
bson_destroy(intern->scope);
intern->scope = NULL;
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
phongo_create_object_retval php_phongo_javascript_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_javascript_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_javascript;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_javascript_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_javascript;
return retval;
}
#endif
} /* }}} */
static int php_phongo_javascript_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t *intern1, *intern2;
intern1 = Z_JAVASCRIPT_OBJ_P(o1);
intern2 = Z_JAVASCRIPT_OBJ_P(o2);
/* Do not consider the scope document for comparisons */
return strcmp(intern1->code, intern2->code);
} /* }}} */
static HashTable* php_phongo_javascript_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_JAVASCRIPT_OBJ_P(object)->properties;
} /* }}} */
HashTable* php_phongo_javascript_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_javascript_t* intern;
HashTable* props;
intern = Z_JAVASCRIPT_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->code) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval code;
ZVAL_STRING(&code, intern->code);
zend_hash_str_update(props, "code", sizeof("code") - 1, &code);
if (intern->scope) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
if (php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state)) {
Z_ADDREF(state.zchild);
zend_hash_str_update(props, "scope", sizeof("scope") - 1, &state.zchild);
} else {
zval scope;
ZVAL_NULL(&scope);
zend_hash_str_update(props, "scope", sizeof("scope") - 1, &scope);
}
zval_ptr_dtor(&state.zchild);
} else {
zval scope;
ZVAL_NULL(&scope);
zend_hash_str_update(props, "scope", sizeof("scope") - 1, &scope);
}
}
#else
{
zval* code;
MAKE_STD_ZVAL(code);
ZVAL_STRING(code, intern->code, 1);
zend_hash_update(props, "code", sizeof("code"), &code, sizeof(code), NULL);
if (intern->scope) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
if (php_phongo_bson_to_zval_ex(bson_get_data(intern->scope), intern->scope->len, &state)) {
Z_ADDREF_P(state.zchild);
zend_hash_update(props, "scope", sizeof("scope"), &state.zchild, sizeof(state.zchild), NULL);
} else {
zval* scope;
MAKE_STD_ZVAL(scope);
ZVAL_NULL(scope);
zend_hash_update(props, "scope", sizeof("scope"), &scope, sizeof(scope), NULL);
}
zval_ptr_dtor(&state.zchild);
} else {
zval* scope;
MAKE_STD_ZVAL(scope);
ZVAL_NULL(scope);
zend_hash_update(props, "scope", sizeof("scope"), &scope, sizeof(scope), NULL);
}
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_javascript_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_javascript_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_javascript_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_javascript_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_javascript_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Javascript", php_phongo_javascript_me);
php_phongo_javascript_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_javascript_ce->create_object = php_phongo_javascript_create_object;
PHONGO_CE_FINAL(php_phongo_javascript_ce);
zend_class_implements(php_phongo_javascript_ce TSRMLS_CC, 1, php_phongo_javascript_interface_ce);
zend_class_implements(php_phongo_javascript_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_javascript_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_javascript_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_javascript, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_javascript.compare_objects = php_phongo_javascript_compare_objects;
php_phongo_handler_javascript.get_debug_info = php_phongo_javascript_get_debug_info;
php_phongo_handler_javascript.get_gc = php_phongo_javascript_get_gc;
php_phongo_handler_javascript.get_properties = php_phongo_javascript_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_javascript.free_obj = php_phongo_javascript_free_object;
php_phongo_handler_javascript.offset = XtOffsetOf(php_phongo_javascript_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/JavascriptInterface.c 0000644 0000765 0000024 00000003272 13572250757 020110 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_javascript_interface_ce;
/* {{{ MongoDB\BSON\JavascriptInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_JavascriptInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_javascript_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(JavascriptInterface, getCode, ai_JavascriptInterface_void)
ZEND_ABSTRACT_ME(JavascriptInterface, getScope, ai_JavascriptInterface_void)
ZEND_ABSTRACT_ME(JavascriptInterface, __toString, ai_JavascriptInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_javascript_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "JavascriptInterface", php_phongo_javascript_interface_me);
php_phongo_javascript_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/MaxKey.c 0000644 0000765 0000024 00000012177 13572250757 015363 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_maxkey_ce;
/* {{{ proto void MongoDB\BSON\MaxKey::__set_state(array $properties)
*/
static PHP_METHOD(MaxKey, __set_state)
{
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_maxkey_ce);
} /* }}} */
/* {{{ proto array MongoDB\BSON\MaxKey::jsonSerialize()
*/
static PHP_METHOD(MaxKey, jsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init_size(return_value, 1);
ADD_ASSOC_LONG_EX(return_value, "$maxKey", 1);
} /* }}} */
/* {{{ proto string MongoDB\BSON\MaxKey::serialize()
*/
static PHP_METHOD(MaxKey, serialize)
{
PHONGO_RETURN_STRING("");
} /* }}} */
/* {{{ proto void MongoDB\BSON\MaxKey::unserialize(string $serialized)
*/
static PHP_METHOD(MaxKey, unserialize)
{
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ MongoDB\BSON\MaxKey function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_MaxKey___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_MaxKey_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_MaxKey_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_maxkey_me[] = {
/* clang-format off */
PHP_ME(MaxKey, __set_state, ai_MaxKey___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(MaxKey, jsonSerialize, ai_MaxKey_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(MaxKey, serialize, ai_MaxKey_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(MaxKey, unserialize, ai_MaxKey_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\MaxKey object handlers */
static zend_object_handlers php_phongo_handler_maxkey;
static void php_phongo_maxkey_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_maxkey_t* intern = Z_OBJ_MAXKEY(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_maxkey_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_maxkey_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_maxkey_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_maxkey;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_maxkey_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_maxkey;
return retval;
}
#endif
} /* }}} */
/* }}} */
void php_phongo_maxkey_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MaxKey", php_phongo_maxkey_me);
php_phongo_maxkey_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_maxkey_ce->create_object = php_phongo_maxkey_create_object;
PHONGO_CE_FINAL(php_phongo_maxkey_ce);
zend_class_implements(php_phongo_maxkey_ce TSRMLS_CC, 1, php_phongo_maxkey_interface_ce);
zend_class_implements(php_phongo_maxkey_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_maxkey_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_maxkey_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_maxkey, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
#if PHP_VERSION_ID >= 70000
php_phongo_handler_maxkey.free_obj = php_phongo_maxkey_free_object;
php_phongo_handler_maxkey.offset = XtOffsetOf(php_phongo_maxkey_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/MaxKeyInterface.c 0000644 0000765 0000024 00000002462 13572250757 017200 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_maxkey_interface_ce;
/* {{{ MongoDB\BSON\MaxKeyInterface function entries */
static zend_function_entry php_phongo_maxkey_interface_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_maxkey_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MaxKeyInterface", php_phongo_maxkey_interface_me);
php_phongo_maxkey_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/MinKey.c 0000644 0000765 0000024 00000012200 13572250757 015344 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_minkey_ce;
/* {{{ proto void MongoDB\BSON\MinKey::__set_state(array $properties)
*/
static PHP_METHOD(MinKey, __set_state)
{
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_minkey_ce);
} /* }}} */
/* {{{ proto array MongoDB\BSON\MinKey::jsonSerialize()
*/
static PHP_METHOD(MinKey, jsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init_size(return_value, 1);
ADD_ASSOC_LONG_EX(return_value, "$minKey", 1);
} /* }}} */
/* {{{ proto string MongoDB\BSON\MinKey::serialize()
*/
static PHP_METHOD(MinKey, serialize)
{
PHONGO_RETURN_STRING("");
} /* }}} */
/* {{{ proto void MongoDB\BSON\MinKey::unserialize(string $serialized)
*/
static PHP_METHOD(MinKey, unserialize)
{
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ MongoDB\BSON\MinKey function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_MinKey___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_MinKey_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_MinKey_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_minkey_me[] = {
/* clang-format off */
PHP_ME(MinKey, __set_state, ai_MinKey___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(MinKey, jsonSerialize, ai_MinKey_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(MinKey, serialize, ai_MinKey_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(MinKey, unserialize, ai_MinKey_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\MinKey object handlers */
static zend_object_handlers php_phongo_handler_minkey;
static void php_phongo_minkey_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_minkey_t* intern = Z_OBJ_MINKEY(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_minkey_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_minkey_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_minkey_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_minkey;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_minkey_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_minkey;
return retval;
}
#endif
} /* }}} */
/* }}} */
void php_phongo_minkey_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MinKey", php_phongo_minkey_me);
php_phongo_minkey_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_minkey_ce->create_object = php_phongo_minkey_create_object;
PHONGO_CE_FINAL(php_phongo_minkey_ce);
zend_class_implements(php_phongo_minkey_ce TSRMLS_CC, 1, php_phongo_minkey_interface_ce);
zend_class_implements(php_phongo_minkey_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_minkey_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_minkey_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_minkey, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
#if PHP_VERSION_ID >= 70000
php_phongo_handler_minkey.free_obj = php_phongo_minkey_free_object;
php_phongo_handler_minkey.offset = XtOffsetOf(php_phongo_minkey_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/MinKeyInterface.c 0000644 0000765 0000024 00000002462 13572250757 017176 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_minkey_interface_ce;
/* {{{ MongoDB\BSON\MinKeyInterface function entries */
static zend_function_entry php_phongo_minkey_interface_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_minkey_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MinKeyInterface", php_phongo_minkey_interface_me);
php_phongo_minkey_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/ObjectId.c 0000644 0000765 0000024 00000031137 13572250757 015645 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_objectid_ce;
/* Initialize the object with a generated value and return whether it was
* successful. */
static bool php_phongo_objectid_init(php_phongo_objectid_t* intern)
{
bson_oid_t oid;
intern->initialized = true;
bson_oid_init(&oid, NULL);
bson_oid_to_string(&oid, intern->oid);
return true;
}
/* Initialize the object from a hex string and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_objectid_init_from_hex_string(php_phongo_objectid_t* intern, const char* hex, phongo_zpp_char_len hex_len TSRMLS_DC) /* {{{ */
{
if (bson_oid_is_valid(hex, hex_len)) {
bson_oid_t oid;
bson_oid_init_from_string(&oid, hex);
bson_oid_to_string(&oid, intern->oid);
intern->initialized = true;
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing ObjectId string: %s", hex);
return false;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_objectid_init_from_hash(php_phongo_objectid_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* z_oid;
z_oid = zend_hash_str_find(props, "oid", sizeof("oid") - 1);
if (z_oid && Z_TYPE_P(z_oid) == IS_STRING) {
return php_phongo_objectid_init_from_hex_string(intern, Z_STRVAL_P(z_oid), Z_STRLEN_P(z_oid) TSRMLS_CC);
}
#else
zval** z_oid;
if (zend_hash_find(props, "oid", sizeof("oid"), (void**) &z_oid) == SUCCESS && Z_TYPE_PP(z_oid) == IS_STRING) {
return php_phongo_objectid_init_from_hex_string(intern, Z_STRVAL_PP(z_oid), Z_STRLEN_PP(z_oid) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"oid\" string field", ZSTR_VAL(php_phongo_objectid_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\ObjectId::__construct([string $id])
Constructs a new BSON ObjectId type, optionally from a hex string. */
static PHP_METHOD(ObjectId, __construct)
{
php_phongo_objectid_t* intern;
zend_error_handling error_handling;
char* id = NULL;
phongo_zpp_char_len id_len;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_OBJECTID_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!", &id, &id_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (id) {
php_phongo_objectid_init_from_hex_string(intern, id, id_len TSRMLS_CC);
} else {
php_phongo_objectid_init(intern);
}
} /* }}} */
/* {{{ proto integer MongoDB\BSON\ObjectId::getTimestamp()
*/
static PHP_METHOD(ObjectId, getTimestamp)
{
php_phongo_objectid_t* intern;
bson_oid_t tmp_oid;
intern = Z_OBJECTID_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
bson_oid_init_from_string(&tmp_oid, intern->oid);
RETVAL_LONG(bson_oid_get_time_t(&tmp_oid));
} /* }}} */
/* {{{ proto MongoDB\BSON\ObjectId::__set_state(array $properties)
*/
static PHP_METHOD(ObjectId, __set_state)
{
php_phongo_objectid_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_objectid_ce);
intern = Z_OBJECTID_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_objectid_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\ObjectId::__toString()
*/
static PHP_METHOD(ObjectId, __toString)
{
php_phongo_objectid_t* intern;
intern = Z_OBJECTID_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRINGL(intern->oid, 24);
} /* }}} */
/* {{{ proto array MongoDB\BSON\ObjectId::jsonSerialize()
*/
static PHP_METHOD(ObjectId, jsonSerialize)
{
php_phongo_objectid_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_OBJECTID_OBJ_P(getThis());
array_init_size(return_value, 1);
ADD_ASSOC_STRINGL(return_value, "$oid", intern->oid, 24);
} /* }}} */
/* {{{ proto string MongoDB\BSON\ObjectId::serialize()
*/
static PHP_METHOD(ObjectId, serialize)
{
php_phongo_objectid_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_OBJECTID_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "oid", intern->oid, 24);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "oid", intern->oid, 24);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\ObjectId::unserialize(string $serialized)
*/
static PHP_METHOD(ObjectId, unserialize)
{
php_phongo_objectid_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_OBJECTID_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_objectid_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_objectid_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_objectid_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\ObjectId function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_ObjectId___construct, 0, 0, 0)
ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ObjectId___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ObjectId_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ObjectId_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_objectid_me[] = {
/* clang-format off */
PHP_ME(ObjectId, __construct, ai_ObjectId___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ObjectId, getTimestamp, ai_ObjectId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ObjectId, __set_state, ai_ObjectId___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(ObjectId, __toString, ai_ObjectId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ObjectId, jsonSerialize, ai_ObjectId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ObjectId, serialize, ai_ObjectId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ObjectId, unserialize, ai_ObjectId_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\ObjectId object handlers */
static zend_object_handlers php_phongo_handler_objectid;
static void php_phongo_objectid_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_objectid_t* intern = Z_OBJ_OBJECTID(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_objectid_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_objectid_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_objectid_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_objectid;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_objectid_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_objectid;
return retval;
}
#endif
} /* }}} */
static int php_phongo_objectid_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_objectid_t* intern1;
php_phongo_objectid_t* intern2;
intern1 = Z_OBJECTID_OBJ_P(o1);
intern2 = Z_OBJECTID_OBJ_P(o2);
return strcmp(intern1->oid, intern2->oid);
} /* }}} */
static HashTable* php_phongo_objectid_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_OBJECTID_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_objectid_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_objectid_t* intern;
HashTable* props;
intern = Z_OBJECTID_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 1);
if (!intern->initialized) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval zv;
ZVAL_STRING(&zv, intern->oid);
zend_hash_str_update(props, "oid", sizeof("oid") - 1, &zv);
}
#else
{
zval* zv;
MAKE_STD_ZVAL(zv);
ZVAL_STRING(zv, intern->oid, 1);
zend_hash_update(props, "oid", sizeof("oid"), &zv, sizeof(zv), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_objectid_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_objectid_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_objectid_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_objectid_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_objectid_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "ObjectId", php_phongo_objectid_me);
php_phongo_objectid_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_objectid_ce->create_object = php_phongo_objectid_create_object;
PHONGO_CE_FINAL(php_phongo_objectid_ce);
zend_class_implements(php_phongo_objectid_ce TSRMLS_CC, 1, php_phongo_objectid_interface_ce);
zend_class_implements(php_phongo_objectid_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_objectid_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_objectid_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_objectid, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_objectid.compare_objects = php_phongo_objectid_compare_objects;
php_phongo_handler_objectid.get_debug_info = php_phongo_objectid_get_debug_info;
php_phongo_handler_objectid.get_gc = php_phongo_objectid_get_gc;
php_phongo_handler_objectid.get_properties = php_phongo_objectid_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_objectid.free_obj = php_phongo_objectid_free_object;
php_phongo_handler_objectid.offset = XtOffsetOf(php_phongo_objectid_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/ObjectIdInterface.c 0000644 0000765 0000024 00000003131 13572250757 017457 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_objectid_interface_ce;
/* {{{ MongoDB\BSON\ObjectIdInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_ObjectIdInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_objectid_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(ObjectIdInterface, getTimestamp, ai_ObjectIdInterface_void)
ZEND_ABSTRACT_ME(ObjectIdInterface, __toString, ai_ObjectIdInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_objectid_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "ObjectIdInterface", php_phongo_objectid_interface_me);
php_phongo_objectid_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Persistable.c 0000644 0000765 0000024 00000002620 13572250757 016432 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_persistable_ce;
/* {{{ MongoDB\BSON\Persistable function entries */
static zend_function_entry php_phongo_persistable_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_persistable_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Persistable", php_phongo_persistable_me);
php_phongo_persistable_ce = zend_register_internal_interface(&ce TSRMLS_CC);
zend_class_implements(php_phongo_persistable_ce TSRMLS_CC, 2, php_phongo_unserializable_ce, php_phongo_serializable_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Regex.c 0000644 0000765 0000024 00000035057 13572250757 015241 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_regex_ce;
/* qsort() compare callback for alphabetizing regex flags upon initialization */
static int php_phongo_regex_compare_flags(const void* f1, const void* f2) /* {{{ */
{
if (*(const char*) f1 == *(const char*) f2) {
return 0;
}
return (*(const char*) f1 > *(const char*) f2) ? 1 : -1;
} /* }}} */
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_regex_init(php_phongo_regex_t* intern, const char* pattern, phongo_zpp_char_len pattern_len, const char* flags, phongo_zpp_char_len flags_len TSRMLS_DC) /* {{{ */
{
if (strlen(pattern) != (size_t) pattern_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Pattern cannot contain null bytes");
return false;
}
intern->pattern = estrndup(pattern, pattern_len);
intern->pattern_len = pattern_len;
if (flags) {
if (strlen(flags) != (size_t) flags_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Flags cannot contain null bytes");
return false;
}
intern->flags = estrndup(flags, flags_len);
intern->flags_len = flags_len;
/* Ensure flags are alphabetized upon initialization */
qsort((void*) intern->flags, flags_len, 1, php_phongo_regex_compare_flags);
} else {
intern->flags = estrdup("");
intern->flags_len = 0;
}
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_regex_init_from_hash(php_phongo_regex_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *pattern, *flags;
if ((pattern = zend_hash_str_find(props, "pattern", sizeof("pattern") - 1)) && Z_TYPE_P(pattern) == IS_STRING &&
(flags = zend_hash_str_find(props, "flags", sizeof("flags") - 1)) && Z_TYPE_P(flags) == IS_STRING) {
return php_phongo_regex_init(intern, Z_STRVAL_P(pattern), Z_STRLEN_P(pattern), Z_STRVAL_P(flags), Z_STRLEN_P(flags) TSRMLS_CC);
}
#else
zval **pattern, **flags;
if (zend_hash_find(props, "pattern", sizeof("pattern"), (void**) &pattern) == SUCCESS && Z_TYPE_PP(pattern) == IS_STRING &&
zend_hash_find(props, "flags", sizeof("flags"), (void**) &flags) == SUCCESS && Z_TYPE_PP(flags) == IS_STRING) {
return php_phongo_regex_init(intern, Z_STRVAL_PP(pattern), Z_STRLEN_PP(pattern), Z_STRVAL_PP(flags), Z_STRLEN_PP(flags) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"pattern\" and \"flags\" string fields", ZSTR_VAL(php_phongo_regex_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\Regex::__construct(string $pattern [, string $flags])
Constructs a new BSON regular expression type. */
static PHP_METHOD(Regex, __construct)
{
php_phongo_regex_t* intern;
zend_error_handling error_handling;
char* pattern;
phongo_zpp_char_len pattern_len;
char* flags = NULL;
phongo_zpp_char_len flags_len = 0;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_REGEX_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &pattern, &pattern_len, &flags, &flags_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_regex_init(intern, pattern, pattern_len, flags, flags_len TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Regex::getPattern()
*/
static PHP_METHOD(Regex, getPattern)
{
php_phongo_regex_t* intern;
intern = Z_REGEX_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRINGL(intern->pattern, intern->pattern_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Regex::getFlags()
*/
static PHP_METHOD(Regex, getFlags)
{
php_phongo_regex_t* intern;
intern = Z_REGEX_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRINGL(intern->flags, intern->flags_len);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Regex::__set_state(array $properties)
*/
static PHP_METHOD(Regex, __set_state)
{
php_phongo_regex_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_regex_ce);
intern = Z_REGEX_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_regex_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Regex::__toString()
Returns a string in the form: /pattern/flags */
static PHP_METHOD(Regex, __toString)
{
php_phongo_regex_t* intern;
char* regex;
int regex_len;
intern = Z_REGEX_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
regex_len = spprintf(®ex, 0, "/%s/%s", intern->pattern, intern->flags);
PHONGO_RETVAL_STRINGL(regex, regex_len);
efree(regex);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Regex::jsonSerialize()
*/
static PHP_METHOD(Regex, jsonSerialize)
{
php_phongo_regex_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_REGEX_OBJ_P(getThis());
array_init_size(return_value, 2);
ADD_ASSOC_STRINGL(return_value, "$regex", intern->pattern, intern->pattern_len);
ADD_ASSOC_STRINGL(return_value, "$options", intern->flags, intern->flags_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Regex::serialize()
*/
static PHP_METHOD(Regex, serialize)
{
php_phongo_regex_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_REGEX_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "pattern", intern->pattern, intern->pattern_len);
ADD_ASSOC_STRINGL(&retval, "flags", intern->flags, intern->flags_len);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "pattern", intern->pattern, intern->pattern_len);
ADD_ASSOC_STRINGL(retval, "flags", intern->flags, intern->flags_len);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Regex::unserialize(string $serialized)
*/
static PHP_METHOD(Regex, unserialize)
{
php_phongo_regex_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_REGEX_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_regex_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_regex_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_regex_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Regex function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Regex___construct, 0, 0, 2)
ZEND_ARG_INFO(0, pattern)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Regex___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Regex_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Regex_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_regex_me[] = {
/* clang-format off */
PHP_ME(Regex, __construct, ai_Regex___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, __set_state, ai_Regex___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(Regex, __toString, ai_Regex_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, jsonSerialize, ai_Regex_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, serialize, ai_Regex_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, unserialize, ai_Regex_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, getPattern, ai_Regex_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Regex, getFlags, ai_Regex_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Regex object handlers */
static zend_object_handlers php_phongo_handler_regex;
static void php_phongo_regex_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_regex_t* intern = Z_OBJ_REGEX(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->pattern) {
efree(intern->pattern);
}
if (intern->flags) {
efree(intern->flags);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_regex_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_regex_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_regex_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_regex;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_regex_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_regex;
return retval;
}
#endif
} /* }}} */
static int php_phongo_regex_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_regex_t *intern1, *intern2;
int retval;
intern1 = Z_REGEX_OBJ_P(o1);
intern2 = Z_REGEX_OBJ_P(o2);
/* MongoDB compares the pattern string before the flags. */
retval = strcmp(intern1->pattern, intern2->pattern);
if (retval != 0) {
return retval;
}
return strcmp(intern1->flags, intern2->flags);
} /* }}} */
static HashTable* php_phongo_regex_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_REGEX_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_regex_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_regex_t* intern;
HashTable* props;
intern = Z_REGEX_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->pattern) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval pattern, flags;
ZVAL_STRINGL(&pattern, intern->pattern, intern->pattern_len);
zend_hash_str_update(props, "pattern", sizeof("pattern") - 1, &pattern);
ZVAL_STRINGL(&flags, intern->flags, intern->flags_len);
zend_hash_str_update(props, "flags", sizeof("flags") - 1, &flags);
}
#else
{
zval *pattern, *flags;
MAKE_STD_ZVAL(pattern);
ZVAL_STRINGL(pattern, intern->pattern, intern->pattern_len, 1);
zend_hash_update(props, "pattern", sizeof("pattern"), &pattern, sizeof(pattern), NULL);
MAKE_STD_ZVAL(flags);
ZVAL_STRINGL(flags, intern->flags, intern->flags_len, 1);
zend_hash_update(props, "flags", sizeof("flags"), &flags, sizeof(flags), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_regex_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_regex_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_regex_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_regex_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_regex_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Regex", php_phongo_regex_me);
php_phongo_regex_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_regex_ce->create_object = php_phongo_regex_create_object;
PHONGO_CE_FINAL(php_phongo_regex_ce);
zend_class_implements(php_phongo_regex_ce TSRMLS_CC, 1, php_phongo_regex_interface_ce);
zend_class_implements(php_phongo_regex_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_regex_ce TSRMLS_CC, 1, zend_ce_serializable);
zend_class_implements(php_phongo_regex_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
memcpy(&php_phongo_handler_regex, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_regex.compare_objects = php_phongo_regex_compare_objects;
php_phongo_handler_regex.get_debug_info = php_phongo_regex_get_debug_info;
php_phongo_handler_regex.get_gc = php_phongo_regex_get_gc;
php_phongo_handler_regex.get_properties = php_phongo_regex_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_regex.free_obj = php_phongo_regex_free_object;
php_phongo_handler_regex.offset = XtOffsetOf(php_phongo_regex_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/RegexInterface.c 0000644 0000765 0000024 00000003167 13572250757 017057 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_regex_interface_ce;
/* {{{ MongoDB\BSON\RegexInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_RegexInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_regex_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(RegexInterface, getFlags, ai_RegexInterface_void)
ZEND_ABSTRACT_ME(RegexInterface, getPattern, ai_RegexInterface_void)
ZEND_ABSTRACT_ME(RegexInterface, __toString, ai_RegexInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_regex_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "RegexInterface", php_phongo_regex_interface_me);
php_phongo_regex_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Serializable.c 0000644 0000765 0000024 00000003061 13572250757 016563 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_serializable_ce;
/* {{{ MongoDB\BSON\Serializable function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Serializable_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_serializable_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(Serializable, bsonSerialize, ai_Serializable_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_serializable_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Serializable", php_phongo_serializable_me);
php_phongo_serializable_ce = zend_register_internal_interface(&ce TSRMLS_CC);
zend_class_implements(php_phongo_serializable_ce TSRMLS_CC, 1, php_phongo_type_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Symbol.c 0000644 0000765 0000024 00000024170 13572250757 015426 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_symbol_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_symbol_init(php_phongo_symbol_t* intern, const char* symbol, phongo_zpp_char_len symbol_len TSRMLS_DC) /* {{{ */
{
if (strlen(symbol) != (size_t) symbol_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Symbol cannot contain null bytes");
return false;
}
intern->symbol = estrndup(symbol, symbol_len);
intern->symbol_len = symbol_len;
return true;
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_symbol_init_from_hash(php_phongo_symbol_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* symbol;
if ((symbol = zend_hash_str_find(props, "symbol", sizeof("symbol") - 1)) && Z_TYPE_P(symbol) == IS_STRING) {
return php_phongo_symbol_init(intern, Z_STRVAL_P(symbol), Z_STRLEN_P(symbol) TSRMLS_CC);
}
#else
zval** symbol;
if (zend_hash_find(props, "symbol", sizeof("symbol"), (void**) &symbol) == SUCCESS && Z_TYPE_PP(symbol) == IS_STRING) {
return php_phongo_symbol_init(intern, Z_STRVAL_PP(symbol), Z_STRLEN_PP(symbol) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"symbol\" string field", ZSTR_VAL(php_phongo_symbol_ce->name));
return false;
} /* }}} */
/* {{{ proto string MongoDB\BSON\Symbol::__toString()
Return the Symbol's symbol string. */
static PHP_METHOD(Symbol, __toString)
{
php_phongo_symbol_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_SYMBOL_OBJ_P(getThis());
PHONGO_RETURN_STRINGL(intern->symbol, intern->symbol_len);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Symbol::jsonSerialize()
*/
static PHP_METHOD(Symbol, jsonSerialize)
{
php_phongo_symbol_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_SYMBOL_OBJ_P(getThis());
array_init_size(return_value, 1);
ADD_ASSOC_STRINGL(return_value, "$symbol", intern->symbol, intern->symbol_len);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Symbol::serialize()
*/
static PHP_METHOD(Symbol, serialize)
{
php_phongo_symbol_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
intern = Z_SYMBOL_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 1);
ADD_ASSOC_STRINGL(&retval, "symbol", intern->symbol, intern->symbol_len);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 1);
ADD_ASSOC_STRINGL(retval, "symbol", intern->symbol, intern->symbol_len);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Symbol::unserialize(string $serialized)
*/
static PHP_METHOD(Symbol, unserialize)
{
php_phongo_symbol_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_SYMBOL_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_symbol_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_symbol_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_symbol_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Symbol function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Symbol_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Symbol_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_symbol_me[] = {
/* clang-format off */
/* __set_state intentionally missing */
PHP_ME(Symbol, __toString, ai_Symbol_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Symbol, jsonSerialize, ai_Symbol_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Symbol, serialize, ai_Symbol_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Symbol, unserialize, ai_Symbol_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Symbol_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Symbol object handlers */
static zend_object_handlers php_phongo_handler_symbol;
static void php_phongo_symbol_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_symbol_t* intern = Z_OBJ_SYMBOL(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->symbol) {
efree(intern->symbol);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
phongo_create_object_retval php_phongo_symbol_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_symbol_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_symbol_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_symbol;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_symbol_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_symbol;
return retval;
}
#endif
} /* }}} */
static int php_phongo_symbol_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_symbol_t *intern1, *intern2;
intern1 = Z_SYMBOL_OBJ_P(o1);
intern2 = Z_SYMBOL_OBJ_P(o2);
return strcmp(intern1->symbol, intern2->symbol);
} /* }}} */
static HashTable* php_phongo_symbol_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_SYMBOL_OBJ_P(object)->properties;
} /* }}} */
HashTable* php_phongo_symbol_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_symbol_t* intern;
HashTable* props;
intern = Z_SYMBOL_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->symbol) {
return props;
}
#if PHP_VERSION_ID >= 70000
{
zval symbol;
ZVAL_STRING(&symbol, intern->symbol);
zend_hash_str_update(props, "symbol", sizeof("symbol") - 1, &symbol);
}
#else
{
zval* symbol;
MAKE_STD_ZVAL(symbol);
ZVAL_STRING(symbol, intern->symbol, 1);
zend_hash_update(props, "symbol", sizeof("symbol"), &symbol, sizeof(symbol), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_symbol_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_symbol_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_symbol_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_symbol_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_symbol_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Symbol", php_phongo_symbol_me);
php_phongo_symbol_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_symbol_ce->create_object = php_phongo_symbol_create_object;
PHONGO_CE_FINAL(php_phongo_symbol_ce);
zend_class_implements(php_phongo_symbol_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_symbol_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_symbol_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_symbol, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_symbol.compare_objects = php_phongo_symbol_compare_objects;
php_phongo_handler_symbol.get_debug_info = php_phongo_symbol_get_debug_info;
php_phongo_handler_symbol.get_gc = php_phongo_symbol_get_gc;
php_phongo_handler_symbol.get_properties = php_phongo_symbol_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_symbol.free_obj = php_phongo_symbol_free_object;
php_phongo_handler_symbol.offset = XtOffsetOf(php_phongo_symbol_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Timestamp.c 0000644 0000765 0000024 00000044745 13572250757 016136 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_timestamp_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_timestamp_init(php_phongo_timestamp_t* intern, int64_t increment, int64_t timestamp TSRMLS_DC) /* {{{ */
{
if (increment < 0 || increment > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected increment to be an unsigned 32-bit integer, %" PRId64 " given", increment);
return false;
}
if (timestamp < 0 || timestamp > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected timestamp to be an unsigned 32-bit integer, %" PRId64 " given", timestamp);
return false;
}
intern->increment = (uint32_t) increment;
intern->timestamp = (uint32_t) timestamp;
intern->initialized = true;
return true;
} /* }}} */
/* Initialize the object from numeric strings and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_timestamp_init_from_string(php_phongo_timestamp_t* intern, const char* s_increment, phongo_zpp_char_len s_increment_len, const char* s_timestamp, phongo_zpp_char_len s_timestamp_len TSRMLS_DC) /* {{{ */
{
int64_t increment, timestamp;
char* endptr = NULL;
/* bson_ascii_strtoll() sets errno if conversion fails. If conversion
* succeeds, we still want to ensure that the entire string was parsed. */
increment = bson_ascii_strtoll(s_increment, &endptr, 10);
if (errno || (endptr && endptr != ((const char*) s_increment + s_increment_len))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing \"%s\" as 64-bit integer increment for %s initialization", s_increment, ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
}
timestamp = bson_ascii_strtoll(s_timestamp, &endptr, 10);
if (errno || (endptr && endptr != ((const char*) s_timestamp + s_timestamp_len))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing \"%s\" as 64-bit integer timestamp for %s initialization", s_timestamp, ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
}
return php_phongo_timestamp_init(intern, increment, timestamp TSRMLS_CC);
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_timestamp_init_from_hash(php_phongo_timestamp_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *increment, *timestamp;
if ((increment = zend_hash_str_find(props, "increment", sizeof("increment") - 1)) && Z_TYPE_P(increment) == IS_LONG &&
(timestamp = zend_hash_str_find(props, "timestamp", sizeof("timestamp") - 1)) && Z_TYPE_P(timestamp) == IS_LONG) {
return php_phongo_timestamp_init(intern, Z_LVAL_P(increment), Z_LVAL_P(timestamp) TSRMLS_CC);
}
if ((increment = zend_hash_str_find(props, "increment", sizeof("increment") - 1)) && Z_TYPE_P(increment) == IS_STRING &&
(timestamp = zend_hash_str_find(props, "timestamp", sizeof("timestamp") - 1)) && Z_TYPE_P(timestamp) == IS_STRING) {
return php_phongo_timestamp_init_from_string(intern, Z_STRVAL_P(increment), Z_STRLEN_P(increment), Z_STRVAL_P(timestamp), Z_STRLEN_P(timestamp) TSRMLS_CC);
}
#else
zval **increment, **timestamp;
if (zend_hash_find(props, "increment", sizeof("increment"), (void**) &increment) == SUCCESS && Z_TYPE_PP(increment) == IS_LONG &&
zend_hash_find(props, "timestamp", sizeof("timestamp"), (void**) ×tamp) == SUCCESS && Z_TYPE_PP(timestamp) == IS_LONG) {
return php_phongo_timestamp_init(intern, Z_LVAL_PP(increment), Z_LVAL_PP(timestamp) TSRMLS_CC);
}
if (zend_hash_find(props, "increment", sizeof("increment"), (void**) &increment) == SUCCESS && Z_TYPE_PP(increment) == IS_STRING &&
zend_hash_find(props, "timestamp", sizeof("timestamp"), (void**) ×tamp) == SUCCESS && Z_TYPE_PP(timestamp) == IS_STRING) {
return php_phongo_timestamp_init_from_string(intern, Z_STRVAL_PP(increment), Z_STRLEN_PP(increment), Z_STRVAL_PP(timestamp), Z_STRLEN_PP(timestamp) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"increment\" and \"timestamp\" integer or numeric string fields", ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
} /* }}} */
/* {{{ proto void MongoDB\BSON\Timestamp::__construct(int|string $increment, int|string $timestamp)
Construct a new BSON timestamp type, which consists of a 4-byte increment and
4-byte timestamp. */
static PHP_METHOD(Timestamp, __construct)
{
php_phongo_timestamp_t* intern;
zend_error_handling error_handling;
zval * increment = NULL, *timestamp = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_TIMESTAMP_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &increment, ×tamp) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (Z_TYPE_P(increment) == IS_LONG && Z_TYPE_P(timestamp) == IS_LONG) {
php_phongo_timestamp_init(intern, Z_LVAL_P(increment), Z_LVAL_P(timestamp) TSRMLS_CC);
return;
}
if (Z_TYPE_P(increment) == IS_LONG) {
convert_to_string(increment);
}
if (Z_TYPE_P(increment) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected increment to be an unsigned 32-bit integer or string, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(increment));
return;
}
if (Z_TYPE_P(timestamp) == IS_LONG) {
convert_to_string(timestamp);
}
if (Z_TYPE_P(timestamp) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected timestamp to be an unsigned 32-bit integer or string, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(timestamp));
return;
}
php_phongo_timestamp_init_from_string(intern, Z_STRVAL_P(increment), Z_STRLEN_P(increment), Z_STRVAL_P(timestamp), Z_STRLEN_P(timestamp) TSRMLS_CC);
} /* }}} */
/* {{{ proto integer MongoDB\BSON\Timestamp::getIncrement()
*/
static PHP_METHOD(Timestamp, getIncrement)
{
php_phongo_timestamp_t* intern;
intern = Z_TIMESTAMP_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_LONG(intern->increment);
} /* }}} */
/* {{{ proto integer MongoDB\BSON\Timestamp::getTimestamp()
*/
static PHP_METHOD(Timestamp, getTimestamp)
{
php_phongo_timestamp_t* intern;
intern = Z_TIMESTAMP_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_LONG(intern->timestamp);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Timestamp::__set_state(array $properties)
*/
static PHP_METHOD(Timestamp, __set_state)
{
php_phongo_timestamp_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_timestamp_ce);
intern = Z_TIMESTAMP_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_timestamp_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Timestamp::__toString()
Returns a string in the form: [increment:timestamp] */
static PHP_METHOD(Timestamp, __toString)
{
php_phongo_timestamp_t* intern;
char* retval;
int retval_len;
intern = Z_TIMESTAMP_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
retval_len = spprintf(&retval, 0, "[%" PRIu32 ":%" PRIu32 "]", intern->increment, intern->timestamp);
PHONGO_RETVAL_STRINGL(retval, retval_len);
efree(retval);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Timestamp::jsonSerialize()
*/
static PHP_METHOD(Timestamp, jsonSerialize)
{
php_phongo_timestamp_t* intern;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_TIMESTAMP_OBJ_P(getThis());
array_init_size(return_value, 1);
#if PHP_VERSION_ID >= 70000
{
zval ts;
array_init_size(&ts, 2);
ADD_ASSOC_LONG_EX(&ts, "t", intern->timestamp);
ADD_ASSOC_LONG_EX(&ts, "i", intern->increment);
ADD_ASSOC_ZVAL_EX(return_value, "$timestamp", &ts);
}
#else
{
zval* ts;
MAKE_STD_ZVAL(ts);
array_init_size(ts, 2);
ADD_ASSOC_LONG_EX(ts, "t", intern->timestamp);
ADD_ASSOC_LONG_EX(ts, "i", intern->increment);
ADD_ASSOC_ZVAL_EX(return_value, "$timestamp", ts);
}
#endif
} /* }}} */
/* {{{ proto string MongoDB\BSON\Timestamp::serialize()
*/
static PHP_METHOD(Timestamp, serialize)
{
php_phongo_timestamp_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
char s_increment[12];
char s_timestamp[12];
int s_increment_len;
int s_timestamp_len;
intern = Z_TIMESTAMP_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
s_increment_len = snprintf(s_increment, sizeof(s_increment), "%" PRIu32, intern->increment);
s_timestamp_len = snprintf(s_timestamp, sizeof(s_timestamp), "%" PRIu32, intern->timestamp);
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "increment", s_increment, s_increment_len);
ADD_ASSOC_STRINGL(&retval, "timestamp", s_timestamp, s_timestamp_len);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "increment", s_increment, s_increment_len);
ADD_ASSOC_STRINGL(retval, "timestamp", s_timestamp, s_timestamp_len);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\Timestamp::unserialize(string $serialized)
*/
static PHP_METHOD(Timestamp, unserialize)
{
php_phongo_timestamp_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_TIMESTAMP_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_timestamp_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_timestamp_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_timestamp_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\Timestamp function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Timestamp___construct, 0, 0, 2)
ZEND_ARG_INFO(0, increment)
ZEND_ARG_INFO(0, timestamp)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Timestamp___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Timestamp_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Timestamp_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_timestamp_me[] = {
/* clang-format off */
PHP_ME(Timestamp, __construct, ai_Timestamp___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, __set_state, ai_Timestamp___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(Timestamp, __toString, ai_Timestamp_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, jsonSerialize, ai_Timestamp_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, serialize, ai_Timestamp_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, unserialize, ai_Timestamp_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, getIncrement, ai_Timestamp_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Timestamp, getTimestamp, ai_Timestamp_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Timestamp object handlers */
static zend_object_handlers php_phongo_handler_timestamp;
static void php_phongo_timestamp_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_timestamp_t* intern = Z_OBJ_TIMESTAMP(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_timestamp_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_timestamp_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_timestamp_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_timestamp;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_timestamp_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_timestamp;
return retval;
}
#endif
} /* }}} */
static int php_phongo_timestamp_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_timestamp_t *intern1, *intern2;
intern1 = Z_TIMESTAMP_OBJ_P(o1);
intern2 = Z_TIMESTAMP_OBJ_P(o2);
/* MongoDB compares the timestamp before the increment. */
if (intern1->timestamp != intern2->timestamp) {
return intern1->timestamp < intern2->timestamp ? -1 : 1;
}
if (intern1->increment != intern2->increment) {
return intern1->increment < intern2->increment ? -1 : 1;
}
return 0;
} /* }}} */
static HashTable* php_phongo_timestamp_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_TIMESTAMP_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_timestamp_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_timestamp_t* intern;
HashTable* props;
char s_increment[24];
char s_timestamp[24];
int s_increment_len;
int s_timestamp_len;
intern = Z_TIMESTAMP_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->initialized) {
return props;
}
s_increment_len = snprintf(s_increment, sizeof(s_increment), "%" PRIu32, intern->increment);
s_timestamp_len = snprintf(s_timestamp, sizeof(s_timestamp), "%" PRIu32, intern->timestamp);
#if PHP_VERSION_ID >= 70000
{
zval increment, timestamp;
ZVAL_STRINGL(&increment, s_increment, s_increment_len);
zend_hash_str_update(props, "increment", sizeof("increment") - 1, &increment);
ZVAL_STRINGL(×tamp, s_timestamp, s_timestamp_len);
zend_hash_str_update(props, "timestamp", sizeof("timestamp") - 1, ×tamp);
}
#else
{
zval *increment, *timestamp;
MAKE_STD_ZVAL(increment);
ZVAL_STRINGL(increment, s_increment, s_increment_len, 1);
zend_hash_update(props, "increment", sizeof("increment"), &increment, sizeof(increment), NULL);
MAKE_STD_ZVAL(timestamp);
ZVAL_STRINGL(timestamp, s_timestamp, s_timestamp_len, 1);
zend_hash_update(props, "timestamp", sizeof("timestamp"), ×tamp, sizeof(timestamp), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_timestamp_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_timestamp_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_timestamp_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_timestamp_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_timestamp_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Timestamp", php_phongo_timestamp_me);
php_phongo_timestamp_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_timestamp_ce->create_object = php_phongo_timestamp_create_object;
PHONGO_CE_FINAL(php_phongo_timestamp_ce);
zend_class_implements(php_phongo_timestamp_ce TSRMLS_CC, 1, php_phongo_timestamp_interface_ce);
zend_class_implements(php_phongo_timestamp_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_timestamp_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_timestamp_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_timestamp, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_timestamp.compare_objects = php_phongo_timestamp_compare_objects;
php_phongo_handler_timestamp.get_debug_info = php_phongo_timestamp_get_debug_info;
php_phongo_handler_timestamp.get_gc = php_phongo_timestamp_get_gc;
php_phongo_handler_timestamp.get_properties = php_phongo_timestamp_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_timestamp.free_obj = php_phongo_timestamp_free_object;
php_phongo_handler_timestamp.offset = XtOffsetOf(php_phongo_timestamp_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/TimestampInterface.c 0000644 0000765 0000024 00000003265 13572250757 017747 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_timestamp_interface_ce;
/* {{{ MongoDB\BSON\TimestampInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_TimestampInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_timestamp_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(TimestampInterface, getIncrement, ai_TimestampInterface_void)
ZEND_ABSTRACT_ME(TimestampInterface, getTimestamp, ai_TimestampInterface_void)
ZEND_ABSTRACT_ME(TimestampInterface, __toString, ai_TimestampInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_timestamp_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "TimestampInterface", php_phongo_timestamp_interface_me);
php_phongo_timestamp_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Type.c 0000644 0000765 0000024 00000002345 13572250757 015102 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_type_ce;
/* {{{ MongoDB\BSON\Type function entries */
static zend_function_entry php_phongo_type_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_type_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Type", php_phongo_type_me);
php_phongo_type_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/UTCDateTime.c 0000644 0000765 0000024 00000044333 13572250757 016234 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef PHP_WIN32
#include "win32/time.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_utcdatetime_ce;
/* Initialize the object and return whether it was successful. */
static bool php_phongo_utcdatetime_init(php_phongo_utcdatetime_t* intern, int64_t milliseconds) /* {{{ */
{
intern->milliseconds = milliseconds;
intern->initialized = true;
return true;
} /* }}} */
/* Initialize the object from a numeric string and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_utcdatetime_init_from_string(php_phongo_utcdatetime_t* intern, const char* s_milliseconds, phongo_zpp_char_len s_milliseconds_len TSRMLS_DC) /* {{{ */
{
int64_t milliseconds;
char* endptr = NULL;
/* bson_ascii_strtoll() sets errno if conversion fails. If conversion
* succeeds, we still want to ensure that the entire string was parsed. */
milliseconds = bson_ascii_strtoll(s_milliseconds, &endptr, 10);
if (errno || (endptr && endptr != ((const char*) s_milliseconds + s_milliseconds_len))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error parsing \"%s\" as 64-bit integer for %s initialization", s_milliseconds, ZSTR_VAL(php_phongo_utcdatetime_ce->name));
return false;
}
return php_phongo_utcdatetime_init(intern, milliseconds);
} /* }}} */
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_utcdatetime_init_from_hash(php_phongo_utcdatetime_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* milliseconds;
if ((milliseconds = zend_hash_str_find(props, "milliseconds", sizeof("milliseconds") - 1)) && Z_TYPE_P(milliseconds) == IS_LONG) {
return php_phongo_utcdatetime_init(intern, Z_LVAL_P(milliseconds));
}
if ((milliseconds = zend_hash_str_find(props, "milliseconds", sizeof("milliseconds") - 1)) && Z_TYPE_P(milliseconds) == IS_STRING) {
return php_phongo_utcdatetime_init_from_string(intern, Z_STRVAL_P(milliseconds), Z_STRLEN_P(milliseconds) TSRMLS_CC);
}
#else
zval** milliseconds;
if (zend_hash_find(props, "milliseconds", sizeof("milliseconds"), (void**) &milliseconds) == SUCCESS && Z_TYPE_PP(milliseconds) == IS_LONG) {
return php_phongo_utcdatetime_init(intern, Z_LVAL_PP(milliseconds));
}
if (zend_hash_find(props, "milliseconds", sizeof("milliseconds"), (void**) &milliseconds) == SUCCESS && Z_TYPE_PP(milliseconds) == IS_STRING) {
return php_phongo_utcdatetime_init_from_string(intern, Z_STRVAL_PP(milliseconds), Z_STRLEN_PP(milliseconds) TSRMLS_CC);
}
#endif
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"milliseconds\" integer or numeric string field", ZSTR_VAL(php_phongo_utcdatetime_ce->name));
return false;
} /* }}} */
/* Initialize the object from the current time and return whether it was
* successful. */
static bool php_phongo_utcdatetime_init_from_current_time(php_phongo_utcdatetime_t* intern) /* {{{ */
{
int64_t sec, usec;
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
sec = cur_time.tv_sec;
usec = cur_time.tv_usec;
intern->milliseconds = (sec * 1000) + (usec / 1000);
intern->initialized = true;
return true;
} /* }}} */
/* Initialize the object from a DateTime object and return whether it was
* successful. */
static bool php_phongo_utcdatetime_init_from_date(php_phongo_utcdatetime_t* intern, php_date_obj* datetime_obj) /* {{{ */
{
int64_t sec, usec;
/* The following assignments use the same logic as date_format() in php_date.c */
sec = datetime_obj->time->sse;
#if PHP_VERSION_ID >= 70200
usec = (int64_t) floor(datetime_obj->time->us);
#else
usec = (int64_t) floor(datetime_obj->time->f * 1000000 + 0.5);
#endif
intern->milliseconds = (sec * 1000) + (usec / 1000);
intern->initialized = true;
return true;
} /* }}} */
/* {{{ proto void MongoDB\BSON\UTCDateTime::__construct([int|float|string|DateTimeInterface $milliseconds = null])
Construct a new BSON UTCDateTime type from either the current time,
milliseconds since the epoch, or a DateTimeInterface object. Defaults to the
current time. */
static PHP_METHOD(UTCDateTime, __construct)
{
php_phongo_utcdatetime_t* intern;
zend_error_handling error_handling;
zval* milliseconds = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_UTCDATETIME_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|z!", &milliseconds) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (milliseconds == NULL) {
php_phongo_utcdatetime_init_from_current_time(intern);
return;
}
if (Z_TYPE_P(milliseconds) == IS_OBJECT) {
if (instanceof_function(Z_OBJCE_P(milliseconds), php_date_get_date_ce() TSRMLS_CC) ||
(php_phongo_date_immutable_ce && instanceof_function(Z_OBJCE_P(milliseconds), php_phongo_date_immutable_ce TSRMLS_CC))) {
php_phongo_utcdatetime_init_from_date(intern, Z_PHPDATE_P(milliseconds));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected instance of DateTimeInterface, %s given", ZSTR_VAL(Z_OBJCE_P(milliseconds)->name));
}
return;
}
if (Z_TYPE_P(milliseconds) == IS_LONG) {
php_phongo_utcdatetime_init(intern, Z_LVAL_P(milliseconds));
return;
}
if (Z_TYPE_P(milliseconds) == IS_DOUBLE) {
char tmp[24];
int tmp_len;
tmp_len = snprintf(tmp, sizeof(tmp), "%.0f", Z_DVAL_P(milliseconds) > 0 ? floor(Z_DVAL_P(milliseconds)) : ceil(Z_DVAL_P(milliseconds)));
php_phongo_utcdatetime_init_from_string(intern, tmp, tmp_len TSRMLS_CC);
return;
}
if (Z_TYPE_P(milliseconds) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected integer or string, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(milliseconds));
return;
}
php_phongo_utcdatetime_init_from_string(intern, Z_STRVAL_P(milliseconds), Z_STRLEN_P(milliseconds) TSRMLS_CC);
} /* }}} */
/* {{{ proto void MongoDB\BSON\UTCDateTime::__set_state(array $properties)
*/
static PHP_METHOD(UTCDateTime, __set_state)
{
php_phongo_utcdatetime_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_utcdatetime_ce);
intern = Z_UTCDATETIME_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_utcdatetime_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string MongoDB\BSON\UTCDateTime::__toString()
Returns the UTCDateTime's milliseconds as a string */
static PHP_METHOD(UTCDateTime, __toString)
{
php_phongo_utcdatetime_t* intern;
char s_milliseconds[24];
int s_milliseconds_len;
intern = Z_UTCDATETIME_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
s_milliseconds_len = snprintf(s_milliseconds, sizeof(s_milliseconds), "%" PRId64, intern->milliseconds);
PHONGO_RETVAL_STRINGL(s_milliseconds, s_milliseconds_len);
} /* }}} */
/* {{{ proto DateTime MongoDB\BSON\UTCDateTime::toDateTime()
Returns a DateTime object representing this UTCDateTime */
static PHP_METHOD(UTCDateTime, toDateTime)
{
php_phongo_utcdatetime_t* intern;
php_date_obj* datetime_obj;
char* sec;
size_t sec_len;
intern = Z_UTCDATETIME_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
object_init_ex(return_value, php_date_get_date_ce());
datetime_obj = Z_PHPDATE_P(return_value);
sec_len = spprintf(&sec, 0, "@%" PRId64, intern->milliseconds / 1000);
php_date_initialize(datetime_obj, sec, sec_len, NULL, NULL, 0 TSRMLS_CC);
efree(sec);
#if PHP_VERSION_ID >= 70200
datetime_obj->time->us = (intern->milliseconds % 1000) * 1000;
#else
datetime_obj->time->f = (double) (intern->milliseconds % 1000) / 1000;
#endif
}
/* }}} */
/* {{{ proto array MongoDB\BSON\UTCDateTime::jsonSerialize()
*/
static PHP_METHOD(UTCDateTime, jsonSerialize)
{
php_phongo_utcdatetime_t* intern;
char s_milliseconds[24];
int s_milliseconds_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern = Z_UTCDATETIME_OBJ_P(getThis());
s_milliseconds_len = snprintf(s_milliseconds, sizeof(s_milliseconds), "%" PRId64, intern->milliseconds);
array_init_size(return_value, 1);
#if PHP_VERSION_ID >= 70000
{
zval udt;
array_init_size(&udt, 1);
ADD_ASSOC_STRINGL(&udt, "$numberLong", s_milliseconds, s_milliseconds_len);
ADD_ASSOC_ZVAL_EX(return_value, "$date", &udt);
}
#else
{
zval* udt;
MAKE_STD_ZVAL(udt);
array_init_size(udt, 1);
ADD_ASSOC_STRINGL(udt, "$numberLong", s_milliseconds, s_milliseconds_len);
ADD_ASSOC_ZVAL_EX(return_value, "$date", udt);
}
#endif
} /* }}} */
/* {{{ proto string MongoDB\BSON\UTCDateTime::serialize()
*/
static PHP_METHOD(UTCDateTime, serialize)
{
php_phongo_utcdatetime_t* intern;
ZVAL_RETVAL_TYPE retval;
php_serialize_data_t var_hash;
smart_str buf = { 0 };
char s_milliseconds[24];
int s_milliseconds_len;
intern = Z_UTCDATETIME_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
s_milliseconds_len = snprintf(s_milliseconds, sizeof(s_milliseconds), "%" PRId64, intern->milliseconds);
#if PHP_VERSION_ID >= 70000
array_init_size(&retval, 2);
ADD_ASSOC_STRINGL(&retval, "milliseconds", s_milliseconds, s_milliseconds_len);
#else
ALLOC_INIT_ZVAL(retval);
array_init_size(retval, 2);
ADD_ASSOC_STRINGL(retval, "milliseconds", s_milliseconds, s_milliseconds_len);
#endif
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, &retval, &var_hash TSRMLS_CC);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
PHONGO_RETVAL_SMART_STR(buf);
smart_str_free(&buf);
zval_ptr_dtor(&retval);
} /* }}} */
/* {{{ proto void MongoDB\BSON\UTCDateTime::unserialize(string $serialized)
*/
static PHP_METHOD(UTCDateTime, unserialize)
{
php_phongo_utcdatetime_t* intern;
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
#if PHP_VERSION_ID >= 70000
zval props;
#else
zval* props;
#endif
php_unserialize_data_t var_hash;
intern = Z_UTCDATETIME_OBJ_P(getThis());
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
#if PHP_VERSION_ID < 70000
ALLOC_INIT_ZVAL(props);
#endif
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&props, (const unsigned char**) &serialized, (unsigned char*) serialized + serialized_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&props);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s unserialization failed", ZSTR_VAL(php_phongo_utcdatetime_ce->name));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
#if PHP_VERSION_ID >= 70000
php_phongo_utcdatetime_init_from_hash(intern, HASH_OF(&props) TSRMLS_CC);
#else
php_phongo_utcdatetime_init_from_hash(intern, HASH_OF(props) TSRMLS_CC);
#endif
zval_ptr_dtor(&props);
} /* }}} */
/* {{{ MongoDB\BSON\UTCDateTime function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_UTCDateTime___construct, 0, 0, 0)
ZEND_ARG_INFO(0, milliseconds)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_UTCDateTime___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_UTCDateTime_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_UTCDateTime_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_utcdatetime_me[] = {
/* clang-format off */
PHP_ME(UTCDateTime, __construct, ai_UTCDateTime___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(UTCDateTime, __set_state, ai_UTCDateTime___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(UTCDateTime, __toString, ai_UTCDateTime_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(UTCDateTime, jsonSerialize, ai_UTCDateTime_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(UTCDateTime, serialize, ai_UTCDateTime_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(UTCDateTime, unserialize, ai_UTCDateTime_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(UTCDateTime, toDateTime, ai_UTCDateTime_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\UTCDateTime object handlers */
static zend_object_handlers php_phongo_handler_utcdatetime;
static void php_phongo_utcdatetime_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_utcdatetime_t* intern = Z_OBJ_UTCDATETIME(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_utcdatetime_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_utcdatetime_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_utcdatetime_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_utcdatetime;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_utcdatetime_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_utcdatetime;
return retval;
}
#endif
} /* }}} */
static int php_phongo_utcdatetime_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_utcdatetime_t *intern1, *intern2;
intern1 = Z_UTCDATETIME_OBJ_P(o1);
intern2 = Z_UTCDATETIME_OBJ_P(o2);
if (intern1->milliseconds != intern2->milliseconds) {
return intern1->milliseconds < intern2->milliseconds ? -1 : 1;
}
return 0;
} /* }}} */
static HashTable* php_phongo_utcdatetime_get_gc(zval* object, phongo_get_gc_table table, int* n TSRMLS_DC) /* {{{ */
{
*table = NULL;
*n = 0;
return Z_UTCDATETIME_OBJ_P(object)->properties;
} /* }}} */
static HashTable* php_phongo_utcdatetime_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_utcdatetime_t* intern;
HashTable* props;
char s_milliseconds[24];
int s_milliseconds_len;
intern = Z_UTCDATETIME_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->initialized) {
return props;
}
s_milliseconds_len = snprintf(s_milliseconds, sizeof(s_milliseconds), "%" PRId64, intern->milliseconds);
#if PHP_VERSION_ID >= 70000
{
zval milliseconds;
ZVAL_STRINGL(&milliseconds, s_milliseconds, s_milliseconds_len);
zend_hash_str_update(props, "milliseconds", sizeof("milliseconds") - 1, &milliseconds);
}
#else
{
zval* milliseconds;
MAKE_STD_ZVAL(milliseconds);
ZVAL_STRINGL(milliseconds, s_milliseconds, s_milliseconds_len, 1);
zend_hash_update(props, "milliseconds", sizeof("milliseconds"), &milliseconds, sizeof(milliseconds), NULL);
}
#endif
return props;
} /* }}} */
static HashTable* php_phongo_utcdatetime_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_utcdatetime_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_utcdatetime_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_utcdatetime_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_utcdatetime_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "UTCDateTime", php_phongo_utcdatetime_me);
php_phongo_utcdatetime_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_utcdatetime_ce->create_object = php_phongo_utcdatetime_create_object;
PHONGO_CE_FINAL(php_phongo_utcdatetime_ce);
zend_class_implements(php_phongo_utcdatetime_ce TSRMLS_CC, 1, php_phongo_utcdatetime_interface_ce);
zend_class_implements(php_phongo_utcdatetime_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_utcdatetime_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_utcdatetime_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_utcdatetime, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_utcdatetime.compare_objects = php_phongo_utcdatetime_compare_objects;
php_phongo_handler_utcdatetime.get_debug_info = php_phongo_utcdatetime_get_debug_info;
php_phongo_handler_utcdatetime.get_gc = php_phongo_utcdatetime_get_gc;
php_phongo_handler_utcdatetime.get_properties = php_phongo_utcdatetime_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_utcdatetime.free_obj = php_phongo_utcdatetime_free_object;
php_phongo_handler_utcdatetime.offset = XtOffsetOf(php_phongo_utcdatetime_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/UTCDateTimeInterface.c 0000644 0000765 0000024 00000003173 13572250757 020052 0 ustar alcaeus staff /*
* Copyright 2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_utcdatetime_interface_ce;
/* {{{ MongoDB\BSON\UTCDateTimeInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_UTCDateTimeInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_utcdatetime_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(UTCDateTimeInterface, toDateTime, ai_UTCDateTimeInterface_void)
ZEND_ABSTRACT_ME(UTCDateTimeInterface, __toString, ai_UTCDateTimeInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_utcdatetime_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "UTCDateTimeInterface", php_phongo_utcdatetime_interface_me);
php_phongo_utcdatetime_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Undefined.c 0000644 0000765 0000024 00000012132 13572250757 016055 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#if PHP_VERSION_ID >= 70000
#include
#else
#include
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_undefined_ce;
/* {{{ proto string MongoDB\BSON\Undefined::__toString()
Return the empty string. */
static PHP_METHOD(Undefined, __toString)
{
PHONGO_RETURN_STRINGL("", 0);
} /* }}} */
/* {{{ proto array MongoDB\BSON\Undefined::jsonSerialize()
*/
static PHP_METHOD(Undefined, jsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init_size(return_value, 1);
ADD_ASSOC_BOOL_EX(return_value, "$undefined", 1);
} /* }}} */
/* {{{ proto string MongoDB\BSON\Undefined::serialize()
*/
static PHP_METHOD(Undefined, serialize)
{
PHONGO_RETURN_STRING("");
} /* }}} */
/* {{{ proto void MongoDB\BSON\Undefined::unserialize(string $serialized)
*/
static PHP_METHOD(Undefined, unserialize)
{
zend_error_handling error_handling;
char* serialized;
phongo_zpp_char_len serialized_len;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &serialized, &serialized_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ MongoDB\BSON\Undefined function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Undefined_unserialize, 0, 0, 1)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Undefined_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_undefined_me[] = {
/* clang-format off */
/* __set_state intentionally missing */
PHP_ME(Undefined, __toString, ai_Undefined_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Undefined, jsonSerialize, ai_Undefined_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Undefined, serialize, ai_Undefined_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Undefined, unserialize, ai_Undefined_unserialize, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Undefined_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\BSON\Undefined object handlers */
static zend_object_handlers php_phongo_handler_undefined;
static void php_phongo_undefined_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_undefined_t* intern = Z_OBJ_UNDEFINED(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_undefined_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_undefined_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_undefined_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_undefined;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_undefined_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_undefined;
return retval;
}
#endif
} /* }}} */
/* }}} */
void php_phongo_undefined_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Undefined", php_phongo_undefined_me);
php_phongo_undefined_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_undefined_ce->create_object = php_phongo_undefined_create_object;
PHONGO_CE_FINAL(php_phongo_undefined_ce);
zend_class_implements(php_phongo_undefined_ce TSRMLS_CC, 1, php_phongo_json_serializable_ce);
zend_class_implements(php_phongo_undefined_ce TSRMLS_CC, 1, php_phongo_type_ce);
zend_class_implements(php_phongo_undefined_ce TSRMLS_CC, 1, zend_ce_serializable);
memcpy(&php_phongo_handler_undefined, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
#if PHP_VERSION_ID >= 70000
php_phongo_handler_undefined.free_obj = php_phongo_undefined_free_object;
php_phongo_handler_undefined.offset = XtOffsetOf(php_phongo_undefined_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/Unserializable.c 0000644 0000765 0000024 00000003051 13572250757 017125 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_unserializable_ce;
/* {{{ MongoDB\BSON\Unserializable function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Unserializable_bsonUnserialize, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, data, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_unserializable_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(Unserializable, bsonUnserialize, ai_Unserializable_bsonUnserialize)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_unserializable_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Unserializable", php_phongo_unserializable_me);
php_phongo_unserializable_ce = zend_register_internal_interface(&ce TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/functions.c 0000644 0000765 0000024 00000012465 13572250757 016175 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
typedef enum {
PHONGO_JSON_MODE_LEGACY,
PHONGO_JSON_MODE_CANONICAL,
PHONGO_JSON_MODE_RELAXED,
} php_phongo_json_mode_t;
/* {{{ proto string MongoDB\BSON\fromPHP(array|object $value)
Returns the BSON representation of a PHP value */
PHP_FUNCTION(MongoDB_BSON_fromPHP)
{
zval* data;
bson_t* bson;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A", &data) == FAILURE) {
return;
}
bson = bson_new();
php_phongo_zval_to_bson(data, PHONGO_BSON_NONE, bson, NULL TSRMLS_CC);
PHONGO_RETVAL_STRINGL((const char*) bson_get_data(bson), bson->len);
bson_destroy(bson);
} /* }}} */
/* {{{ proto array|object MongoDB\BSON\toPHP(string $bson [, array $typemap = array()])
Returns the PHP representation of a BSON value, optionally converting it into a custom class */
PHP_FUNCTION(MongoDB_BSON_toPHP)
{
char* data;
phongo_zpp_char_len data_len;
zval* typemap = NULL;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|a!", &data, &data_len, &typemap) == FAILURE) {
return;
}
if (!php_phongo_bson_typemap_to_state(typemap, &state.map TSRMLS_CC)) {
return;
}
if (!php_phongo_bson_to_zval_ex((const unsigned char*) data, data_len, &state)) {
zval_ptr_dtor(&state.zchild);
php_phongo_bson_typemap_dtor(&state.map);
RETURN_NULL();
}
php_phongo_bson_typemap_dtor(&state.map);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto string MongoDB\BSON\fromJSON(string $json)
Returns the BSON representation of a JSON value */
PHP_FUNCTION(MongoDB_BSON_fromJSON)
{
char* json;
phongo_zpp_char_len json_len;
bson_t bson = BSON_INITIALIZER;
bson_error_t error = { 0 };
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &json, &json_len) == FAILURE) {
return;
}
if (bson_init_from_json(&bson, (const char*) json, json_len, &error)) {
PHONGO_RETVAL_STRINGL((const char*) bson_get_data(&bson), bson.len);
bson_destroy(&bson);
} else {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "%s", error.domain == BSON_ERROR_JSON ? error.message : "Error parsing JSON");
}
} /* }}} */
static void phongo_bson_to_json(INTERNAL_FUNCTION_PARAMETERS, php_phongo_json_mode_t mode)
{
char* data;
phongo_zpp_char_len data_len;
const bson_t* bson;
bool eof = false;
bson_reader_t* reader;
char* json = NULL;
size_t json_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) == FAILURE) {
return;
}
reader = bson_reader_new_from_data((const unsigned char*) data, data_len);
bson = bson_reader_read(reader, NULL);
if (!bson) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "Could not read document from BSON reader");
bson_reader_destroy(reader);
return;
}
if (mode == PHONGO_JSON_MODE_LEGACY) {
json = bson_as_json(bson, &json_len);
} else if (mode == PHONGO_JSON_MODE_CANONICAL) {
json = bson_as_canonical_extended_json(bson, &json_len);
} else if (mode == PHONGO_JSON_MODE_RELAXED) {
json = bson_as_relaxed_extended_json(bson, &json_len);
}
if (!json) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "Could not convert BSON document to a JSON string");
bson_reader_destroy(reader);
return;
}
PHONGO_RETVAL_STRINGL(json, json_len);
bson_free(json);
if (bson_reader_read(reader, &eof) || !eof) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "Reading document did not exhaust input buffer");
}
bson_reader_destroy(reader);
} /* }}} */
/* {{{ proto string MongoDB\BSON\toJSON(string $bson)
Returns the legacy extended JSON representation of a BSON value */
PHP_FUNCTION(MongoDB_BSON_toJSON)
{
phongo_bson_to_json(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHONGO_JSON_MODE_LEGACY);
} /* }}} */
/* {{{ proto string MongoDB\BSON\toCanonicalExtendedJSON(string $bson)
Returns the canonical extended JSON representation of a BSON value */
PHP_FUNCTION(MongoDB_BSON_toCanonicalExtendedJSON)
{
phongo_bson_to_json(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHONGO_JSON_MODE_CANONICAL);
} /* }}} */
/* {{{ proto string MongoDB\BSON\toRelaxedExtendedJSON(string $bson)
Returns the relaxed extended JSON representation of a BSON value */
PHP_FUNCTION(MongoDB_BSON_toRelaxedExtendedJSON)
{
phongo_bson_to_json(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHONGO_JSON_MODE_RELAXED);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/BSON/functions.h 0000644 0000765 0000024 00000002120 13572250757 016165 0 ustar alcaeus staff /*
* Copyright 2014-2017 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.
*/
#ifndef PHONGO_BSON_FUNCTIONS_H
#define PHONGO_BSON_FUNCTIONS_H
#include
PHP_FUNCTION(MongoDB_BSON_fromPHP);
PHP_FUNCTION(MongoDB_BSON_toPHP);
PHP_FUNCTION(MongoDB_BSON_fromJSON);
PHP_FUNCTION(MongoDB_BSON_toJSON);
PHP_FUNCTION(MongoDB_BSON_toCanonicalExtendedJSON);
PHP_FUNCTION(MongoDB_BSON_toRelaxedExtendedJSON);
#endif /* PHONGO_BSON_FUNCTIONS_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/AuthenticationException.c 0000644 0000765 0000024 00000003106 13572250757 023475 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_authenticationexception_ce;
/* {{{ MongoDB\Driver\Exception\AuthenticationException function entries */
static zend_function_entry php_phongo_authenticationexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_authenticationexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "AuthenticationException", php_phongo_authenticationexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_authenticationexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce);
#else
php_phongo_authenticationexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce, NULL TSRMLS_CC);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/BulkWriteException.c 0000644 0000765 0000024 00000003024 13572250757 022425 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_bulkwriteexception_ce;
/* {{{ MongoDB\Driver\Exception\BulkWriteException function entries */
static zend_function_entry php_phongo_bulkwriteexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_bulkwriteexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "BulkWriteException", php_phongo_bulkwriteexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_bulkwriteexception_ce = zend_register_internal_class_ex(&ce, php_phongo_writeexception_ce);
#else
php_phongo_bulkwriteexception_ce = zend_register_internal_class_ex(&ce, php_phongo_writeexception_ce, NULL TSRMLS_CC);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/CommandException.c 0000644 0000765 0000024 00000005003 13572250757 022072 0 ustar alcaeus staff /*
* Copyright 2018 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_commandexception_ce;
/* {{{ proto document MongoDB\Driver\Exception\CommandException::getResultDocument()
Returns the result document from the failed command. */
static PHP_METHOD(CommandException, getResultDocument)
{
zval* resultdocument;
#if PHP_VERSION_ID >= 70000
zval rv;
#endif
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
resultdocument = zend_read_property(php_phongo_commandexception_ce, getThis(), ZEND_STRL("resultDocument"), 0, &rv TSRMLS_CC);
#else
resultdocument = zend_read_property(php_phongo_commandexception_ce, getThis(), ZEND_STRL("resultDocument"), 0 TSRMLS_CC);
#endif
RETURN_ZVAL(resultdocument, 1, 0);
} /* }}} */
/* {{{ MongoDB\Driver\Exception\CommandException function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CommandException_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_commandexception_me[] = {
/* clang-format off */
PHP_ME(CommandException, getResultDocument, ai_CommandException_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_commandexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "CommandException", php_phongo_commandexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_commandexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce);
#else
php_phongo_commandexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce, NULL TSRMLS_CC);
#endif
zend_declare_property_null(php_phongo_commandexception_ce, ZEND_STRL("resultDocument"), ZEND_ACC_PROTECTED TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/ConnectionException.c 0000644 0000765 0000024 00000003040 13572250757 022612 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_connectionexception_ce;
/* {{{ MongoDB\Driver\Exception\ConnectionException function entries */
static zend_function_entry php_phongo_connectionexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_connectionexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ConnectionException", php_phongo_connectionexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_connectionexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce);
#else
php_phongo_connectionexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce, NULL TSRMLS_CC);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/ConnectionTimeoutException.c 0000644 0000765 0000024 00000003232 13572250757 024164 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_connectiontimeoutexception_ce;
/* {{{ MongoDB\Driver\Exception\ConnectionTimeoutException function entries */
static zend_function_entry php_phongo_connectiontimeoutexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_connectiontimeoutexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ConnectionTimeoutException", php_phongo_connectiontimeoutexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_connectiontimeoutexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce);
#else
php_phongo_connectiontimeoutexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce, NULL TSRMLS_CC);
#endif
PHONGO_CE_FINAL(php_phongo_connectiontimeoutexception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/Exception.c 0000644 0000765 0000024 00000002663 13572250757 020604 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_exception_ce;
/* {{{ MongoDB\Driver\Exception\Exception function entries */
static zend_function_entry php_phongo_exception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_exception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "Exception", php_phongo_exception_me);
php_phongo_exception_ce = zend_register_internal_interface(&ce TSRMLS_CC);
#if PHP_VERSION_ID >= 70000
zend_class_implements(php_phongo_exception_ce TSRMLS_CC, 1, zend_ce_throwable);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/ExecutionTimeoutException.c 0000644 0000765 0000024 00000003211 13572250757 024025 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_executiontimeoutexception_ce;
/* {{{ MongoDB\Driver\Exception\ExecutionTimeoutException function entries */
static zend_function_entry php_phongo_executiontimeoutexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_executiontimeoutexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ExecutionTimeoutException", php_phongo_executiontimeoutexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_executiontimeoutexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce);
#else
php_phongo_executiontimeoutexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce, NULL TSRMLS_CC);
#endif
PHONGO_CE_FINAL(php_phongo_executiontimeoutexception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/InvalidArgumentException.c 0000644 0000765 0000024 00000003324 13572250757 023611 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_invalidargumentexception_ce;
/* {{{ MongoDB\Driver\Exception\InvalidArgumentException function entries */
static zend_function_entry php_phongo_invalidargumentexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_invalidargumentexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "InvalidArgumentException", php_phongo_invalidargumentexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_invalidargumentexception_ce = zend_register_internal_class_ex(&ce, spl_ce_InvalidArgumentException);
#else
php_phongo_invalidargumentexception_ce = zend_register_internal_class_ex(&ce, spl_ce_InvalidArgumentException, NULL TSRMLS_CC);
#endif
zend_class_implements(php_phongo_invalidargumentexception_ce TSRMLS_CC, 1, php_phongo_exception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/LogicException.c 0000644 0000765 0000024 00000003146 13572250757 021557 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_logicexception_ce;
/* {{{ MongoDB\Driver\Exception\LogicException function entries */
static zend_function_entry php_phongo_logicexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_logicexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "LogicException", php_phongo_logicexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_logicexception_ce = zend_register_internal_class_ex(&ce, spl_ce_LogicException);
#else
php_phongo_logicexception_ce = zend_register_internal_class_ex(&ce, spl_ce_LogicException, NULL TSRMLS_CC);
#endif
zend_class_implements(php_phongo_logicexception_ce TSRMLS_CC, 1, php_phongo_exception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/RuntimeException.c 0000644 0000765 0000024 00000007230 13572250757 022143 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_array_api.h"
zend_class_entry* php_phongo_runtimeexception_ce;
static bool php_phongo_has_string_array_element(zval* labels, char* label TSRMLS_DC)
{
HashTable* ht_data;
if (Z_TYPE_P(labels) != IS_ARRAY) {
return false;
}
ht_data = HASH_OF(labels);
#if PHP_VERSION_ID >= 70000
{
zval* z_label;
ZEND_HASH_FOREACH_VAL(ht_data, z_label)
{
if ((Z_TYPE_P(z_label) == IS_STRING) && (strcmp(Z_STRVAL_P(z_label), label) == 0)) {
return true;
}
}
ZEND_HASH_FOREACH_END();
}
#else
{
HashPosition pos;
zval** z_label;
for (
zend_hash_internal_pointer_reset_ex(ht_data, &pos);
zend_hash_get_current_data_ex(ht_data, (void**) &z_label, &pos) == SUCCESS;
zend_hash_move_forward_ex(ht_data, &pos)) {
if (Z_TYPE_PP(z_label) == IS_STRING) {
if (strcmp(Z_STRVAL_PP(z_label), label) == 0) {
return true;
}
}
}
}
#endif
return false;
}
/* {{{ proto bool MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $label)
Returns whether a specific error label has been set */
static PHP_METHOD(RuntimeException, hasErrorLabel)
{
char* label;
phongo_zpp_char_len label_len;
zval* error_labels;
#if PHP_VERSION_ID >= 70000
zval rv;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &label, &label_len) == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
error_labels = zend_read_property(php_phongo_runtimeexception_ce, getThis(), ZEND_STRL("errorLabels"), 0, &rv TSRMLS_CC);
#else
error_labels = zend_read_property(php_phongo_runtimeexception_ce, getThis(), ZEND_STRL("errorLabels"), 0 TSRMLS_CC);
#endif
RETURN_BOOL(php_phongo_has_string_array_element(error_labels, label TSRMLS_CC));
} /* }}} */
ZEND_BEGIN_ARG_INFO_EX(ai_RuntimeException_hasErrorLabel, 0, 0, 1)
ZEND_ARG_INFO(0, label)
ZEND_END_ARG_INFO()
/* {{{ MongoDB\Driver\Exception\RuntimeException function entries */
static zend_function_entry php_phongo_runtimeexception_me[] = {
/* clang-format off */
PHP_ME(RuntimeException, hasErrorLabel, ai_RuntimeException_hasErrorLabel, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_runtimeexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "RuntimeException", php_phongo_runtimeexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_runtimeexception_ce = zend_register_internal_class_ex(&ce, spl_ce_RuntimeException);
#else
php_phongo_runtimeexception_ce = zend_register_internal_class_ex(&ce, spl_ce_RuntimeException, NULL TSRMLS_CC);
#endif
zend_class_implements(php_phongo_runtimeexception_ce TSRMLS_CC, 1, php_phongo_exception_ce);
zend_declare_property_null(php_phongo_runtimeexception_ce, ZEND_STRL("errorLabels"), ZEND_ACC_PROTECTED TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/SSLConnectionException.c 0000644 0000765 0000024 00000003166 13572250757 023205 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_sslconnectionexception_ce;
/* {{{ MongoDB\Driver\Exception\SSLConnectionException function entries */
static zend_function_entry php_phongo_sslconnectionexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_sslconnectionexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "SSLConnectionException", php_phongo_sslconnectionexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_sslconnectionexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce);
#else
php_phongo_sslconnectionexception_ce = zend_register_internal_class_ex(&ce, php_phongo_connectionexception_ce, NULL TSRMLS_CC);
#endif
PHONGO_CE_FINAL(php_phongo_sslconnectionexception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/ServerException.c 0000644 0000765 0000024 00000002773 13572250757 021775 0 ustar alcaeus staff /*
* Copyright 2018 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_serverexception_ce;
/* {{{ MongoDB\Driver\Exception\ServerException function entries */
static zend_function_entry php_phongo_serverexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_serverexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ServerException", php_phongo_serverexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_serverexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce);
#else
php_phongo_serverexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce, NULL TSRMLS_CC);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/UnexpectedValueException.c 0000644 0000765 0000024 00000003324 13572250757 023621 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_unexpectedvalueexception_ce;
/* {{{ MongoDB\Driver\Exception\UnexpectedValueException function entries */
static zend_function_entry php_phongo_unexpectedvalueexception_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_unexpectedvalueexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "UnexpectedValueException", php_phongo_unexpectedvalueexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_unexpectedvalueexception_ce = zend_register_internal_class_ex(&ce, spl_ce_UnexpectedValueException);
#else
php_phongo_unexpectedvalueexception_ce = zend_register_internal_class_ex(&ce, spl_ce_UnexpectedValueException, NULL TSRMLS_CC);
#endif
zend_class_implements(php_phongo_unexpectedvalueexception_ce TSRMLS_CC, 1, php_phongo_exception_ce);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Exception/WriteException.c 0000644 0000765 0000024 00000005076 13572250757 021620 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_writeexception_ce;
/* {{{ proto MongoDB\Driver\WriteResult MongoDB\Driver\Exception\WriteException::getWriteResult()
Returns the WriteResult from the failed write operation. */
static PHP_METHOD(WriteException, getWriteResult)
{
zval* writeresult;
#if PHP_VERSION_ID >= 70000
zval rv;
#endif
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
writeresult = zend_read_property(php_phongo_writeexception_ce, getThis(), ZEND_STRL("writeResult"), 0, &rv TSRMLS_CC);
#else
writeresult = zend_read_property(php_phongo_writeexception_ce, getThis(), ZEND_STRL("writeResult"), 0 TSRMLS_CC);
#endif
RETURN_ZVAL(writeresult, 1, 0);
} /* }}} */
/* {{{ MongoDB\Driver\Exception\WriteException function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteException_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_writeexception_me[] = {
/* clang-format off */
PHP_ME(WriteException, getWriteResult, ai_WriteException_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_writeexception_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "WriteException", php_phongo_writeexception_me);
#if PHP_VERSION_ID >= 70000
php_phongo_writeexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce);
#else
php_phongo_writeexception_ce = zend_register_internal_class_ex(&ce, php_phongo_serverexception_ce, NULL TSRMLS_CC);
#endif
php_phongo_writeexception_ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS;
zend_declare_property_null(php_phongo_writeexception_ce, ZEND_STRL("writeResult"), ZEND_ACC_PROTECTED TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/CommandFailedEvent.c 0000644 0000765 0000024 00000022535 13572250757 022522 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_commandfailedevent_ce;
/* {{{ proto string CommandFailedEvent::getCommandName()
Returns the command name for this event */
PHP_METHOD(CommandFailedEvent, getCommandName)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETVAL_STRING(intern->command_name);
} /* }}} */
/* {{{ proto int CommandFailedEvent::getDurationMicros()
Returns the event's duration in microseconds */
PHP_METHOD(CommandFailedEvent, getDurationMicros)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->duration_micros);
} /* }}} */
/* {{{ proto Exception CommandFailedEvent::getError()
Returns the error document associated with the event */
PHP_METHOD(CommandFailedEvent, getError)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&intern->z_error, 1, 0);
#else
RETURN_ZVAL(intern->z_error, 1, 0);
#endif
} /* }}} */
/* {{{ proto string CommandFailedEvent::getOperationId()
Returns the event's operation ID */
PHP_METHOD(CommandFailedEvent, getOperationId)
{
php_phongo_commandfailedevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->operation_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto stdClass CommandFailedEvent::getReply()
Returns the reply document associated with the event */
PHP_METHOD(CommandFailedEvent, getReply)
{
php_phongo_commandfailedevent_t* intern;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_bson_to_zval_ex(bson_get_data(intern->reply), intern->reply->len, &state);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto string CommandFailedEvent::getRequestId()
Returns the event's request ID */
PHP_METHOD(CommandFailedEvent, getRequestId)
{
php_phongo_commandfailedevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->request_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto MongoDB\Driver\Server CommandFailedEvent::getServer()
Returns the Server from which the event originated */
PHP_METHOD(CommandFailedEvent, getServer)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phongo_server_init(return_value, intern->client, intern->server_id TSRMLS_CC);
} /* }}} */
/**
* Event thrown when a command has failed to execute.
*
* This class is only constructed internally.
*/
/* {{{ MongoDB\Driver\Monitoring\CommandFailedEvent function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CommandFailedEvent_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_commandfailedevent_me[] = {
/* clang-format off */
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_CommandFailedEvent_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getCommandName, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getError, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getDurationMicros, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getOperationId, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getReply, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getRequestId, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandFailedEvent, getServer, ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_CommandFailedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Monitoring\CommandFailedEvent object handlers */
static zend_object_handlers php_phongo_handler_commandfailedevent;
static void php_phongo_commandfailedevent_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_commandfailedevent_t* intern = Z_OBJ_COMMANDFAILEDEVENT(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (!Z_ISUNDEF(intern->z_error)) {
zval_ptr_dtor(&intern->z_error);
}
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->command_name) {
efree(intern->command_name);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_commandfailedevent_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_commandfailedevent_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_commandfailedevent_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_commandfailedevent;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_commandfailedevent_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_commandfailedevent;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_commandfailedevent_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_commandfailedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[20], request_id[20];
php_phongo_bson_state reply_state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(object);
*is_temp = 1;
array_init_size(&retval, 6);
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_INT64(&retval, "durationMicros", (int64_t) intern->duration_micros);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "error", &intern->z_error);
Z_ADDREF(intern->z_error);
#else
ADD_ASSOC_ZVAL_EX(&retval, "error", intern->z_error);
Z_ADDREF_P(intern->z_error);
#endif
sprintf(operation_id, "%" PRIu64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
php_phongo_bson_to_zval_ex(bson_get_data(intern->reply), intern->reply->len, &reply_state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL(&retval, "reply", &reply_state.zchild);
#else
ADD_ASSOC_ZVAL(&retval, "reply", reply_state.zchild);
#endif
sprintf(request_id, "%" PRIu64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
{
#if PHP_VERSION_ID >= 70000
zval server;
phongo_server_init(&server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
#else
zval* server = NULL;
MAKE_STD_ZVAL(server);
phongo_server_init(server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", server);
#endif
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_commandfailedevent_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
(void) type;
(void) module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandFailedEvent", php_phongo_commandfailedevent_me);
php_phongo_commandfailedevent_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_commandfailedevent_ce->create_object = php_phongo_commandfailedevent_create_object;
PHONGO_CE_FINAL(php_phongo_commandfailedevent_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_commandfailedevent_ce);
memcpy(&php_phongo_handler_commandfailedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandfailedevent.get_debug_info = php_phongo_commandfailedevent_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_commandfailedevent.free_obj = php_phongo_commandfailedevent_free_object;
php_phongo_handler_commandfailedevent.offset = XtOffsetOf(php_phongo_commandfailedevent_t, std);
#endif
return;
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/CommandStartedEvent.c 0000644 0000765 0000024 00000021304 13572250757 022735 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_commandstartedevent_ce;
/* {{{ proto stdClass CommandStartedEvent::getCommand()
Returns the command document associated with the event */
PHP_METHOD(CommandStartedEvent, getCommand)
{
php_phongo_commandstartedevent_t* intern;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_bson_to_zval_ex(bson_get_data(intern->command), intern->command->len, &state);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto string CommandStartedEvent::getCommandName()
Returns the command name for this event */
PHP_METHOD(CommandStartedEvent, getCommandName)
{
php_phongo_commandstartedevent_t* intern;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETVAL_STRING(intern->command_name);
} /* }}} */
/* {{{ proto string CommandStartedEvent::getDatabaseName()
Returns the database name for this event */
PHP_METHOD(CommandStartedEvent, getDatabaseName)
{
php_phongo_commandstartedevent_t* intern;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETVAL_STRING(intern->database_name);
} /* }}} */
/* {{{ proto string CommandStartedEvent::getOperationId()
Returns the event's operation ID */
PHP_METHOD(CommandStartedEvent, getOperationId)
{
php_phongo_commandstartedevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->operation_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto string CommandStartedEvent::getRequestId()
Returns the event's request ID */
PHP_METHOD(CommandStartedEvent, getRequestId)
{
php_phongo_commandstartedevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->request_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto MongoDB\Driver\Server CommandStartedEvent::getServer()
Returns the Server from which the event originated */
PHP_METHOD(CommandStartedEvent, getServer)
{
php_phongo_commandstartedevent_t* intern;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phongo_server_init(return_value, intern->client, intern->server_id TSRMLS_CC);
} /* }}} */
/**
* Event thrown when a command has started to execute.
*
* This class is only constructed internally.
*/
/* {{{ MongoDB\Driver\Monitoring\CommandStartedEvent function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CommandStartedEvent_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_commandstartedevent_me[] = {
/* clang-format off */
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_CommandStartedEvent_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getCommand, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getCommandName, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getDatabaseName, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getOperationId, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getRequestId, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandStartedEvent, getServer, ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_CommandStartedEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Monitoring\CommandStartedEvent object handlers */
static zend_object_handlers php_phongo_handler_commandstartedevent;
static void php_phongo_commandstartedevent_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_commandstartedevent_t* intern = Z_OBJ_COMMANDSTARTEDEVENT(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->command) {
bson_destroy(intern->command);
}
if (intern->command_name) {
efree(intern->command_name);
}
if (intern->database_name) {
efree(intern->database_name);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_commandstartedevent_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_commandstartedevent_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_commandstartedevent_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_commandstartedevent;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_commandstartedevent_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_commandstartedevent;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_commandstartedevent_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_commandstartedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[20], request_id[20];
php_phongo_bson_state command_state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(object);
*is_temp = 1;
array_init_size(&retval, 6);
php_phongo_bson_to_zval_ex(bson_get_data(intern->command), intern->command->len, &command_state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL(&retval, "command", &command_state.zchild);
#else
ADD_ASSOC_ZVAL(&retval, "command", command_state.zchild);
#endif
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_STRING(&retval, "databaseName", intern->database_name);
sprintf(operation_id, "%" PRIu64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
sprintf(request_id, "%" PRIu64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
{
#if PHP_VERSION_ID >= 70000
zval server;
phongo_server_init(&server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
#else
zval* server = NULL;
MAKE_STD_ZVAL(server);
phongo_server_init(server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", server);
#endif
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_commandstartedevent_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
(void) type;
(void) module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandStartedEvent", php_phongo_commandstartedevent_me);
php_phongo_commandstartedevent_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_commandstartedevent_ce->create_object = php_phongo_commandstartedevent_create_object;
PHONGO_CE_FINAL(php_phongo_commandstartedevent_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_commandstartedevent_ce);
memcpy(&php_phongo_handler_commandstartedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandstartedevent.get_debug_info = php_phongo_commandstartedevent_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_commandstartedevent.free_obj = php_phongo_commandstartedevent_free_object;
php_phongo_handler_commandstartedevent.offset = XtOffsetOf(php_phongo_commandstartedevent_t, std);
#endif
return;
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/CommandSubscriber.c 0000644 0000765 0000024 00000004521 13572250757 022432 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_commandsubscriber_ce;
/* {{{ MongoDB\Driver\Monitoring\CommandSubscriber function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CommandSubscriber_commandStarted, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandStartedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_CommandSubscriber_commandSucceeded, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandSucceededEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_CommandSubscriber_commandFailed, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandFailedEvent, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_commandsubscriber_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(CommandSubscriber, commandStarted, ai_CommandSubscriber_commandStarted)
ZEND_ABSTRACT_ME(CommandSubscriber, commandSucceeded, ai_CommandSubscriber_commandSucceeded)
ZEND_ABSTRACT_ME(CommandSubscriber, commandFailed, ai_CommandSubscriber_commandFailed)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_commandsubscriber_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
(void) type;
(void) module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandSubscriber", php_phongo_commandsubscriber_me);
php_phongo_commandsubscriber_ce = zend_register_internal_interface(&ce TSRMLS_CC);
zend_class_implements(php_phongo_commandsubscriber_ce TSRMLS_CC, 1, php_phongo_subscriber_ce);
return;
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/CommandSucceededEvent.c 0000644 0000765 0000024 00000021414 13572250757 023215 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_commandsucceededevent_ce;
/* {{{ proto string CommandSucceededEvent::getCommandName()
Returns the command name for this event */
PHP_METHOD(CommandSucceededEvent, getCommandName)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETVAL_STRING(intern->command_name);
} /* }}} */
/* {{{ proto int CommandSucceededEvent::getDurationMicros()
Returns the event's duration in microseconds */
PHP_METHOD(CommandSucceededEvent, getDurationMicros)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->duration_micros);
} /* }}} */
/* {{{ proto string CommandSucceededEvent::getOperationId()
Returns the event's operation ID */
PHP_METHOD(CommandSucceededEvent, getOperationId)
{
php_phongo_commandsucceededevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->operation_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto stdClass CommandSucceededEvent::getReply()
Returns the reply document associated with the event */
PHP_METHOD(CommandSucceededEvent, getReply)
{
php_phongo_commandsucceededevent_t* intern;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_bson_to_zval_ex(bson_get_data(intern->reply), intern->reply->len, &state);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto string CommandsucceededEvent::getRequestId()
Returns the event's request ID */
PHP_METHOD(CommandSucceededEvent, getRequestId)
{
php_phongo_commandsucceededevent_t* intern;
char int_as_string[20];
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sprintf(int_as_string, "%" PRIu64, intern->request_id);
PHONGO_RETVAL_STRING(int_as_string);
} /* }}} */
/* {{{ proto MongoDB\Driver\Server CommandSucceededEvent::getServer()
Returns the Server from which the event originated */
PHP_METHOD(CommandSucceededEvent, getServer)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phongo_server_init(return_value, intern->client, intern->server_id TSRMLS_CC);
} /* }}} */
/**
* Event thrown when a command has succeeded to execute.
*
* This class is only constructed internally.
*/
/* {{{ MongoDB\Driver\Monitoring\CommandSucceededEvent function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CommandSucceededEvent_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_commandsucceededevent_me[] = {
/* clang-format off */
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_CommandSucceededEvent_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getCommandName, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getDurationMicros, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getOperationId, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getReply, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getRequestId, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(CommandSucceededEvent, getServer, ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_CommandSucceededEvent_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Monitoring\CommandSucceededEvent object handlers */
static zend_object_handlers php_phongo_handler_commandsucceededevent;
static void php_phongo_commandsucceededevent_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_commandsucceededevent_t* intern = Z_OBJ_COMMANDSUCCEEDEDEVENT(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->command_name) {
efree(intern->command_name);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_commandsucceededevent_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_commandsucceededevent_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_commandsucceededevent_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_commandsucceededevent;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_commandsucceededevent_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_commandsucceededevent;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_commandsucceededevent_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_commandsucceededevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[20], request_id[20];
php_phongo_bson_state reply_state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(object);
*is_temp = 1;
array_init_size(&retval, 6);
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_INT64(&retval, "durationMicros", (int64_t) intern->duration_micros);
sprintf(operation_id, "%" PRIu64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
php_phongo_bson_to_zval_ex(bson_get_data(intern->reply), intern->reply->len, &reply_state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL(&retval, "reply", &reply_state.zchild);
#else
ADD_ASSOC_ZVAL(&retval, "reply", reply_state.zchild);
#endif
sprintf(request_id, "%" PRIu64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
{
#if PHP_VERSION_ID >= 70000
zval server;
phongo_server_init(&server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
#else
zval* server = NULL;
MAKE_STD_ZVAL(server);
phongo_server_init(server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", server);
#endif
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_commandsucceededevent_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
(void) type;
(void) module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandSucceededEvent", php_phongo_commandsucceededevent_me);
php_phongo_commandsucceededevent_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_commandsucceededevent_ce->create_object = php_phongo_commandsucceededevent_create_object;
PHONGO_CE_FINAL(php_phongo_commandsucceededevent_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_commandsucceededevent_ce);
memcpy(&php_phongo_handler_commandsucceededevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandsucceededevent.get_debug_info = php_phongo_commandsucceededevent_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_commandsucceededevent.free_obj = php_phongo_commandsucceededevent_free_object;
php_phongo_handler_commandsucceededevent.offset = XtOffsetOf(php_phongo_commandsucceededevent_t, std);
#endif
return;
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/Subscriber.c 0000644 0000765 0000024 00000002573 13572250757 021140 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_subscriber_ce;
/* {{{ MongoDB\Driver\Monitoring\Subscriber function entries */
static zend_function_entry php_phongo_subscriber_me[] = {
PHP_FE_END
};
/* }}} */
void php_phongo_subscriber_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
(void) type;
(void) module_number;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "Subscriber", php_phongo_subscriber_me);
php_phongo_subscriber_ce = zend_register_internal_interface(&ce TSRMLS_CC);
return;
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/functions.c 0000644 0000765 0000024 00000006352 13572250757 021044 0 ustar alcaeus staff /*
* Copyright 2016-2017 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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
ZEND_EXTERN_MODULE_GLOBALS(mongodb)
static char* php_phongo_make_subscriber_hash(zval* subscriber TSRMLS_DC)
{
char* hash;
int hash_len;
hash_len = spprintf(&hash, 0, "SUBS-%09d", Z_OBJ_HANDLE_P(subscriber));
return hash;
}
/* {{{ proto void MongoDB\Driver\Monitoring\addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber)
Adds a monitoring subscriber to the set of subscribers */
PHP_FUNCTION(MongoDB_Driver_Monitoring_addSubscriber)
{
zval* zSubscriber = NULL;
char* hash;
#if PHP_VERSION_ID >= 70000
zval* subscriber;
#else
zval** subscriber;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &zSubscriber, php_phongo_subscriber_ce) == FAILURE) {
return;
}
/* The HashTable should never be NULL, as it's initialized during RINIT and
* destroyed during RSHUTDOWN. This is simply a defensive guard. */
if (!MONGODB_G(subscribers)) {
return;
}
hash = php_phongo_make_subscriber_hash(zSubscriber TSRMLS_CC);
/* If we have already stored the subscriber, bail out. Otherwise, add
* subscriber to list */
#if PHP_VERSION_ID >= 70000
if ((subscriber = zend_hash_str_find(MONGODB_G(subscribers), hash, strlen(hash)))) {
efree(hash);
return;
}
zend_hash_str_update(MONGODB_G(subscribers), hash, strlen(hash), zSubscriber);
#else
if (zend_hash_find(MONGODB_G(subscribers), hash, strlen(hash) + 1, (void**) &subscriber) == SUCCESS) {
efree(hash);
return;
}
zend_hash_update(MONGODB_G(subscribers), hash, strlen(hash) + 1, (void*) &zSubscriber, sizeof(zval*), NULL);
#endif
Z_ADDREF_P(zSubscriber);
efree(hash);
} /* }}} */
/* {{{ proto void MongoDB\Driver\Monitoring\removeSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber)
Removes a monitoring subscriber from the set of subscribers */
PHP_FUNCTION(MongoDB_Driver_Monitoring_removeSubscriber)
{
zval* zSubscriber = NULL;
char* hash;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &zSubscriber, php_phongo_subscriber_ce) == FAILURE) {
return;
}
/* The HashTable should never be NULL, as it's initialized during RINIT and
* destroyed during RSHUTDOWN. This is simply a defensive guard. */
if (!MONGODB_G(subscribers)) {
return;
}
hash = php_phongo_make_subscriber_hash(zSubscriber TSRMLS_CC);
#if PHP_VERSION_ID >= 70000
zend_hash_str_del(MONGODB_G(subscribers), hash, strlen(hash));
#else
zend_hash_del(MONGODB_G(subscribers), hash, strlen(hash) + 1);
#endif
efree(hash);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Monitoring/functions.h 0000644 0000765 0000024 00000001736 13572250757 021052 0 ustar alcaeus staff /*
* Copyright 2016-2017 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.
*/
#ifndef PHONGO_MONITORING_FUNCTIONS_H
#define PHONGO_MONITORING_FUNCTIONS_H
#include
PHP_FUNCTION(MongoDB_Driver_Monitoring_addSubscriber);
PHP_FUNCTION(MongoDB_Driver_Monitoring_removeSubscriber);
#endif /* PHONGO_MONITORING_FUNCTIONS_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/BulkWrite.c 0000644 0000765 0000024 00000047463 13572250757 016627 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
#define PHONGO_BULKWRITE_BYPASS_UNSET -1
zend_class_entry* php_phongo_bulkwrite_ce;
/* Extracts the "_id" field of a BSON document into a return value. */
static void php_phongo_bulkwrite_extract_id(bson_t* doc, zval** return_value) /* {{{ */
{
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
zval* id = NULL;
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!php_phongo_bson_to_zval_ex(bson_get_data(doc), doc->len, &state)) {
goto cleanup;
}
#if PHP_VERSION_ID >= 70000
id = php_array_fetchc(&state.zchild, "_id");
#else
id = php_array_fetchc(state.zchild, "_id");
#endif
if (id) {
ZVAL_ZVAL(*return_value, id, 1, 0);
}
cleanup:
zval_ptr_dtor(&state.zchild);
} /* }}} */
/* Returns whether any top-level field names in the document contain a "$". */
static inline bool php_phongo_bulkwrite_update_has_operators(bson_t* bupdate) /* {{{ */
{
bson_iter_t iter;
if (bson_iter_init(&iter, bupdate)) {
while (bson_iter_next(&iter)) {
if (strchr(bson_iter_key(&iter), '$')) {
return true;
}
}
}
return false;
} /* }}} */
/* Returns whether the update document is considered an aggregation pipeline */
static inline bool php_phongo_bulkwrite_update_is_pipeline(bson_t* bupdate) /* {{{ */
{
bson_iter_t iter;
bson_iter_t child;
const char* key;
int i = 0;
char* i_str;
if (!bson_iter_init(&iter, bupdate)) {
return false;
}
while (bson_iter_next(&iter)) {
key = bson_iter_key(&iter);
i_str = bson_strdup_printf("%d", i++);
if (strcmp(key, i_str)) {
bson_free(i_str);
return false;
}
bson_free(i_str);
if (BSON_ITER_HOLDS_DOCUMENT(&iter)) {
if (!bson_iter_recurse(&iter, &child)) {
return false;
}
if (!bson_iter_next(&child)) {
return false;
}
key = bson_iter_key(&child);
if (key[0] != '$') {
return false;
}
} else {
return false;
}
}
/* should return false when the document is empty */
return i != 0;
} /* }}} */
/* Returns whether the BSON array's keys are a sequence of integer strings
* starting with "0". BSON_APPEND_ARRAY considers it the caller's responsibility
* to ensure that the array's keys are properly formatted. */
static inline bool php_phongo_bulkwrite_bson_array_has_valid_keys(bson_t* array) /* {{{ */
{
bson_iter_t iter;
if (bson_empty(array)) {
return true;
}
if (bson_iter_init(&iter, array)) {
char key[12];
int count = 0;
while (bson_iter_next(&iter)) {
bson_snprintf(key, sizeof(key), "%d", count);
if (0 != strcmp(key, bson_iter_key(&iter))) {
return false;
}
count++;
}
}
return true;
} /* }}} */
/* Appends an array field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_bulkwrite_opts_append_array(bson_t* opts, const char* key, zval* zarr TSRMLS_DC) /* {{{ */
{
zval* value = php_array_fetch(zarr, key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(value)));
return false;
}
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, &b, NULL TSRMLS_CC);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!php_phongo_bulkwrite_bson_array_has_valid_keys(&b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "\"%s\" option has invalid keys for a BSON array", key);
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_ARRAY(opts, key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
} /* }}} */
/* Appends a document field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_bulkwrite_opts_append_document(bson_t* opts, const char* key, zval* zarr TSRMLS_DC) /* {{{ */
{
zval* value = php_array_fetch(zarr, key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(value)));
return false;
}
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, &b, NULL TSRMLS_CC);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_DOCUMENT(opts, key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
} /* }}} */
#define PHONGO_BULKWRITE_APPEND_BOOL(opt, value) \
if (!BSON_APPEND_BOOL(boptions, (opt), (value))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", (opt)); \
return false; \
}
#define PHONGO_BULKWRITE_APPEND_INT32(opt, value) \
if (!BSON_APPEND_INT32(boptions, (opt), (value))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", (opt)); \
return false; \
}
#define PHONGO_BULKWRITE_OPT_ARRAY(opt) \
if (zoptions && php_array_existsc(zoptions, (opt))) { \
if (!php_phongo_bulkwrite_opts_append_array(boptions, (opt), zoptions TSRMLS_CC)) { \
return false; \
} \
}
#define PHONGO_BULKWRITE_OPT_DOCUMENT(opt) \
if (zoptions && php_array_existsc(zoptions, (opt))) { \
if (!php_phongo_bulkwrite_opts_append_document(boptions, (opt), zoptions TSRMLS_CC)) { \
return false; \
} \
}
/* Applies options (including defaults) for an update operation. */
static bool php_phongo_bulkwrite_update_apply_options(bson_t* boptions, zval* zoptions TSRMLS_DC) /* {{{ */
{
bool multi = false, upsert = false;
if (zoptions) {
if (php_array_existsc(zoptions, "multi")) {
multi = php_array_fetchc_bool(zoptions, "multi");
}
if (php_array_existsc(zoptions, "upsert")) {
upsert = php_array_fetchc_bool(zoptions, "upsert");
}
}
PHONGO_BULKWRITE_APPEND_BOOL("multi", multi);
PHONGO_BULKWRITE_APPEND_BOOL("upsert", upsert);
PHONGO_BULKWRITE_OPT_ARRAY("arrayFilters");
PHONGO_BULKWRITE_OPT_DOCUMENT("collation");
return true;
} /* }}} */
/* Applies options (including defaults) for an delete operation. */
static bool php_phongo_bulkwrite_delete_apply_options(bson_t* boptions, zval* zoptions TSRMLS_DC) /* {{{ */
{
int32_t limit = 0;
if (zoptions) {
if (php_array_existsc(zoptions, "limit")) {
limit = php_array_fetchc_bool(zoptions, "limit") ? 1 : 0;
}
}
PHONGO_BULKWRITE_APPEND_INT32("limit", limit);
PHONGO_BULKWRITE_OPT_DOCUMENT("collation");
return true;
} /* }}} */
#undef PHONGO_BULKWRITE_APPEND_BOOL
#undef PHONGO_BULKWRITE_APPEND_INT32
#undef PHONGO_BULKWRITE_OPT_DOCUMENT
/* {{{ proto void MongoDB\Driver\BulkWrite::__construct([array $options = array()])
Constructs a new BulkWrite */
static PHP_METHOD(BulkWrite, __construct)
{
php_phongo_bulkwrite_t* intern;
zend_error_handling error_handling;
zval* options = NULL;
zend_bool ordered = 1;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_BULKWRITE_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &options) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (options && php_array_existsc(options, "ordered")) {
ordered = php_array_fetchc_bool(options, "ordered");
}
intern->bulk = mongoc_bulk_operation_new(ordered);
intern->ordered = ordered;
intern->bypass = PHONGO_BULKWRITE_BYPASS_UNSET;
intern->num_ops = 0;
if (options && php_array_existsc(options, "bypassDocumentValidation")) {
zend_bool bypass = php_array_fetchc_bool(options, "bypassDocumentValidation");
mongoc_bulk_operation_set_bypass_document_validation(intern->bulk, bypass);
intern->bypass = bypass;
}
} /* }}} */
/* {{{ proto mixed MongoDB\Driver\BulkWrite::insert(array|object $document)
Adds an insert operation to the BulkWrite */
static PHP_METHOD(BulkWrite, insert)
{
php_phongo_bulkwrite_t* intern;
zval* zdocument;
bson_t bdocument = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_t* bson_out = NULL;
int bson_flags = PHONGO_BSON_ADD_ID;
bson_error_t error = { 0 };
DECLARE_RETURN_VALUE_USED
intern = Z_BULKWRITE_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A", &zdocument) == FAILURE) {
return;
}
if (return_value_used) {
bson_flags |= PHONGO_BSON_RETURN_ID;
}
php_phongo_zval_to_bson(zdocument, bson_flags, &bdocument, &bson_out TSRMLS_CC);
if (EG(exception)) {
goto cleanup;
}
if (!mongoc_bulk_operation_insert_with_opts(intern->bulk, &bdocument, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
intern->num_ops++;
if (bson_out && return_value_used) {
php_phongo_bulkwrite_extract_id(bson_out, &return_value);
}
cleanup:
bson_destroy(&bdocument);
bson_destroy(&boptions);
bson_clear(&bson_out);
} /* }}} */
/* {{{ proto void MongoDB\Driver\BulkWrite::update(array|object $query, array|object $newObj[, array $updateOptions = array()])
Adds an update operation to the BulkWrite */
static PHP_METHOD(BulkWrite, update)
{
php_phongo_bulkwrite_t* intern;
zval * zquery, *zupdate, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, bupdate = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
intern = Z_BULKWRITE_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "AA|a!", &zquery, &zupdate, &zoptions) == FAILURE) {
return;
}
php_phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL TSRMLS_CC);
if (EG(exception)) {
goto cleanup;
}
php_phongo_zval_to_bson(zupdate, PHONGO_BSON_NONE, &bupdate, NULL TSRMLS_CC);
if (EG(exception)) {
goto cleanup;
}
if (!php_phongo_bulkwrite_update_apply_options(&boptions, zoptions TSRMLS_CC)) {
goto cleanup;
}
if (php_phongo_bulkwrite_update_has_operators(&bupdate) || php_phongo_bulkwrite_update_is_pipeline(&bupdate)) {
if (zoptions && php_array_existsc(zoptions, "multi") && php_array_fetchc_bool(zoptions, "multi")) {
if (!mongoc_bulk_operation_update_many_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
} else {
if (!mongoc_bulk_operation_update_one_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
}
} else {
if (zoptions && php_array_existsc(zoptions, "multi") && php_array_fetchc_bool(zoptions, "multi")) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Replacement document conflicts with true \"multi\" option");
goto cleanup;
}
if (!mongoc_bulk_operation_replace_one_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
}
intern->num_ops++;
cleanup:
bson_destroy(&bquery);
bson_destroy(&bupdate);
bson_destroy(&boptions);
} /* }}} */
/* {{{ proto void MongoDB\Driver\BulkWrite::delete(array|object $query[, array $deleteOptions = array()])
Adds a delete operation to the BulkWrite */
static PHP_METHOD(BulkWrite, delete)
{
php_phongo_bulkwrite_t* intern;
zval * zquery, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
intern = Z_BULKWRITE_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A|a!", &zquery, &zoptions) == FAILURE) {
return;
}
php_phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL TSRMLS_CC);
if (EG(exception)) {
goto cleanup;
}
if (!php_phongo_bulkwrite_delete_apply_options(&boptions, zoptions TSRMLS_CC)) {
goto cleanup;
}
if (zoptions && php_array_existsc(zoptions, "limit") && php_array_fetchc_bool(zoptions, "limit")) {
if (!mongoc_bulk_operation_remove_one_with_opts(intern->bulk, &bquery, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
} else {
if (!mongoc_bulk_operation_remove_many_with_opts(intern->bulk, &bquery, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
goto cleanup;
}
}
intern->num_ops++;
cleanup:
bson_destroy(&bquery);
bson_destroy(&boptions);
} /* }}} */
/* {{{ proto integer MongoDB\Driver\BulkWrite::count()
Returns the number of operations that have been added to the BulkWrite */
static PHP_METHOD(BulkWrite, count)
{
php_phongo_bulkwrite_t* intern;
intern = Z_BULKWRITE_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->num_ops);
} /* }}} */
/* {{{ MongoDB\Driver\BulkWrite function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_BulkWrite___construct, 0, 0, 0)
ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_BulkWrite_insert, 0, 0, 1)
ZEND_ARG_INFO(0, document)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_BulkWrite_update, 0, 0, 2)
ZEND_ARG_INFO(0, query)
ZEND_ARG_INFO(0, newObj)
ZEND_ARG_ARRAY_INFO(0, updateOptions, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_BulkWrite_delete, 0, 0, 1)
ZEND_ARG_INFO(0, query)
ZEND_ARG_ARRAY_INFO(0, deleteOptions, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_BulkWrite_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_bulkwrite_me[] = {
/* clang-format off */
PHP_ME(BulkWrite, __construct, ai_BulkWrite___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(BulkWrite, insert, ai_BulkWrite_insert, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(BulkWrite, update, ai_BulkWrite_update, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(BulkWrite, delete, ai_BulkWrite_delete, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(BulkWrite, count, ai_BulkWrite_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_BulkWrite_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\BulkWrite object handlers */
static zend_object_handlers php_phongo_handler_bulkwrite;
static void php_phongo_bulkwrite_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_bulkwrite_t* intern = Z_OBJ_BULKWRITE(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->bulk) {
mongoc_bulk_operation_destroy(intern->bulk);
}
if (intern->database) {
efree(intern->database);
}
if (intern->collection) {
efree(intern->collection);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_bulkwrite_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_bulkwrite_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_bulkwrite_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_bulkwrite;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_bulkwrite_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_bulkwrite;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_bulkwrite_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
zval retval = ZVAL_STATIC_INIT;
php_phongo_bulkwrite_t* intern = NULL;
*is_temp = 1;
intern = Z_BULKWRITE_OBJ_P(object);
array_init(&retval);
if (intern->database) {
ADD_ASSOC_STRING(&retval, "database", intern->database);
} else {
ADD_ASSOC_NULL_EX(&retval, "database");
}
if (intern->collection) {
ADD_ASSOC_STRING(&retval, "collection", intern->collection);
} else {
ADD_ASSOC_NULL_EX(&retval, "collection");
}
ADD_ASSOC_BOOL_EX(&retval, "ordered", intern->ordered);
if (intern->bypass != PHONGO_BULKWRITE_BYPASS_UNSET) {
ADD_ASSOC_BOOL_EX(&retval, "bypassDocumentValidation", intern->bypass);
} else {
ADD_ASSOC_NULL_EX(&retval, "bypassDocumentValidation");
}
ADD_ASSOC_BOOL_EX(&retval, "executed", intern->executed);
ADD_ASSOC_LONG_EX(&retval, "server_id", mongoc_bulk_operation_get_hint(intern->bulk));
if (mongoc_bulk_operation_get_write_concern(intern->bulk)) {
#if PHP_VERSION_ID >= 70000
zval write_concern;
php_phongo_write_concern_to_zval(&write_concern, mongoc_bulk_operation_get_write_concern(intern->bulk));
ADD_ASSOC_ZVAL_EX(&retval, "write_concern", &write_concern);
#else
zval* write_concern = NULL;
MAKE_STD_ZVAL(write_concern);
php_phongo_write_concern_to_zval(write_concern, mongoc_bulk_operation_get_write_concern(intern->bulk));
ADD_ASSOC_ZVAL_EX(&retval, "write_concern", write_concern);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "write_concern");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_bulkwrite_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "BulkWrite", php_phongo_bulkwrite_me);
php_phongo_bulkwrite_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_bulkwrite_ce->create_object = php_phongo_bulkwrite_create_object;
PHONGO_CE_FINAL(php_phongo_bulkwrite_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_bulkwrite_ce);
memcpy(&php_phongo_handler_bulkwrite, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_bulkwrite.get_debug_info = php_phongo_bulkwrite_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_bulkwrite.free_obj = php_phongo_bulkwrite_free_object;
php_phongo_handler_bulkwrite.offset = XtOffsetOf(php_phongo_bulkwrite_t, std);
#endif
zend_class_implements(php_phongo_bulkwrite_ce TSRMLS_CC, 1, spl_ce_Countable);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Command.c 0000644 0000765 0000024 00000015675 13572250757 016275 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_command_ce;
/* Initialize the "maxAwaitTimeMS" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "maxAwaitTimeMS" option is assigned to the cursor after query execution
* via mongoc_cursor_set_max_await_time_ms(). */
static bool php_phongo_command_init_max_await_time_ms(php_phongo_command_t* intern, zval* options TSRMLS_DC) /* {{{ */
{
if (php_array_existsc(options, "maxAwaitTimeMS")) {
int64_t max_await_time_ms = php_array_fetchc_long(options, "maxAwaitTimeMS");
if (max_await_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxAwaitTimeMS\" option to be >= 0, %" PRId64 " given", max_await_time_ms);
return false;
}
if (max_await_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxAwaitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_await_time_ms);
return false;
}
intern->max_await_time_ms = (uint32_t) max_await_time_ms;
}
return true;
} /* }}} */
/* Initializes the php_phongo_command_init from options argument. This
* function will fall back to a modifier in the absence of a top-level option
* (where applicable). */
static bool php_phongo_command_init(php_phongo_command_t* intern, zval* filter, zval* options TSRMLS_DC) /* {{{ */
{
bson_iter_t iter;
bson_iter_t sub_iter;
intern->bson = bson_new();
php_phongo_zval_to_bson(filter, PHONGO_BSON_NONE, intern->bson, NULL TSRMLS_CC);
/* Note: if any exceptions are thrown, we can simply return as PHP will
* invoke php_phongo_query_free_object to destruct the object. */
if (EG(exception)) {
return false;
}
if (bson_iter_init(&iter, intern->bson) && bson_iter_find_descendant(&iter, "cursor.batchSize", &sub_iter) && BSON_ITER_HOLDS_INT(&sub_iter)) {
int64_t batch_size = bson_iter_as_int64(&sub_iter);
if (batch_size >= 0 && batch_size <= UINT32_MAX) {
intern->batch_size = (uint32_t) batch_size;
}
}
if (!options) {
return true;
}
if (!php_phongo_command_init_max_await_time_ms(intern, options TSRMLS_CC)) {
return false;
}
return true;
} /* }}} */
/* {{{ proto void MongoDB\Driver\Command::__construct(array|object $document[, array $options = array()])
Constructs a new Command */
static PHP_METHOD(Command, __construct)
{
php_phongo_command_t* intern;
zend_error_handling error_handling;
zval* document;
zval* options = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_COMMAND_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A|a!", &document, &options) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_command_init(intern, document, options TSRMLS_CC);
} /* }}} */
/* {{{ MongoDB\Driver\Command function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Command___construct, 0, 0, 1)
ZEND_ARG_INFO(0, document)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Command_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_command_me[] = {
/* clang-format off */
PHP_ME(Command, __construct, ai_Command___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Command_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Command object handlers */
static zend_object_handlers php_phongo_handler_command;
static void php_phongo_command_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_command_t* intern = Z_OBJ_COMMAND(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->bson) {
bson_clear(&intern->bson);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_command_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_command_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_command_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_command;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_command_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_command;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_command_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_command_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_COMMAND_OBJ_P(object);
array_init_size(&retval, 1);
if (intern->bson) {
#if PHP_VERSION_ID >= 70000
zval zv;
#else
zval* zv;
#endif
php_phongo_bson_to_zval(bson_get_data(intern->bson), intern->bson->len, &zv);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "command", &zv);
#else
ADD_ASSOC_ZVAL_EX(&retval, "command", zv);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "command");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_command_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Command", php_phongo_command_me);
php_phongo_command_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_command_ce->create_object = php_phongo_command_create_object;
PHONGO_CE_FINAL(php_phongo_command_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_command_ce);
memcpy(&php_phongo_handler_command, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_command.get_debug_info = php_phongo_command_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_command.free_obj = php_phongo_command_free_object;
php_phongo_handler_command.offset = XtOffsetOf(php_phongo_command_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Cursor.c 0000644 0000765 0000024 00000040641 13572250757 016163 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_cursor_ce;
/* Check if the cursor is exhausted (i.e. ID is zero) and free any reference to
* the session. Calling this function during iteration will allow an implicit
* session to return to the pool immediately after a getMore indicates that the
* server has no more results to return. */
static void php_phongo_cursor_free_session_if_exhausted(php_phongo_cursor_t* cursor) /* {{{ */
{
if (mongoc_cursor_get_id(cursor->cursor)) {
return;
}
if (!Z_ISUNDEF(cursor->session)) {
zval_ptr_dtor(&cursor->session);
ZVAL_UNDEF(&cursor->session);
}
} /* }}} */
static void php_phongo_cursor_free_current(php_phongo_cursor_t* cursor) /* {{{ */
{
if (!Z_ISUNDEF(cursor->visitor_data.zchild)) {
zval_ptr_dtor(&cursor->visitor_data.zchild);
ZVAL_UNDEF(&cursor->visitor_data.zchild);
}
} /* }}} */
/* {{{ MongoDB\Driver\Cursor iterator handlers */
static void php_phongo_cursor_iterator_dtor(zend_object_iterator* iter TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_iterator* cursor_it = (php_phongo_cursor_iterator*) iter;
if (!Z_ISUNDEF(cursor_it->intern.data)) {
#if PHP_VERSION_ID >= 70000
zval_ptr_dtor(&cursor_it->intern.data);
#else
zval_ptr_dtor((zval**) &cursor_it->intern.data);
cursor_it->intern.data = NULL;
#endif
}
#if PHP_VERSION_ID < 70000
efree(cursor_it);
#endif
} /* }}} */
static int php_phongo_cursor_iterator_valid(zend_object_iterator* iter TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* cursor = ((php_phongo_cursor_iterator*) iter)->cursor;
if (!Z_ISUNDEF(cursor->visitor_data.zchild)) {
return SUCCESS;
}
return FAILURE;
} /* }}} */
static void php_phongo_cursor_iterator_get_current_key(zend_object_iterator* iter, zval* key TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* cursor = ((php_phongo_cursor_iterator*) iter)->cursor;
ZVAL_LONG(key, cursor->current);
} /* }}} */
#if PHP_VERSION_ID < 70000
static void php_phongo_cursor_iterator_get_current_data(zend_object_iterator* iter, zval*** data TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* cursor = ((php_phongo_cursor_iterator*) iter)->cursor;
*data = &cursor->visitor_data.zchild;
} /* }}} */
#else
static zval* php_phongo_cursor_iterator_get_current_data(zend_object_iterator* iter) /* {{{ */
{
php_phongo_cursor_t* cursor = ((php_phongo_cursor_iterator*) iter)->cursor;
return &cursor->visitor_data.zchild;
} /* }}} */
#endif
static void php_phongo_cursor_iterator_move_forward(zend_object_iterator* iter TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_iterator* cursor_it = (php_phongo_cursor_iterator*) iter;
php_phongo_cursor_t* cursor = cursor_it->cursor;
const bson_t* doc;
php_phongo_cursor_free_current(cursor);
/* If the cursor has already advanced, increment its position. Otherwise,
* the first call to mongoc_cursor_next() will be made below and we should
* leave its position at zero. */
if (cursor->advanced) {
cursor->current++;
} else {
cursor->advanced = true;
}
if (mongoc_cursor_next(cursor->cursor, &doc)) {
php_phongo_bson_to_zval_ex(bson_get_data(doc), doc->len, &cursor->visitor_data);
} else {
bson_error_t error = { 0 };
const bson_t* doc = NULL;
if (mongoc_cursor_error_document(cursor->cursor, &error, &doc)) {
/* Intentionally not destroying the cursor as it will happen
* naturally now that there are no more results */
phongo_throw_exception_from_bson_error_t_and_reply(&error, doc TSRMLS_CC);
}
}
php_phongo_cursor_free_session_if_exhausted(cursor);
} /* }}} */
static void php_phongo_cursor_iterator_rewind(zend_object_iterator* iter TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_iterator* cursor_it = (php_phongo_cursor_iterator*) iter;
php_phongo_cursor_t* cursor = cursor_it->cursor;
const bson_t* doc;
/* If the cursor was never advanced (e.g. command cursor), do so now */
if (!cursor->advanced) {
cursor->advanced = true;
if (!phongo_cursor_advance_and_check_for_error(cursor->cursor TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
}
if (cursor->current > 0) {
phongo_throw_exception(PHONGO_ERROR_LOGIC TSRMLS_CC, "Cursors cannot rewind after starting iteration");
return;
}
php_phongo_cursor_free_current(cursor);
doc = mongoc_cursor_current(cursor->cursor);
if (doc) {
php_phongo_bson_to_zval_ex(bson_get_data(doc), doc->len, &cursor->visitor_data);
}
php_phongo_cursor_free_session_if_exhausted(cursor);
} /* }}} */
static zend_object_iterator_funcs php_phongo_cursor_iterator_funcs = {
php_phongo_cursor_iterator_dtor,
php_phongo_cursor_iterator_valid,
php_phongo_cursor_iterator_get_current_data,
php_phongo_cursor_iterator_get_current_key,
php_phongo_cursor_iterator_move_forward,
php_phongo_cursor_iterator_rewind,
NULL /* invalidate_current is not used */
};
static zend_object_iterator* php_phongo_cursor_get_iterator(zend_class_entry* ce, zval* object, int by_ref TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_iterator* cursor_it = NULL;
php_phongo_cursor_t* cursor = Z_CURSOR_OBJ_P(object);
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
if (cursor->got_iterator) {
phongo_throw_exception(PHONGO_ERROR_LOGIC TSRMLS_CC, "Cursors cannot yield multiple iterators");
return NULL;
}
cursor->got_iterator = true;
cursor_it = ecalloc(1, sizeof(php_phongo_cursor_iterator));
#if PHP_VERSION_ID >= 70000
zend_iterator_init(&cursor_it->intern);
#endif
#if PHP_VERSION_ID >= 70000
ZVAL_COPY(&cursor_it->intern.data, object);
#else
Z_ADDREF_P(object);
cursor_it->intern.data = (void*) object;
#endif
cursor_it->intern.funcs = &php_phongo_cursor_iterator_funcs;
cursor_it->cursor = cursor;
/* cursor_it->current should already be allocated to zero */
php_phongo_cursor_free_current(cursor_it->cursor);
return &cursor_it->intern;
} /* }}} */
/* }}} */
/* {{{ proto void MongoDB\Driver\Cursor::setTypeMap(array $typemap)
Sets a type map to use for BSON unserialization */
static PHP_METHOD(Cursor, setTypeMap)
{
php_phongo_cursor_t* intern;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
zval* typemap = NULL;
bool restore_current_element = false;
intern = Z_CURSOR_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a!", &typemap) == FAILURE) {
return;
}
if (!php_phongo_bson_typemap_to_state(typemap, &state.map TSRMLS_CC)) {
return;
}
/* Check if the existing element needs to be freed before we overwrite
* visitor_data, which contains the only reference to it. */
if (!Z_ISUNDEF(intern->visitor_data.zchild)) {
php_phongo_cursor_free_current(intern);
restore_current_element = true;
}
php_phongo_bson_typemap_dtor(&intern->visitor_data.map);
intern->visitor_data = state;
/* If the cursor has a current element, we just freed it and should restore
* it with a new type map applied. */
if (restore_current_element && mongoc_cursor_current(intern->cursor)) {
const bson_t* doc = mongoc_cursor_current(intern->cursor);
php_phongo_bson_to_zval_ex(bson_get_data(doc), doc->len, &intern->visitor_data);
}
} /* }}} */
static int php_phongo_cursor_to_array_apply(zend_object_iterator* iter, void* puser TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* data;
zval* return_value = (zval*) puser;
data = iter->funcs->get_current_data(iter TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (Z_ISUNDEF_P(data)) {
return ZEND_HASH_APPLY_STOP;
}
Z_TRY_ADDREF_P(data);
add_next_index_zval(return_value, data);
#else
zval** data;
zval* return_value = (zval*) puser;
iter->funcs->get_current_data(iter, &data TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (data == NULL || *data == NULL) {
return ZEND_HASH_APPLY_STOP;
}
Z_ADDREF_PP(data);
add_next_index_zval(return_value, *data);
#endif
return ZEND_HASH_APPLY_KEEP;
} /* }}} */
/* {{{ proto array MongoDB\Driver\Cursor::toArray()
Returns an array of all result documents for this cursor */
static PHP_METHOD(Cursor, toArray)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
if (spl_iterator_apply(getThis(), php_phongo_cursor_to_array_apply, (void*) return_value TSRMLS_CC) != SUCCESS) {
zval_dtor(return_value);
RETURN_NULL();
}
} /* }}} */
/* {{{ proto MongoDB\Driver\CursorId MongoDB\Driver\Cursor::getId()
Returns the CursorId for this cursor */
static PHP_METHOD(Cursor, getId)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_cursor_id_new_from_id(return_value, mongoc_cursor_get_id(intern->cursor) TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Server MongoDB\Driver\Cursor::getServer()
Returns the Server object to which this cursor is attached */
static PHP_METHOD(Cursor, getServer)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phongo_server_init(return_value, intern->client, intern->server_id TSRMLS_CC);
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Cursor::isDead()
Checks if a cursor is still alive */
static PHP_METHOD(Cursor, isDead)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!mongoc_cursor_more(intern->cursor));
} /* }}} */
/* {{{ MongoDB\Driver\Cursor function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Cursor_setTypeMap, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, typemap, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Cursor_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_cursor_me[] = {
/* clang-format off */
PHP_ME(Cursor, setTypeMap, ai_Cursor_setTypeMap, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Cursor, toArray, ai_Cursor_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Cursor, getId, ai_Cursor_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Cursor, getServer, ai_Cursor_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Cursor, isDead, ai_Cursor_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Cursor_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Cursor_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Cursor object handlers */
static zend_object_handlers php_phongo_handler_cursor;
static void php_phongo_cursor_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* intern = Z_OBJ_CURSOR(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->cursor) {
mongoc_cursor_destroy(intern->cursor);
}
if (intern->database) {
efree(intern->database);
}
if (intern->collection) {
efree(intern->collection);
}
if (!Z_ISUNDEF(intern->query)) {
zval_ptr_dtor(&intern->query);
}
if (!Z_ISUNDEF(intern->command)) {
zval_ptr_dtor(&intern->command);
}
if (!Z_ISUNDEF(intern->read_preference)) {
zval_ptr_dtor(&intern->read_preference);
}
if (!Z_ISUNDEF(intern->session)) {
zval_ptr_dtor(&intern->session);
}
php_phongo_bson_typemap_dtor(&intern->visitor_data.map);
php_phongo_cursor_free_current(intern);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_cursor_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_cursor_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_cursor;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_cursor_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_cursor;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_cursor_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_cursor_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_CURSOR_OBJ_P(object);
array_init_size(&retval, 10);
if (intern->database) {
ADD_ASSOC_STRING(&retval, "database", intern->database);
} else {
ADD_ASSOC_NULL_EX(&retval, "database");
}
if (intern->collection) {
ADD_ASSOC_STRING(&retval, "collection", intern->collection);
} else {
ADD_ASSOC_NULL_EX(&retval, "collection");
}
if (!Z_ISUNDEF(intern->query)) {
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "query", &intern->query);
Z_ADDREF(intern->query);
#else
ADD_ASSOC_ZVAL_EX(&retval, "query", intern->query);
Z_ADDREF_P(intern->query);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "query");
}
if (!Z_ISUNDEF(intern->command)) {
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "command", &intern->command);
Z_ADDREF(intern->command);
#else
ADD_ASSOC_ZVAL_EX(&retval, "command", intern->command);
Z_ADDREF_P(intern->command);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "command");
}
if (!Z_ISUNDEF(intern->read_preference)) {
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "readPreference", &intern->read_preference);
Z_ADDREF(intern->read_preference);
#else
ADD_ASSOC_ZVAL_EX(&retval, "readPreference", intern->read_preference);
Z_ADDREF_P(intern->read_preference);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "readPreference");
}
if (!Z_ISUNDEF(intern->session)) {
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "session", &intern->session);
Z_ADDREF(intern->session);
#else
ADD_ASSOC_ZVAL_EX(&retval, "session", intern->session);
Z_ADDREF_P(intern->session);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "session");
}
ADD_ASSOC_BOOL_EX(&retval, "isDead", !mongoc_cursor_more(intern->cursor));
ADD_ASSOC_LONG_EX(&retval, "currentIndex", intern->current);
if (!Z_ISUNDEF(intern->visitor_data.zchild)) {
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "currentDocument", &intern->visitor_data.zchild);
Z_ADDREF(intern->visitor_data.zchild);
#else
ADD_ASSOC_ZVAL_EX(&retval, "currentDocument", intern->visitor_data.zchild);
Z_ADDREF_P(intern->visitor_data.zchild);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "currentDocument");
}
{
#if PHP_VERSION_ID >= 70000
zval server;
phongo_server_init(&server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
#else
zval* server = NULL;
MAKE_STD_ZVAL(server);
phongo_server_init(server, intern->client, intern->server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", server);
#endif
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_cursor_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Cursor", php_phongo_cursor_me);
php_phongo_cursor_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_cursor_ce->create_object = php_phongo_cursor_create_object;
PHONGO_CE_FINAL(php_phongo_cursor_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_cursor_ce);
php_phongo_cursor_ce->get_iterator = php_phongo_cursor_get_iterator;
zend_class_implements(php_phongo_cursor_ce TSRMLS_CC, 1, php_phongo_cursor_interface_ce);
memcpy(&php_phongo_handler_cursor, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_cursor.get_debug_info = php_phongo_cursor_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_cursor.free_obj = php_phongo_cursor_free_object;
php_phongo_handler_cursor.offset = XtOffsetOf(php_phongo_cursor_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/CursorId.c 0000644 0000765 0000024 00000010525 13572250757 016436 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_cursorid_ce;
/* {{{ proto string MongoDB\Driver\CursorId::__toString()
Returns the string representation of the CursorId */
static PHP_METHOD(CursorId, __toString)
{
php_phongo_cursorid_t* intern;
char* tmp;
int tmp_len;
intern = Z_CURSORID_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
tmp_len = spprintf(&tmp, 0, "%" PRId64, intern->id);
PHONGO_RETVAL_STRINGL(tmp, tmp_len);
efree(tmp);
} /* }}} */
/* {{{ MongoDB\Driver\CursorId function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CursorId_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_cursorid_me[] = {
/* clang-format off */
PHP_ME(CursorId, __toString, ai_CursorId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_CursorId_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_CursorId_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\CursorId object handlers */
static zend_object_handlers php_phongo_handler_cursorid;
static void php_phongo_cursorid_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_cursorid_t* intern = Z_OBJ_CURSORID(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_cursorid_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_cursorid_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_cursorid_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_cursorid;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_cursorid_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_cursorid;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_cursorid_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_cursorid_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_CURSORID_OBJ_P(object);
array_init(&retval);
#if SIZEOF_LONG == 4
{
char tmp[24];
int tmp_len;
tmp_len = snprintf(tmp, sizeof(tmp), "%" PRId64, intern->id);
ADD_ASSOC_STRINGL(&retval, "id", tmp, tmp_len);
}
#else
ADD_ASSOC_LONG_EX(&retval, "id", intern->id);
#endif
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_cursorid_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "CursorId", php_phongo_cursorid_me);
php_phongo_cursorid_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_cursorid_ce->create_object = php_phongo_cursorid_create_object;
PHONGO_CE_FINAL(php_phongo_cursorid_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_cursorid_ce);
memcpy(&php_phongo_handler_cursorid, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_cursorid.get_debug_info = php_phongo_cursorid_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_cursorid.free_obj = php_phongo_cursorid_free_object;
php_phongo_handler_cursorid.offset = XtOffsetOf(php_phongo_cursorid_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/CursorInterface.c 0000644 0000765 0000024 00000004007 13572250757 020000 0 ustar alcaeus staff /*
* Copyright 2018 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_cursor_interface_ce;
/* {{{ MongoDB\BSON\CursorInterface function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_CursorInterface_setTypeMap, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, typemap, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_CursorInterface_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_cursor_interface_me[] = {
/* clang-format off */
ZEND_ABSTRACT_ME(CursorInterface, getId, ai_CursorInterface_void)
ZEND_ABSTRACT_ME(CursorInterface, getServer, ai_CursorInterface_void)
ZEND_ABSTRACT_ME(CursorInterface, isDead, ai_CursorInterface_void)
ZEND_ABSTRACT_ME(CursorInterface, setTypeMap, ai_CursorInterface_setTypeMap)
ZEND_ABSTRACT_ME(CursorInterface, toArray, ai_CursorInterface_void)
PHP_FE_END
/* clang-format on */
};
/* }}} */
void php_phongo_cursor_interface_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "CursorInterface", php_phongo_cursor_interface_me);
php_phongo_cursor_interface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
zend_class_implements(php_phongo_cursor_interface_ce TSRMLS_CC, 1, zend_ce_traversable);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Manager.c 0000644 0000765 0000024 00000074201 13572250757 016257 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "Session.h"
#define PHONGO_MANAGER_URI_DEFAULT "mongodb://127.0.0.1/"
/**
* Manager abstracts a cluster of Server objects (i.e. socket connections).
*
* Typically, users will connect to a cluster using a URI, and the Manager will
* perform tasks such as replica set discovery and create the necessary Server
* objects. That said, it is also possible to create a Manager with an arbitrary
* collection of Server objects using the static factory method (this can be
* useful for testing or administration).
*
* Operation methods do not take socket-level options (e.g. socketTimeoutMS).
* Those options should be specified during construction.
*/
zend_class_entry* php_phongo_manager_ce;
/* Checks if driverOptions contains a stream context resource in the "context"
* key and incorporates any of its SSL options into the base array that did not
* already exist (i.e. array union). The "context" key is then unset from the
* base array.
*
* This handles the merging of any legacy SSL context options and also makes
* driverOptions suitable for serialization by removing the resource zval. */
static bool php_phongo_manager_merge_context_options(zval* zdriverOptions TSRMLS_DC) /* {{{ */
{
php_stream_context* context;
zval * zcontext, *zcontextOptions;
if (!php_array_existsc(zdriverOptions, "context")) {
return true;
}
zcontext = php_array_fetchc(zdriverOptions, "context");
context = php_stream_context_from_zval(zcontext, 1);
if (!context) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "\"context\" driver option is not a valid Stream-Context resource");
return false;
}
#if PHP_VERSION_ID >= 70000
zcontextOptions = php_array_fetchc_array(&context->options, "ssl");
#else
zcontextOptions = php_array_fetchc_array(context->options, "ssl");
#endif
if (!zcontextOptions) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Stream-Context resource does not contain \"ssl\" options array");
return false;
}
/* Perform array union (see: add_function() in zend_operators.c) */
#if PHP_VERSION_ID >= 70000
zend_hash_merge(Z_ARRVAL_P(zdriverOptions), Z_ARRVAL_P(zcontextOptions), zval_add_ref, 0);
#else
{
zval* tmp;
zend_hash_merge(Z_ARRVAL_P(zdriverOptions), Z_ARRVAL_P(zcontextOptions), (void (*)(void* pData)) zval_add_ref, (void*) &tmp, sizeof(zval*), 0);
}
#endif
php_array_unsetc(zdriverOptions, "context");
return true;
} /* }}} */
/* Prepare authMechanismProperties for BSON encoding by converting a boolean
* value for the "CANONICALIZE_HOST_NAME" option to a string.
*
* Note: URI options are case-insensitive, so we must iterate through the
* HashTable in order to detect options. */
static void php_phongo_manager_prep_authmechanismproperties(zval* properties TSRMLS_DC) /* {{{ */
{
HashTable* ht_data;
if (Z_TYPE_P(properties) != IS_ARRAY && Z_TYPE_P(properties) != IS_OBJECT) {
return;
}
ht_data = HASH_OF(properties);
#if PHP_VERSION_ID >= 70000
{
zend_string* string_key = NULL;
zend_ulong num_key = 0;
zval* property;
ZEND_HASH_FOREACH_KEY_VAL(ht_data, num_key, string_key, property)
{
if (!string_key) {
continue;
}
/* URI options are case-insensitive */
if (!strcasecmp(ZSTR_VAL(string_key), "CANONICALIZE_HOST_NAME")) {
ZVAL_DEREF(property);
if (Z_TYPE_P(property) != IS_STRING && zend_is_true(property)) {
SEPARATE_ZVAL_NOREF(property);
ZVAL_NEW_STR(property, zend_string_init(ZEND_STRL("true"), 0));
}
}
}
ZEND_HASH_FOREACH_END();
}
#else
{
HashPosition pos;
zval** property;
for (
zend_hash_internal_pointer_reset_ex(ht_data, &pos);
zend_hash_get_current_data_ex(ht_data, (void**) &property, &pos) == SUCCESS;
zend_hash_move_forward_ex(ht_data, &pos)) {
char* string_key = NULL;
uint string_key_len = 0;
ulong num_key = 0;
if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(ht_data, &string_key, &string_key_len, &num_key, 0, &pos)) {
continue;
}
/* URI options are case-insensitive */
if (!strcasecmp(string_key, "CANONICALIZE_HOST_NAME")) {
if (Z_TYPE_PP(property) != IS_STRING && zend_is_true(*property)) {
SEPARATE_ZVAL_IF_NOT_REF(property);
Z_TYPE_PP(property) = IS_STRING;
Z_STRVAL_PP(property) = estrndup("true", sizeof("true") - 1);
Z_STRLEN_PP(property) = sizeof("true") - 1;
}
}
}
}
#endif /* PHP_VERSION_ID >= 70000 */
return;
} /* }}} */
/* Prepare URI options for BSON encoding.
*
* Read preference tag sets must be an array of documents. In order to ensure
* that empty arrays serialize as empty documents, array elements will be
* converted to objects. php_phongo_read_preference_tags_are_valid() handles
* actual validation of the tag set structure.
*
* Auth mechanism properties must have string values, so a boolean true value
* for the "CANONICALIZE_HOST_NAME" property will be converted to "true".
*
* Note: URI options are case-insensitive, so we must iterate through the
* HashTable in order to detect options. */
static void php_phongo_manager_prep_uri_options(zval* options TSRMLS_DC) /* {{{ */
{
HashTable* ht_data;
if (Z_TYPE_P(options) != IS_ARRAY) {
return;
}
ht_data = HASH_OF(options);
#if PHP_VERSION_ID >= 70000
{
zend_string* string_key = NULL;
zend_ulong num_key = 0;
zval* option;
ZEND_HASH_FOREACH_KEY_VAL(ht_data, num_key, string_key, option)
{
if (!string_key) {
continue;
}
if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_READPREFERENCETAGS)) {
ZVAL_DEREF(option);
SEPARATE_ZVAL_NOREF(option);
php_phongo_read_preference_prep_tagsets(option TSRMLS_CC);
continue;
}
if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_AUTHMECHANISMPROPERTIES)) {
ZVAL_DEREF(option);
SEPARATE_ZVAL_NOREF(option);
php_phongo_manager_prep_authmechanismproperties(option TSRMLS_CC);
continue;
}
}
ZEND_HASH_FOREACH_END();
}
#else
{
HashPosition pos;
zval** option;
for (
zend_hash_internal_pointer_reset_ex(ht_data, &pos);
zend_hash_get_current_data_ex(ht_data, (void**) &option, &pos) == SUCCESS;
zend_hash_move_forward_ex(ht_data, &pos)) {
char* string_key = NULL;
uint string_key_len = 0;
ulong num_key = 0;
if (HASH_KEY_IS_STRING != zend_hash_get_current_key_ex(ht_data, &string_key, &string_key_len, &num_key, 0, &pos)) {
continue;
}
if (!strcasecmp(string_key, MONGOC_URI_READPREFERENCETAGS)) {
SEPARATE_ZVAL_IF_NOT_REF(option);
php_phongo_read_preference_prep_tagsets(*option TSRMLS_CC);
continue;
}
if (!strcasecmp(string_key, MONGOC_URI_AUTHMECHANISMPROPERTIES)) {
SEPARATE_ZVAL_IF_NOT_REF(option);
php_phongo_manager_prep_authmechanismproperties(*option TSRMLS_CC);
continue;
}
}
}
#endif
return;
} /* }}} */
/* Selects a server for an execute method. If "for_writes" is true, a primary
* will be selected. Otherwise, a read preference will be used to select the
* server. If zreadPreference is NULL, the client's read preference will be
* used. If zsession is a session object in a sharded transaction, the session
* will be checked whether it is pinned to a server. If so, that server will be
* selected. Otherwise, server selection
*
* On success, server_id will be set and the function will return true;
* otherwise, false is returned and an exception is thrown. */
static bool php_phongo_manager_select_server(bool for_writes, zval* zreadPreference, zval* zsession, mongoc_client_t* client, uint32_t* server_id TSRMLS_DC) /* {{{ */
{
mongoc_server_description_t* selected_server;
const mongoc_read_prefs_t* read_preference = NULL;
bson_error_t error = { 0 };
if (zsession) {
const mongoc_client_session_t* session = Z_SESSION_OBJ_P(zsession)->client_session;
/* Attempt to fetch server pinned to session */
if (mongoc_client_session_get_server_id(session) > 0) {
*server_id = mongoc_client_session_get_server_id(session);
return true;
}
}
if (!for_writes) {
read_preference = zreadPreference ? phongo_read_preference_from_zval(zreadPreference TSRMLS_CC) : mongoc_client_get_read_prefs(client);
}
selected_server = mongoc_client_select_server(client, for_writes, read_preference, &error);
if (selected_server) {
*server_id = mongoc_server_description_id(selected_server);
mongoc_server_description_destroy(selected_server);
return true;
}
/* Check for connection related exceptions */
if (!EG(exception)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
}
return false;
} /* }}} */
/* {{{ proto void MongoDB\Driver\Manager::__construct([string $uri = "mongodb://127.0.0.1/"[, array $options = array()[, array $driverOptions = array()]]])
Constructs a new Manager */
static PHP_METHOD(Manager, __construct)
{
php_phongo_manager_t* intern;
zend_error_handling error_handling;
char* uri_string = NULL;
phongo_zpp_char_len uri_string_len = 0;
zval* options = NULL;
zval* driverOptions = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_MANAGER_OBJ_P(getThis());
/* Separate the options and driverOptions zvals, since we may end up
* modifying them in php_phongo_manager_prep_uri_options() and
* php_phongo_manager_merge_context_options() below, respectively. */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!a/!a/!", &uri_string, &uri_string_len, &options, &driverOptions) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (options) {
php_phongo_manager_prep_uri_options(options TSRMLS_CC);
}
if (driverOptions && !php_phongo_manager_merge_context_options(driverOptions TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
phongo_manager_init(intern, uri_string ? uri_string : PHONGO_MANAGER_URI_DEFAULT, options, driverOptions TSRMLS_CC);
if (intern->client) {
php_phongo_set_monitoring_callbacks(intern->client);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
Execute a Command */
static PHP_METHOD(Manager, executeCommand)
{
php_phongo_manager_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
bool free_options = false;
zval* zreadPreference = NULL;
zval* zsession = NULL;
uint32_t server_id = 0;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
options = php_phongo_prep_legacy_option(options, "readPreference", &free_options TSRMLS_CC);
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
if (!phongo_parse_read_preference(options, &zreadPreference TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
if (!php_phongo_manager_select_server(false, zreadPreference, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_RAW, db, command, options, server_id, return_value, return_value_used TSRMLS_CC);
cleanup:
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
Execute a ReadCommand */
static PHP_METHOD(Manager, executeReadCommand)
{
php_phongo_manager_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
if (!phongo_parse_read_preference(options, &zreadPreference TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(false, zreadPreference, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_READ, db, command, options, server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
Execute a WriteCommand */
static PHP_METHOD(Manager, executeWriteCommand)
{
php_phongo_manager_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, NULL, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_WRITE, db, command, options, server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeReadWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null])
Execute a ReadWriteCommand */
static PHP_METHOD(Manager, executeReadWriteCommand)
{
php_phongo_manager_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, NULL, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_READ_WRITE, db, command, options, server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeQuery(string $namespace, MongoDB\Driver\Query $query[, array $options = null])
Execute a Query */
static PHP_METHOD(Manager, executeQuery)
{
php_phongo_manager_t* intern;
char* namespace;
phongo_zpp_char_len namespace_len;
zval* query;
zval* options = NULL;
bool free_options = false;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &namespace, &namespace_len, &query, php_phongo_query_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
options = php_phongo_prep_legacy_option(options, "readPreference", &free_options TSRMLS_CC);
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
if (!phongo_parse_read_preference(options, &zreadPreference TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
if (!php_phongo_manager_select_server(false, zreadPreference, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
phongo_execute_query(intern->client, namespace, query, options, server_id, return_value, return_value_used TSRMLS_CC);
cleanup:
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\WriteResult MongoDB\Driver\Manager::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $zbulk[, array $options = null])
Executes a BulkWrite (i.e. any number of insert, update, and delete ops) */
static PHP_METHOD(Manager, executeBulkWrite)
{
php_phongo_manager_t* intern;
char* namespace;
phongo_zpp_char_len namespace_len;
zval* zbulk;
php_phongo_bulkwrite_t* bulk;
zval* options = NULL;
bool free_options = false;
uint32_t server_id = 0;
zval* zsession = NULL;
DECLARE_RETURN_VALUE_USED
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &namespace, &namespace_len, &zbulk, php_phongo_bulkwrite_ce, &options) == FAILURE) {
return;
}
intern = Z_MANAGER_OBJ_P(getThis());
bulk = Z_BULKWRITE_OBJ_P(zbulk);
options = php_phongo_prep_legacy_option(options, "writeConcern", &free_options TSRMLS_CC);
if (!phongo_parse_session(options, intern->client, NULL, &zsession TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, NULL, zsession, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
goto cleanup;
}
phongo_execute_bulk_write(intern->client, namespace, bulk, options, server_id, return_value, return_value_used TSRMLS_CC);
cleanup:
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\ReadConcern MongoDB\Driver\Manager::getReadConcern()
Returns the ReadConcern associated with this Manager */
static PHP_METHOD(Manager, getReadConcern)
{
php_phongo_manager_t* intern;
DECLARE_RETURN_VALUE_USED
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (return_value_used) {
phongo_readconcern_init(return_value, mongoc_client_get_read_concern(intern->client) TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\ReadPreference MongoDB\Driver\Manager::getReadPreference()
Returns the ReadPreference associated with this Manager */
static PHP_METHOD(Manager, getReadPreference)
{
php_phongo_manager_t* intern;
DECLARE_RETURN_VALUE_USED
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (return_value_used) {
phongo_readpreference_init(return_value, mongoc_client_get_read_prefs(intern->client) TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\Server[] MongoDB\Driver\Manager::getServers()
Returns the Servers associated with this Manager */
static PHP_METHOD(Manager, getServers)
{
php_phongo_manager_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
sds = mongoc_client_get_server_descriptions(intern->client, &n);
array_init_size(return_value, n);
for (i = 0; i < n; i++) {
#if PHP_VERSION_ID >= 70000
zval obj;
phongo_server_init(&obj, intern->client, mongoc_server_description_id(sds[i]) TSRMLS_CC);
add_next_index_zval(return_value, &obj);
#else
zval* obj = NULL;
MAKE_STD_ZVAL(obj);
phongo_server_init(obj, intern->client, mongoc_server_description_id(sds[i]) TSRMLS_CC);
add_next_index_zval(return_value, obj);
#endif
}
mongoc_server_descriptions_destroy_all(sds, n);
} /* }}} */
/* {{{ proto MongoDB\Driver\WriteConcern MongoDB\Driver\Manager::getWriteConcern()
Returns the WriteConcern associated with this Manager */
static PHP_METHOD(Manager, getWriteConcern)
{
php_phongo_manager_t* intern;
DECLARE_RETURN_VALUE_USED
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (return_value_used) {
phongo_writeconcern_init(return_value, mongoc_client_get_write_concern(intern->client) TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\Server MongoDB\Driver\Manager::selectServers(MongoDB\Driver\ReadPreference $readPreference)
Returns a suitable Server for the given ReadPreference */
static PHP_METHOD(Manager, selectServer)
{
php_phongo_manager_t* intern;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &zreadPreference, php_phongo_readpreference_ce) == FAILURE) {
return;
}
if (!php_phongo_manager_select_server(false, zreadPreference, NULL, intern->client, &server_id TSRMLS_CC)) {
/* Exception should already have been thrown */
return;
}
phongo_server_init(return_value, intern->client, server_id TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Session MongoDB\Driver\Manager::startSession([array $options = null])
Returns a new client session */
static PHP_METHOD(Manager, startSession)
{
php_phongo_manager_t* intern;
zval* options = NULL;
mongoc_session_opt_t* cs_opts = NULL;
mongoc_client_session_t* cs;
bson_error_t error = { 0 };
mongoc_transaction_opt_t* txn_opts = NULL;
intern = Z_MANAGER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &options) == FAILURE) {
return;
}
if (options && php_array_existsc(options, "causalConsistency")) {
cs_opts = mongoc_session_opts_new();
mongoc_session_opts_set_causal_consistency(cs_opts, php_array_fetchc_bool(options, "causalConsistency"));
}
if (options && php_array_existsc(options, "defaultTransactionOptions")) {
zval* txn_options = php_array_fetchc(options, "defaultTransactionOptions");
/* Thrown exception and return if the defaultTransactionOptions is not an array */
if (Z_TYPE_P(txn_options) != IS_ARRAY) {
phongo_throw_exception(
PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC,
"Expected \"defaultTransactionOptions\" option to be an array, %s given",
PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(txn_options));
goto cleanup;
}
/* Parse transaction options */
txn_opts = php_mongodb_session_parse_transaction_options(txn_options TSRMLS_CC);
/* If an exception is thrown while parsing, the txn_opts struct is also
* NULL, so no need to free it here */
if (EG(exception)) {
goto cleanup;
}
/* If the options are non-empty, add them to the client session opts struct */
if (txn_opts) {
if (!cs_opts) {
cs_opts = mongoc_session_opts_new();
}
mongoc_session_opts_set_default_transaction_opts(cs_opts, txn_opts);
mongoc_transaction_opts_destroy(txn_opts);
}
}
cs = mongoc_client_start_session(intern->client, cs_opts, &error);
if (cs) {
phongo_session_init(return_value, cs TSRMLS_CC);
} else {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
}
cleanup:
if (cs_opts) {
mongoc_session_opts_destroy(cs_opts);
}
} /* }}} */
/* {{{ MongoDB\Driver\Manager function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Manager___construct, 0, 0, 0)
ZEND_ARG_INFO(0, uri)
ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_ARG_ARRAY_INFO(0, driverOptions, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeCommand, 0, 0, 2)
ZEND_ARG_INFO(0, db)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeRWCommand, 0, 0, 2)
ZEND_ARG_INFO(0, db)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeQuery, 0, 0, 2)
ZEND_ARG_INFO(0, namespace)
ZEND_ARG_OBJ_INFO(0, zquery, MongoDB\\Driver\\Query, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_executeBulkWrite, 0, 0, 2)
ZEND_ARG_INFO(0, namespace)
ZEND_ARG_OBJ_INFO(0, zbulk, MongoDB\\Driver\\BulkWrite, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_selectServer, 0, 0, 1)
ZEND_ARG_OBJ_INFO(0, readPreference, MongoDB\\Driver\\ReadPreference, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_startSession, 0, 0, 0)
ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Manager_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_manager_me[] = {
/* clang-format off */
PHP_ME(Manager, __construct, ai_Manager___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeCommand, ai_Manager_executeCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeReadCommand, ai_Manager_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeWriteCommand, ai_Manager_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeReadWriteCommand, ai_Manager_executeCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeQuery, ai_Manager_executeQuery, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, executeBulkWrite, ai_Manager_executeBulkWrite, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, getReadConcern, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, getReadPreference, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, getServers, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, getWriteConcern, ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, selectServer, ai_Manager_selectServer, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Manager, startSession, ai_Manager_startSession, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Manager_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Manager object handlers */
static zend_object_handlers php_phongo_handler_manager;
static void php_phongo_manager_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_manager_t* intern = Z_OBJ_MANAGER(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->client) {
MONGOC_DEBUG("Not destroying persistent client for Manager");
intern->client = NULL;
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_manager_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_manager_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_manager_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_manager;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_manager_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_manager;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_manager_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_manager_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
zval retval = ZVAL_STATIC_INIT;
ZVAL_RETVAL_TYPE cluster;
*is_temp = 1;
intern = Z_MANAGER_OBJ_P(object);
array_init_size(&retval, 2);
ADD_ASSOC_STRING(&retval, "uri", mongoc_uri_get_string(mongoc_client_get_uri(intern->client)));
sds = mongoc_client_get_server_descriptions(intern->client, &n);
#if PHP_VERSION_ID >= 70000
array_init_size(&cluster, n);
for (i = 0; i < n; i++) {
zval obj;
php_phongo_server_to_zval(&obj, sds[i]);
add_next_index_zval(&cluster, &obj);
}
ADD_ASSOC_ZVAL_EX(&retval, "cluster", &cluster);
#else
MAKE_STD_ZVAL(cluster);
array_init_size(cluster, n);
for (i = 0; i < n; i++) {
zval* obj = NULL;
MAKE_STD_ZVAL(obj);
php_phongo_server_to_zval(obj, sds[i]);
add_next_index_zval(cluster, obj);
}
ADD_ASSOC_ZVAL_EX(&retval, "cluster", cluster);
#endif
mongoc_server_descriptions_destroy_all(sds, n);
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_manager_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Manager", php_phongo_manager_me);
php_phongo_manager_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_manager_ce->create_object = php_phongo_manager_create_object;
PHONGO_CE_FINAL(php_phongo_manager_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_manager_ce);
memcpy(&php_phongo_handler_manager, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_manager.get_debug_info = php_phongo_manager_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_manager.free_obj = php_phongo_manager_free_object;
php_phongo_handler_manager.offset = XtOffsetOf(php_phongo_manager_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Query.c 0000644 0000765 0000024 00000051120 13572250757 016005 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_query_ce;
/* Appends a string field into the BSON options. Returns true on success;
* otherwise, false is returned and an exception is thrown. */
static bool php_phongo_query_opts_append_string(bson_t* opts, const char* opts_key, zval* zarr, const char* zarr_key TSRMLS_DC) /* {{{ */
{
zval* value = php_array_fetch(zarr, zarr_key);
if (Z_TYPE_P(value) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"%s\" %s to be string, %s given", zarr_key, zarr_key[0] == '$' ? "modifier" : "option", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(value));
return false;
}
if (!bson_append_utf8(opts, opts_key, strlen(opts_key), Z_STRVAL_P(value), Z_STRLEN_P(value))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", opts_key);
return false;
}
return true;
} /* }}} */
/* Appends a document field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_query_opts_append_document(bson_t* opts, const char* opts_key, zval* zarr, const char* zarr_key TSRMLS_DC) /* {{{ */
{
zval* value = php_array_fetch(zarr, zarr_key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"%s\" %s to be array or object, %s given", zarr_key, zarr_key[0] == '$' ? "modifier" : "option", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(value));
return false;
}
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, &b, NULL TSRMLS_CC);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!bson_validate(&b, BSON_VALIDATE_EMPTY_KEYS, NULL)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Cannot use empty keys in \"%s\" %s", zarr_key, zarr_key[0] == '$' ? "modifier" : "option");
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_DOCUMENT(opts, opts_key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", opts_key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
} /* }}} */
#define PHONGO_QUERY_OPT_BOOL_EX(opt, zarr, key, deprecated) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if ((deprecated)) { \
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The \"%s\" option is deprecated and will be removed in a future release", key); \
} \
if (!BSON_APPEND_BOOL(intern->opts, (opt), php_array_fetchc_bool((zarr), (key)))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", (opt)); \
return false; \
} \
}
#define PHONGO_QUERY_OPT_BOOL(opt, zarr, key) PHONGO_QUERY_OPT_BOOL_EX((opt), (zarr), (key), 0)
#define PHONGO_QUERY_OPT_BOOL_DEPRECATED(opt, zarr, key) PHONGO_QUERY_OPT_BOOL_EX((opt), (zarr), (key), 1)
#define PHONGO_QUERY_OPT_DOCUMENT(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!php_phongo_query_opts_append_document(intern->opts, (opt), (zarr), (key) TSRMLS_CC)) { \
return false; \
} \
}
/* Note: handling of integer options will depend on SIZEOF_ZEND_LONG and we
* are not converting strings to 64-bit integers for 32-bit platforms. */
#define PHONGO_QUERY_OPT_INT64_EX(opt, zarr, key, deprecated) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if ((deprecated)) { \
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The \"%s\" option is deprecated and will be removed in a future release", key); \
} \
if (!BSON_APPEND_INT64(intern->opts, (opt), php_array_fetchc_long((zarr), (key)))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"%s\" option", (opt)); \
return false; \
} \
}
#define PHONGO_QUERY_OPT_INT64(opt, zarr, key) PHONGO_QUERY_OPT_INT64_EX((opt), (zarr), (key), 0)
#define PHONGO_QUERY_OPT_INT64_DEPRECATED(opt, zarr, key) PHONGO_QUERY_OPT_INT64_EX((opt), (zarr), (key), 1)
#define PHONGO_QUERY_OPT_STRING(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!php_phongo_query_opts_append_string(intern->opts, (opt), (zarr), (key) TSRMLS_CC)) { \
return false; \
} \
}
/* Initialize the "hint" option. Returns true on success; otherwise, false is
* returned and an exception is thrown.
*
* The "hint" option (or "$hint" modifier) must be a string or document. Check
* for both types and merge into BSON options accordingly. */
static bool php_phongo_query_init_hint(php_phongo_query_t* intern, zval* options, zval* modifiers TSRMLS_DC) /* {{{ */
{
/* The "hint" option (or "$hint" modifier) must be a string or document.
* Check for both types and merge into BSON options accordingly. */
if (php_array_existsc(options, "hint")) {
zend_uchar type = Z_TYPE_P(php_array_fetchc(options, "hint"));
if (type == IS_STRING) {
PHONGO_QUERY_OPT_STRING("hint", options, "hint");
} else if (type == IS_OBJECT || type == IS_ARRAY) {
PHONGO_QUERY_OPT_DOCUMENT("hint", options, "hint");
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"hint\" option to be string, array, or object, %s given", zend_get_type_by_const(type));
return false;
}
} else if (modifiers && php_array_existsc(modifiers, "$hint")) {
zend_uchar type = Z_TYPE_P(php_array_fetchc(modifiers, "$hint"));
if (type == IS_STRING) {
PHONGO_QUERY_OPT_STRING("hint", modifiers, "$hint");
} else if (type == IS_OBJECT || type == IS_ARRAY) {
PHONGO_QUERY_OPT_DOCUMENT("hint", modifiers, "$hint");
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"$hint\" modifier to be string, array, or object, %s given", zend_get_type_by_const(type));
return false;
}
}
return true;
} /* }}} */
/* Initialize the "limit" and "singleBatch" options. Returns true on success;
* otherwise, false is returned and an exception is thrown.
*
* mongoc_collection_find_with_opts() requires a non-negative limit. For
* backwards compatibility, a negative limit should be set as a positive value
* and default singleBatch to true. */
static bool php_phongo_query_init_limit_and_singlebatch(php_phongo_query_t* intern, zval* options TSRMLS_DC) /* {{{ */
{
if (php_array_existsc(options, "limit") && php_array_fetchc_long(options, "limit") < 0) {
phongo_long limit = php_array_fetchc_long(options, "limit");
if (!BSON_APPEND_INT64(intern->opts, "limit", -limit)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"limit\" option");
return false;
}
if (php_array_existsc(options, "singleBatch") && !php_array_fetchc_bool(options, "singleBatch")) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Negative \"limit\" option conflicts with false \"singleBatch\" option");
return false;
} else {
if (!BSON_APPEND_BOOL(intern->opts, "singleBatch", true)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Error appending \"singleBatch\" option");
return false;
}
}
} else {
PHONGO_QUERY_OPT_INT64("limit", options, "limit");
PHONGO_QUERY_OPT_BOOL("singleBatch", options, "singleBatch");
}
return true;
} /* }}} */
/* Initialize the "readConcern" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "readConcern" option should be a MongoDB\Driver\ReadConcern instance,
* which must be converted to a mongoc_read_concern_t. */
static bool php_phongo_query_init_readconcern(php_phongo_query_t* intern, zval* options TSRMLS_DC) /* {{{ */
{
if (php_array_existsc(options, "readConcern")) {
zval* read_concern = php_array_fetchc(options, "readConcern");
if (Z_TYPE_P(read_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_concern), php_phongo_readconcern_ce TSRMLS_CC)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_readconcern_ce->name), PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(read_concern));
return false;
}
intern->read_concern = mongoc_read_concern_copy(phongo_read_concern_from_zval(read_concern TSRMLS_CC));
}
return true;
} /* }}} */
/* Initialize the "maxAwaitTimeMS" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "maxAwaitTimeMS" option is assigned to the cursor after query execution
* via mongoc_cursor_set_max_await_time_ms(). */
static bool php_phongo_query_init_max_await_time_ms(php_phongo_query_t* intern, zval* options TSRMLS_DC) /* {{{ */
{
if (php_array_existsc(options, "maxAwaitTimeMS")) {
int64_t max_await_time_ms = php_array_fetchc_long(options, "maxAwaitTimeMS");
if (max_await_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxAwaitTimeMS\" option to be >= 0, %" PRId64 " given", max_await_time_ms);
return false;
}
if (max_await_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxAwaitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_await_time_ms);
return false;
}
intern->max_await_time_ms = (uint32_t) max_await_time_ms;
}
return true;
} /* }}} */
/* Initializes the php_phongo_query_t from filter and options arguments. This
* function will fall back to a modifier in the absence of a top-level option
* (where applicable). */
static bool php_phongo_query_init(php_phongo_query_t* intern, zval* filter, zval* options TSRMLS_DC) /* {{{ */
{
zval* modifiers = NULL;
intern->filter = bson_new();
intern->opts = bson_new();
php_phongo_zval_to_bson(filter, PHONGO_BSON_NONE, intern->filter, NULL TSRMLS_CC);
/* Note: if any exceptions are thrown, we can simply return as PHP will
* invoke php_phongo_query_free_object to destruct the object. */
if (EG(exception)) {
return false;
}
if (!bson_validate(intern->filter, BSON_VALIDATE_EMPTY_KEYS, NULL)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Cannot use empty keys in filter document");
return false;
}
if (!options) {
return true;
}
if (php_array_existsc(options, "modifiers")) {
modifiers = php_array_fetchc(options, "modifiers");
if (Z_TYPE_P(modifiers) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"modifiers\" option to be array, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(modifiers));
return false;
}
}
PHONGO_QUERY_OPT_BOOL("allowPartialResults", options, "allowPartialResults")
else PHONGO_QUERY_OPT_BOOL("allowPartialResults", options, "partial");
PHONGO_QUERY_OPT_BOOL("awaitData", options, "awaitData");
PHONGO_QUERY_OPT_INT64("batchSize", options, "batchSize");
PHONGO_QUERY_OPT_DOCUMENT("collation", options, "collation");
PHONGO_QUERY_OPT_STRING("comment", options, "comment")
else PHONGO_QUERY_OPT_STRING("comment", modifiers, "$comment");
PHONGO_QUERY_OPT_BOOL("exhaust", options, "exhaust");
PHONGO_QUERY_OPT_DOCUMENT("max", options, "max")
else PHONGO_QUERY_OPT_DOCUMENT("max", modifiers, "$max");
PHONGO_QUERY_OPT_INT64_DEPRECATED("maxScan", options, "maxScan")
else PHONGO_QUERY_OPT_INT64_DEPRECATED("maxScan", modifiers, "$maxScan");
PHONGO_QUERY_OPT_INT64("maxTimeMS", options, "maxTimeMS")
else PHONGO_QUERY_OPT_INT64("maxTimeMS", modifiers, "$maxTimeMS");
PHONGO_QUERY_OPT_DOCUMENT("min", options, "min")
else PHONGO_QUERY_OPT_DOCUMENT("min", modifiers, "$min");
PHONGO_QUERY_OPT_BOOL("noCursorTimeout", options, "noCursorTimeout");
PHONGO_QUERY_OPT_BOOL("oplogReplay", options, "oplogReplay");
PHONGO_QUERY_OPT_DOCUMENT("projection", options, "projection");
PHONGO_QUERY_OPT_BOOL("returnKey", options, "returnKey")
else PHONGO_QUERY_OPT_BOOL("returnKey", modifiers, "$returnKey");
PHONGO_QUERY_OPT_BOOL("showRecordId", options, "showRecordId")
else PHONGO_QUERY_OPT_BOOL("showRecordId", modifiers, "$showDiskLoc");
PHONGO_QUERY_OPT_INT64("skip", options, "skip");
PHONGO_QUERY_OPT_DOCUMENT("sort", options, "sort")
else PHONGO_QUERY_OPT_DOCUMENT("sort", modifiers, "$orderby");
PHONGO_QUERY_OPT_BOOL_DEPRECATED("snapshot", options, "snapshot")
else PHONGO_QUERY_OPT_BOOL_DEPRECATED("snapshot", modifiers, "$snapshot");
PHONGO_QUERY_OPT_BOOL("tailable", options, "tailable");
/* The "$explain" modifier should be converted to an "explain" option, which
* libmongoc will later convert back to a modifier for the OP_QUERY code
* path. This modifier will be ignored for the find command code path. */
PHONGO_QUERY_OPT_BOOL("explain", modifiers, "$explain");
if (!php_phongo_query_init_hint(intern, options, modifiers TSRMLS_CC)) {
return false;
}
if (!php_phongo_query_init_limit_and_singlebatch(intern, options TSRMLS_CC)) {
return false;
}
if (!php_phongo_query_init_readconcern(intern, options TSRMLS_CC)) {
return false;
}
if (!php_phongo_query_init_max_await_time_ms(intern, options TSRMLS_CC)) {
return false;
}
return true;
} /* }}} */
#undef PHONGO_QUERY_OPT_BOOL
#undef PHONGO_QUERY_OPT_DOCUMENT
#undef PHONGO_QUERY_OPT_INT64
#undef PHONGO_QUERY_OPT_STRING
/* {{{ proto void MongoDB\Driver\Query::__construct(array|object $filter[, array $options = array()])
Constructs a new Query */
static PHP_METHOD(Query, __construct)
{
php_phongo_query_t* intern;
zend_error_handling error_handling;
zval* filter;
zval* options = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_QUERY_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A|a!", &filter, &options) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
php_phongo_query_init(intern, filter, options TSRMLS_CC);
} /* }}} */
/* {{{ MongoDB\Driver\Query function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Query___construct, 0, 0, 1)
ZEND_ARG_INFO(0, filter)
ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Query_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_query_me[] = {
/* clang-format off */
PHP_ME(Query, __construct, ai_Query___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Query_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Query object handlers */
static zend_object_handlers php_phongo_handler_query;
static void php_phongo_query_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_query_t* intern = Z_OBJ_QUERY(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->filter) {
bson_clear(&intern->filter);
}
if (intern->opts) {
bson_clear(&intern->opts);
}
if (intern->read_concern) {
mongoc_read_concern_destroy(intern->read_concern);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_query_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_query_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_query_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_query;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_query_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_query;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_query_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_query_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_QUERY_OBJ_P(object);
array_init_size(&retval, 3);
/* Avoid using PHONGO_TYPEMAP_NATIVE_ARRAY for decoding filter and opts
* documents so that users can differentiate BSON arrays and documents. */
if (intern->filter) {
#if PHP_VERSION_ID >= 70000
zval zv;
#else
zval* zv;
#endif
php_phongo_bson_to_zval(bson_get_data(intern->filter), intern->filter->len, &zv);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "filter", &zv);
#else
ADD_ASSOC_ZVAL_EX(&retval, "filter", zv);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "filter");
}
if (intern->opts) {
#if PHP_VERSION_ID >= 70000
zval zv;
#else
zval* zv;
#endif
php_phongo_bson_to_zval(bson_get_data(intern->opts), intern->opts->len, &zv);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "options", &zv);
#else
ADD_ASSOC_ZVAL_EX(&retval, "options", zv);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "options");
}
if (intern->read_concern) {
#if PHP_VERSION_ID >= 70000
zval read_concern;
php_phongo_read_concern_to_zval(&read_concern, intern->read_concern);
ADD_ASSOC_ZVAL_EX(&retval, "readConcern", &read_concern);
#else
zval* read_concern = NULL;
MAKE_STD_ZVAL(read_concern);
php_phongo_read_concern_to_zval(read_concern, intern->read_concern);
ADD_ASSOC_ZVAL_EX(&retval, "readConcern", read_concern);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "readConcern");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_query_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Query", php_phongo_query_me);
php_phongo_query_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_query_ce->create_object = php_phongo_query_create_object;
PHONGO_CE_FINAL(php_phongo_query_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_query_ce);
memcpy(&php_phongo_handler_query, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_query.get_debug_info = php_phongo_query_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_query.free_obj = php_phongo_query_free_object;
php_phongo_handler_query.offset = XtOffsetOf(php_phongo_query_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/ReadConcern.c 0000644 0000765 0000024 00000023512 13572250757 017067 0 ustar alcaeus staff /*
* Copyright 2015-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_readconcern_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_readconcern_init_from_hash(php_phongo_readconcern_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval* level;
intern->read_concern = mongoc_read_concern_new();
if ((level = zend_hash_str_find(props, "level", sizeof("level") - 1))) {
if (Z_TYPE_P(level) == IS_STRING) {
mongoc_read_concern_set_level(intern->read_concern, Z_STRVAL_P(level));
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"level\" string field", ZSTR_VAL(php_phongo_readconcern_ce->name));
goto failure;
}
#else
zval** level;
intern->read_concern = mongoc_read_concern_new();
if (zend_hash_find(props, "level", sizeof("level"), (void**) &level) == SUCCESS) {
if (Z_TYPE_PP(level) == IS_STRING) {
mongoc_read_concern_set_level(intern->read_concern, Z_STRVAL_PP(level));
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"level\" string field", ZSTR_VAL(php_phongo_readconcern_ce->name));
goto failure;
}
#endif
return true;
failure:
mongoc_read_concern_destroy(intern->read_concern);
intern->read_concern = NULL;
return false;
} /* }}} */
/* {{{ proto void MongoDB\Driver\ReadConcern::__construct([string $level])
Constructs a new ReadConcern */
static PHP_METHOD(ReadConcern, __construct)
{
php_phongo_readconcern_t* intern;
zend_error_handling error_handling;
char* level = NULL;
phongo_zpp_char_len level_len = 0;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_READCONCERN_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!", &level, &level_len) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
intern->read_concern = mongoc_read_concern_new();
if (level) {
mongoc_read_concern_set_level(intern->read_concern, level);
}
} /* }}} */
/* {{{ proto void MongoDB\BSON\ReadConcern::__set_state(array $properties)
*/
static PHP_METHOD(ReadConcern, __set_state)
{
php_phongo_readconcern_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_readconcern_ce);
intern = Z_READCONCERN_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_readconcern_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string|null MongoDB\Driver\ReadConcern::getLevel()
Returns the ReadConcern "level" option */
static PHP_METHOD(ReadConcern, getLevel)
{
php_phongo_readconcern_t* intern;
const char* level;
intern = Z_READCONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
level = mongoc_read_concern_get_level(intern->read_concern);
if (level) {
PHONGO_RETURN_STRING(level);
}
RETURN_NULL();
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\ReadConcern::isDefault()
Returns whether the read concern has not been modified (i.e. constructed
without a level or from a Manager with no read concern URI options). */
static PHP_METHOD(ReadConcern, isDefault)
{
php_phongo_readconcern_t* intern;
intern = Z_READCONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(mongoc_read_concern_is_default(intern->read_concern));
} /* }}} */
static HashTable* php_phongo_read_concern_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_readconcern_t* intern;
HashTable* props;
const char* level;
intern = Z_READCONCERN_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 1);
if (!intern->read_concern) {
return props;
}
level = mongoc_read_concern_get_level(intern->read_concern);
if (level) {
#if PHP_VERSION_ID >= 70000
zval z_level;
ZVAL_STRING(&z_level, level);
zend_hash_str_update(props, "level", sizeof("level") - 1, &z_level);
#else
zval* z_level;
MAKE_STD_ZVAL(z_level);
ZVAL_STRING(z_level, level, 1);
zend_hash_update(props, "level", sizeof("level"), &z_level, sizeof(z_level), NULL);
#endif
}
return props;
} /* }}} */
/* {{{ proto array MongoDB\Driver\ReadConcern::bsonSerialize()
*/
static PHP_METHOD(ReadConcern, bsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
ZVAL_ARR(return_value, php_phongo_read_concern_get_properties_hash(getThis(), true TSRMLS_CC));
convert_to_object(return_value);
} /* }}} */
/* {{{ MongoDB\Driver\ReadConcern function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_ReadConcern___construct, 0, 0, 0)
ZEND_ARG_INFO(0, level)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ReadConcern___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ReadConcern_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_readconcern_me[] = {
/* clang-format off */
PHP_ME(ReadConcern, __construct, ai_ReadConcern___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadConcern, __set_state, ai_ReadConcern___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(ReadConcern, getLevel, ai_ReadConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadConcern, isDefault, ai_ReadConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadConcern, bsonSerialize, ai_ReadConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\ReadConcern object handlers */
static zend_object_handlers php_phongo_handler_readconcern;
static void php_phongo_readconcern_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_readconcern_t* intern = Z_OBJ_READCONCERN(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->read_concern) {
mongoc_read_concern_destroy(intern->read_concern);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
}
static phongo_create_object_retval php_phongo_readconcern_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_readconcern_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_readconcern_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_readconcern;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_readconcern_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_readconcern;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_readconcern_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_read_concern_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_readconcern_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_read_concern_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
void php_phongo_readconcern_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ReadConcern", php_phongo_readconcern_me);
php_phongo_readconcern_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_readconcern_ce->create_object = php_phongo_readconcern_create_object;
PHONGO_CE_FINAL(php_phongo_readconcern_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_readconcern_ce);
zend_class_implements(php_phongo_readconcern_ce TSRMLS_CC, 1, php_phongo_serializable_ce);
memcpy(&php_phongo_handler_readconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_readconcern.get_debug_info = php_phongo_readconcern_get_debug_info;
php_phongo_handler_readconcern.get_properties = php_phongo_readconcern_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_readconcern.free_obj = php_phongo_readconcern_free_object;
php_phongo_handler_readconcern.offset = XtOffsetOf(php_phongo_readconcern_t, std);
#endif
zend_declare_class_constant_stringl(php_phongo_readconcern_ce, ZEND_STRL("LOCAL"), ZEND_STRL(MONGOC_READ_CONCERN_LEVEL_LOCAL) TSRMLS_CC);
zend_declare_class_constant_stringl(php_phongo_readconcern_ce, ZEND_STRL("MAJORITY"), ZEND_STRL(MONGOC_READ_CONCERN_LEVEL_MAJORITY) TSRMLS_CC);
zend_declare_class_constant_stringl(php_phongo_readconcern_ce, ZEND_STRL("LINEARIZABLE"), ZEND_STRL(MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE) TSRMLS_CC);
zend_declare_class_constant_stringl(php_phongo_readconcern_ce, ZEND_STRL("AVAILABLE"), ZEND_STRL(MONGOC_READ_CONCERN_LEVEL_AVAILABLE) TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/ReadPreference.c 0000644 0000765 0000024 00000057204 13572250757 017563 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_readpreference_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_readpreference_init_from_hash(php_phongo_readpreference_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *mode, *tagSets, *maxStalenessSeconds;
if ((mode = zend_hash_str_find(props, "mode", sizeof("mode") - 1)) && Z_TYPE_P(mode) == IS_STRING) {
if (strcasecmp(Z_STRVAL_P(mode), "primary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
} else if (strcasecmp(Z_STRVAL_P(mode), "primaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), "secondary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
} else if (strcasecmp(Z_STRVAL_P(mode), "secondaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), "nearest") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_NEAREST);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires specific values for \"mode\" string field", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"mode\" field to be string", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
if ((tagSets = zend_hash_str_find(props, "tags", sizeof("tags") - 1))) {
if (Z_TYPE_P(tagSets) == IS_ARRAY) {
bson_t* tags = bson_new();
php_phongo_read_preference_prep_tagsets(tagSets TSRMLS_CC);
php_phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL TSRMLS_CC);
if (!php_phongo_read_preference_tags_are_valid(tags)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" array field to have zero or more documents", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
if (!bson_empty(tags) && (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" array field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" field to be array", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
if ((maxStalenessSeconds = zend_hash_str_find(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds") - 1))) {
if (Z_TYPE_P(maxStalenessSeconds) == IS_LONG) {
if (Z_LVAL_P(maxStalenessSeconds) < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" integer field to be >= %d", ZSTR_VAL(php_phongo_readpreference_ce->name), MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
goto failure;
}
if (Z_LVAL_P(maxStalenessSeconds) > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" integer field to be <= %" PRId32, ZSTR_VAL(php_phongo_readpreference_ce->name), INT32_MAX);
goto failure;
}
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" array field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
mongoc_read_prefs_set_max_staleness_seconds(intern->read_preference, Z_LVAL_P(maxStalenessSeconds));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" field to be integer", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
#else
zval **mode, **tagSets, **maxStalenessSeconds;
if (zend_hash_find(props, "mode", sizeof("mode"), (void**) &mode) == SUCCESS && Z_TYPE_PP(mode) == IS_STRING) {
if (strcasecmp(Z_STRVAL_PP(mode), "primary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
} else if (strcasecmp(Z_STRVAL_PP(mode), "primaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_PP(mode), "secondary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
} else if (strcasecmp(Z_STRVAL_PP(mode), "secondaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_PP(mode), "nearest") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_NEAREST);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires specific values for \"mode\" string field", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"mode\" field to be string", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
if (zend_hash_find(props, "tags", sizeof("tags"), (void**) &tagSets) == SUCCESS) {
if (Z_TYPE_PP(tagSets) == IS_ARRAY) {
bson_t* tags = bson_new();
php_phongo_read_preference_prep_tagsets(*tagSets TSRMLS_CC);
php_phongo_zval_to_bson(*tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL TSRMLS_CC);
if (!php_phongo_read_preference_tags_are_valid(tags)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" array field to have zero or more documents", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
if (!bson_empty(tags) && (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" array field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"tags\" field to be array", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
if (zend_hash_find(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds"), (void**) &maxStalenessSeconds) == SUCCESS) {
if (Z_TYPE_PP(maxStalenessSeconds) == IS_LONG) {
if (Z_LVAL_PP(maxStalenessSeconds) < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" integer field to be >= %d", ZSTR_VAL(php_phongo_readpreference_ce->name), MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
goto failure;
}
if (Z_LVAL_PP(maxStalenessSeconds) > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" integer field to be <= %" PRId32, ZSTR_VAL(php_phongo_readpreference_ce->name), INT32_MAX);
goto failure;
}
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" array field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
mongoc_read_prefs_set_max_staleness_seconds(intern->read_preference, Z_LVAL_PP(maxStalenessSeconds));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"maxStalenessSeconds\" field to be integer", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
#endif
return true;
failure:
mongoc_read_prefs_destroy(intern->read_preference);
intern->read_preference = NULL;
return false;
} /* }}} */
/* {{{ proto void MongoDB\Driver\ReadPreference::__construct(int|string $mode[, array $tagSets = array()[, array $options = array()]])
Constructs a new ReadPreference */
static PHP_METHOD(ReadPreference, __construct)
{
php_phongo_readpreference_t* intern;
zend_error_handling error_handling;
zval* mode;
zval* tagSets = NULL;
zval* options = NULL;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_READPREFERENCE_OBJ_P(getThis());
/* Separate the tagSets zval, since we may end up modifying it in
* php_phongo_read_preference_prep_tagsets() below. */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|a/!a!", &mode, &tagSets, &options) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
if (Z_TYPE_P(mode) == IS_LONG) {
switch (Z_LVAL_P(mode)) {
case MONGOC_READ_PRIMARY:
case MONGOC_READ_SECONDARY:
case MONGOC_READ_PRIMARY_PREFERRED:
case MONGOC_READ_SECONDARY_PREFERRED:
case MONGOC_READ_NEAREST:
intern->read_preference = mongoc_read_prefs_new(Z_LVAL_P(mode));
break;
default:
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Invalid mode: %" PHONGO_LONG_FORMAT, Z_LVAL_P(mode));
return;
}
} else if (Z_TYPE_P(mode) == IS_STRING) {
if (strcasecmp(Z_STRVAL_P(mode), "primary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
} else if (strcasecmp(Z_STRVAL_P(mode), "primaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), "secondary") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
} else if (strcasecmp(Z_STRVAL_P(mode), "secondaryPreferred") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), "nearest") == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_NEAREST);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Invalid mode: '%s'", Z_STRVAL_P(mode));
return;
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected mode to be integer or string, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(mode));
return;
}
if (tagSets) {
bson_t* tags = bson_new();
php_phongo_read_preference_prep_tagsets(tagSets TSRMLS_CC);
php_phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL TSRMLS_CC);
if (!php_phongo_read_preference_tags_are_valid(tags)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "tagSets must be an array of zero or more documents");
bson_destroy(tags);
return;
}
if (!bson_empty(tags) && (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "tagSets may not be used with primary mode");
bson_destroy(tags);
return;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
}
if (options && php_array_exists(options, "maxStalenessSeconds")) {
phongo_long maxStalenessSeconds = php_array_fetchc_long(options, "maxStalenessSeconds");
if (maxStalenessSeconds != MONGOC_NO_MAX_STALENESS) {
if (maxStalenessSeconds < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected maxStalenessSeconds to be >= %d, %" PHONGO_LONG_FORMAT " given", MONGOC_SMALLEST_MAX_STALENESS_SECONDS, maxStalenessSeconds);
return;
}
if (maxStalenessSeconds > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected maxStalenessSeconds to be <= %" PRId32 ", %" PHONGO_LONG_FORMAT " given", INT32_MAX, maxStalenessSeconds);
return;
}
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "maxStalenessSeconds may not be used with primary mode");
return;
}
}
mongoc_read_prefs_set_max_staleness_seconds(intern->read_preference, maxStalenessSeconds);
}
if (!mongoc_read_prefs_is_valid(intern->read_preference)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Read preference is not valid");
return;
}
} /* }}} */
/* {{{ proto void MongoDB\BSON\ReadPreference::__set_state(array $properties)
*/
static PHP_METHOD(ReadPreference, __set_state)
{
php_phongo_readpreference_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_readpreference_ce);
intern = Z_READPREFERENCE_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_readpreference_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto integer MongoDB\Driver\ReadPreference::getMaxStalenessSeconds()
Returns the ReadPreference maxStalenessSeconds value */
static PHP_METHOD(ReadPreference, getMaxStalenessSeconds)
{
php_phongo_readpreference_t* intern;
intern = Z_READPREFERENCE_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference));
} /* }}} */
/* {{{ proto integer MongoDB\Driver\ReadPreference::getMode()
Returns the ReadPreference mode */
static PHP_METHOD(ReadPreference, getMode)
{
php_phongo_readpreference_t* intern;
intern = Z_READPREFERENCE_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(mongoc_read_prefs_get_mode(intern->read_preference));
} /* }}} */
/* {{{ proto array MongoDB\Driver\ReadPreference::getTagSets()
Returns the ReadPreference tag sets */
static PHP_METHOD(ReadPreference, getTagSets)
{
php_phongo_readpreference_t* intern;
const bson_t* tags;
intern = Z_READPREFERENCE_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
tags = mongoc_read_prefs_get_tags(intern->read_preference);
if (tags->len) {
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
/* Use native arrays for debugging output */
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
php_phongo_bson_to_zval_ex(bson_get_data(tags), tags->len, &state);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} else {
RETURN_NULL();
}
} /* }}} */
static HashTable* php_phongo_readpreference_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_readpreference_t* intern;
HashTable* props;
const char* modeString = NULL;
const bson_t* tags;
mongoc_read_mode_t mode;
intern = Z_READPREFERENCE_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 3);
if (!intern->read_preference) {
return props;
}
tags = mongoc_read_prefs_get_tags(intern->read_preference);
mode = mongoc_read_prefs_get_mode(intern->read_preference);
switch (mode) {
case MONGOC_READ_PRIMARY:
modeString = "primary";
break;
case MONGOC_READ_PRIMARY_PREFERRED:
modeString = "primaryPreferred";
break;
case MONGOC_READ_SECONDARY:
modeString = "secondary";
break;
case MONGOC_READ_SECONDARY_PREFERRED:
modeString = "secondaryPreferred";
break;
case MONGOC_READ_NEAREST:
modeString = "nearest";
break;
default: /* Do nothing */
break;
}
if (modeString) {
#if PHP_VERSION_ID >= 70000
zval z_mode;
ZVAL_STRING(&z_mode, modeString);
zend_hash_str_update(props, "mode", sizeof("mode") - 1, &z_mode);
#else
zval* z_mode;
MAKE_STD_ZVAL(z_mode);
ZVAL_STRING(z_mode, modeString, 1);
zend_hash_update(props, "mode", sizeof("mode"), &z_mode, sizeof(z_mode), NULL);
#endif
}
if (!bson_empty0(tags)) {
/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type since tags is an
* array; however, inner documents and arrays can use the default. */
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
php_phongo_bson_to_zval_ex(bson_get_data(tags), tags->len, &state);
#if PHP_VERSION_ID >= 70000
Z_ADDREF(state.zchild);
zend_hash_str_update(props, "tags", sizeof("tags") - 1, &state.zchild);
#else
Z_ADDREF_P(state.zchild);
zend_hash_update(props, "tags", sizeof("tags"), &state.zchild, sizeof(state.zchild), NULL);
#endif
zval_ptr_dtor(&state.zchild);
}
if (mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference) != MONGOC_NO_MAX_STALENESS) {
long maxStalenessSeconds = mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference);
#if PHP_VERSION_ID >= 70000
zval z_max_ss;
ZVAL_LONG(&z_max_ss, maxStalenessSeconds);
zend_hash_str_update(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds") - 1, &z_max_ss);
#else
zval* z_max_ss;
MAKE_STD_ZVAL(z_max_ss);
ZVAL_LONG(z_max_ss, maxStalenessSeconds);
zend_hash_update(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds"), &z_max_ss, sizeof(z_max_ss), NULL);
#endif
}
return props;
} /* }}} */
/* {{{ proto array MongoDB\Driver\ReadPreference::bsonSerialize()
*/
static PHP_METHOD(ReadPreference, bsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
ZVAL_ARR(return_value, php_phongo_readpreference_get_properties_hash(getThis(), true TSRMLS_CC));
convert_to_object(return_value);
} /* }}} */
/* {{{ MongoDB\Driver\ReadPreference function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_ReadPreference___construct, 0, 0, 1)
ZEND_ARG_INFO(0, mode)
ZEND_ARG_ARRAY_INFO(0, tagSets, 1)
ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ReadPreference___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_ReadPreference_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_readpreference_me[] = {
/* clang-format off */
PHP_ME(ReadPreference, __construct, ai_ReadPreference___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadPreference, __set_state, ai_ReadPreference___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(ReadPreference, getMaxStalenessSeconds, ai_ReadPreference_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadPreference, getMode, ai_ReadPreference_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadPreference, getTagSets, ai_ReadPreference_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(ReadPreference, bsonSerialize, ai_ReadPreference_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\ReadPreference object handlers */
static zend_object_handlers php_phongo_handler_readpreference;
static void php_phongo_readpreference_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_readpreference_t* intern = Z_OBJ_READPREFERENCE(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->read_preference) {
mongoc_read_prefs_destroy(intern->read_preference);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_readpreference_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_readpreference_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_readpreference_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_readpreference;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_readpreference_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_readpreference;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_readpreference_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_readpreference_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_readpreference_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_readpreference_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
/* }}} */
void php_phongo_readpreference_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ReadPreference", php_phongo_readpreference_me);
php_phongo_readpreference_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_readpreference_ce->create_object = php_phongo_readpreference_create_object;
PHONGO_CE_FINAL(php_phongo_readpreference_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_readpreference_ce);
zend_class_implements(php_phongo_readpreference_ce TSRMLS_CC, 1, php_phongo_serializable_ce);
memcpy(&php_phongo_handler_readpreference, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_readpreference.get_debug_info = php_phongo_readpreference_get_debug_info;
php_phongo_handler_readpreference.get_properties = php_phongo_readpreference_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_readpreference.free_obj = php_phongo_readpreference_free_object;
php_phongo_handler_readpreference.offset = XtOffsetOf(php_phongo_readpreference_t, std);
#endif
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("RP_PRIMARY"), MONGOC_READ_PRIMARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("RP_PRIMARY_PREFERRED"), MONGOC_READ_PRIMARY_PREFERRED TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("RP_SECONDARY"), MONGOC_READ_SECONDARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("RP_SECONDARY_PREFERRED"), MONGOC_READ_SECONDARY_PREFERRED TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("RP_NEAREST"), MONGOC_READ_NEAREST TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("NO_MAX_STALENESS"), MONGOC_NO_MAX_STALENESS TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_readpreference_ce, ZEND_STRL("SMALLEST_MAX_STALENESS_SECONDS"), MONGOC_SMALLEST_MAX_STALENESS_SECONDS TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Server.c 0000644 0000765 0000024 00000053446 13572250757 016163 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
zend_class_entry* php_phongo_server_ce;
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Server::executeCommand(string $db, MongoDB\Driver\Command $command[, array $options = null]))
Executes a Command on this Server */
static PHP_METHOD(Server, executeCommand)
{
php_phongo_server_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
bool free_options = false;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
options = php_phongo_prep_legacy_option(options, "readPreference", &free_options TSRMLS_CC);
phongo_execute_command(intern->client, PHONGO_COMMAND_RAW, db, command, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Server::executeReadCommand(string $db, MongoDB\Driver\Command $command[, array $options = null]))
Executes a ReadCommand on this Server */
static PHP_METHOD(Server, executeReadCommand)
{
php_phongo_server_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_READ, db, command, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Server::executeWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null]))
Executes a WriteCommand on this Server */
static PHP_METHOD(Server, executeWriteCommand)
{
php_phongo_server_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_WRITE, db, command, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Server::executeReadWriteCommand(string $db, MongoDB\Driver\Command $command[, array $options = null]))
Executes a ReadWriteCommand on this Server */
static PHP_METHOD(Server, executeReadWriteCommand)
{
php_phongo_server_t* intern;
char* db;
phongo_zpp_char_len db_len;
zval* command;
zval* options = NULL;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|a!", &db, &db_len, &command, php_phongo_command_ce, &options) == FAILURE) {
return;
}
phongo_execute_command(intern->client, PHONGO_COMMAND_READ_WRITE, db, command, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Cursor MongoDB\Driver\Server::executeQuery(string $namespace, MongoDB\Driver\Query $query[, array $options = null]))
Executes a Query on this Server */
static PHP_METHOD(Server, executeQuery)
{
php_phongo_server_t* intern;
char* namespace;
phongo_zpp_char_len namespace_len;
zval* query;
zval* options = NULL;
bool free_options = false;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &namespace, &namespace_len, &query, php_phongo_query_ce, &options) == FAILURE) {
return;
}
options = php_phongo_prep_legacy_option(options, "readPreference", &free_options TSRMLS_CC);
phongo_execute_query(intern->client, namespace, query, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto MongoDB\Driver\WriteResult MongoDB\Driver\Server::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $zbulk[, array $options = null])
Executes a BulkWrite (i.e. any number of insert, update, and delete ops) on
this Server */
static PHP_METHOD(Server, executeBulkWrite)
{
php_phongo_server_t* intern;
char* namespace;
phongo_zpp_char_len namespace_len;
zval* zbulk;
php_phongo_bulkwrite_t* bulk;
zval* options = NULL;
bool free_options = false;
DECLARE_RETURN_VALUE_USED
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sO|z!", &namespace, &namespace_len, &zbulk, php_phongo_bulkwrite_ce, &options, php_phongo_writeconcern_ce) == FAILURE) {
return;
}
bulk = Z_BULKWRITE_OBJ_P(zbulk);
options = php_phongo_prep_legacy_option(options, "writeConcern", &free_options TSRMLS_CC);
phongo_execute_bulk_write(intern->client, namespace, bulk, options, intern->server_id, return_value, return_value_used TSRMLS_CC);
if (free_options) {
php_phongo_prep_legacy_option_free(options TSRMLS_CC);
}
} /* }}} */
/* {{{ proto string MongoDB\Driver\Server::getHost()
Returns the hostname for this Server */
static PHP_METHOD(Server, getHost)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
PHONGO_RETVAL_STRING(mongoc_server_description_host(sd)->host);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto array MongoDB\Driver\Server::getTags()
Returns the currently configured tags for this Server */
static PHP_METHOD(Server, getTags)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
const bson_t* is_master = mongoc_server_description_ismaster(sd);
bson_iter_t iter;
if (bson_iter_init_find(&iter, is_master, "tags") && BSON_ITER_HOLDS_DOCUMENT(&iter)) {
const uint8_t* bytes;
uint32_t len;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
bson_iter_document(&iter, &len, &bytes);
if (!php_phongo_bson_to_zval_ex(bytes, len, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
return;
}
mongoc_server_description_destroy(sd);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
}
array_init(return_value);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto array MongoDB\Driver\Server::getInfo()
Returns the last isMaster result document for this Server */
static PHP_METHOD(Server, getInfo)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
const bson_t* is_master = mongoc_server_description_ismaster(sd);
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!php_phongo_bson_to_zval_ex(bson_get_data(is_master), is_master->len, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
return;
}
mongoc_server_description_destroy(sd);
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto integer MongoDB\Driver\Server::getLatency()
Returns the last measured latency for this Server */
static PHP_METHOD(Server, getLatency)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_LONG((phongo_long) mongoc_server_description_round_trip_time(sd));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto integer MongoDB\Driver\Server::getPort()
Returns the port for this Server */
static PHP_METHOD(Server, getPort)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_LONG(mongoc_server_description_host(sd)->port);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto integer MongoDB\Driver\Server::getType()
Returns the node type of this Server */
static PHP_METHOD(Server, getType)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_LONG(php_phongo_server_description_type(sd));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Server::isPrimary()
Returns whether this Server is a primary member of a replica set */
static PHP_METHOD(Server, isPrimary)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_PRIMARY].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Server::isSecondary()
Returns whether this Server is a secondary member of a replica set */
static PHP_METHOD(Server, isSecondary)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_SECONDARY].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Server::isArbiter()
Returns whether this Server is an arbiter member of a replica set */
static PHP_METHOD(Server, isArbiter)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_ARBITER].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Server::isHidden()
Returns whether this Server is a hidden member of a replica set */
static PHP_METHOD(Server, isHidden)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
bson_iter_t iter;
RETVAL_BOOL(bson_iter_init_find_case(&iter, mongoc_server_description_ismaster(sd), "hidden") && bson_iter_as_bool(&iter));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\Server::isPassive()
Returns whether this Server is a passive member of a replica set */
static PHP_METHOD(Server, isPassive)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if ((sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
bson_iter_t iter;
RETVAL_BOOL(bson_iter_init_find_case(&iter, mongoc_server_description_ismaster(sd), "passive") && bson_iter_as_bool(&iter));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
} /* }}} */
/* {{{ MongoDB\Driver\Server function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Server_executeCommand, 0, 0, 2)
ZEND_ARG_INFO(0, db)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Server_executeRWCommand, 0, 0, 2)
ZEND_ARG_INFO(0, db)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Server_executeQuery, 0, 0, 2)
ZEND_ARG_INFO(0, namespace)
ZEND_ARG_OBJ_INFO(0, zquery, MongoDB\\Driver\\Query, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Server_executeBulkWrite, 0, 0, 2)
ZEND_ARG_INFO(0, namespace)
ZEND_ARG_OBJ_INFO(0, zbulk, MongoDB\\Driver\\BulkWrite, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Server_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_server_me[] = {
/* clang-format off */
PHP_ME(Server, executeCommand, ai_Server_executeCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, executeReadCommand, ai_Server_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, executeWriteCommand, ai_Server_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, executeReadWriteCommand, ai_Server_executeRWCommand, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, executeQuery, ai_Server_executeQuery, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, executeBulkWrite, ai_Server_executeBulkWrite, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getHost, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getTags, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getInfo, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getLatency, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getPort, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, getType, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, isPrimary, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, isSecondary, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, isArbiter, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, isHidden, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Server, isPassive, ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Server_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Server_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Server object handlers */
static zend_object_handlers php_phongo_handler_server;
static int php_phongo_server_compare_objects(zval* o1, zval* o2 TSRMLS_DC) /* {{{ */
{
php_phongo_server_t* intern1;
php_phongo_server_t* intern2;
mongoc_server_description_t *sd1, *sd2;
int retval = 0;
intern1 = Z_SERVER_OBJ_P(o1);
intern2 = Z_SERVER_OBJ_P(o2);
sd1 = mongoc_client_get_server_description(intern1->client, intern1->server_id);
sd2 = mongoc_client_get_server_description(intern2->client, intern2->server_id);
if (sd1 && sd2) {
retval = strcasecmp(mongoc_server_description_host(sd1)->host_and_port, mongoc_server_description_host(sd2)->host_and_port);
} else {
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description(s)");
}
if (sd1) {
mongoc_server_description_destroy(sd1);
}
if (sd2) {
mongoc_server_description_destroy(sd2);
}
return retval;
} /* }}} */
static void php_phongo_server_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_server_t* intern = Z_OBJ_SERVER(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_server_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_server_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_server_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_server;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_server_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_server;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_server_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_server_t* intern = NULL;
zval retval = ZVAL_STATIC_INIT;
mongoc_server_description_t* sd;
*is_temp = 1;
intern = Z_SERVER_OBJ_P(object);
if (!(sd = mongoc_client_get_server_description(intern->client, intern->server_id))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME TSRMLS_CC, "Failed to get server description");
return NULL;
}
php_phongo_server_to_zval(&retval, sd);
mongoc_server_description_destroy(sd);
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_server_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Server", php_phongo_server_me);
php_phongo_server_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_server_ce->create_object = php_phongo_server_create_object;
PHONGO_CE_FINAL(php_phongo_server_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_server_ce);
memcpy(&php_phongo_handler_server, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_server.compare_objects = php_phongo_server_compare_objects;
php_phongo_handler_server.get_debug_info = php_phongo_server_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_server.free_obj = php_phongo_server_free_object;
php_phongo_handler_server.offset = XtOffsetOf(php_phongo_server_t, std);
#endif
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_UNKNOWN"), PHONGO_SERVER_UNKNOWN TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_STANDALONE"), PHONGO_SERVER_STANDALONE TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_MONGOS"), PHONGO_SERVER_MONGOS TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_POSSIBLE_PRIMARY"), PHONGO_SERVER_POSSIBLE_PRIMARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_RS_PRIMARY"), PHONGO_SERVER_RS_PRIMARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_RS_SECONDARY"), PHONGO_SERVER_RS_SECONDARY TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_RS_ARBITER"), PHONGO_SERVER_RS_ARBITER TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_RS_OTHER"), PHONGO_SERVER_RS_OTHER TSRMLS_CC);
zend_declare_class_constant_long(php_phongo_server_ce, ZEND_STRL("TYPE_RS_GHOST"), PHONGO_SERVER_RS_GHOST TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Session.c 0000644 0000765 0000024 00000052125 13572250757 016331 0 ustar alcaeus staff /*
* Copyright 2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
#include "php_array_api.h"
#include "Session.h"
zend_class_entry* php_phongo_session_ce;
#define SESSION_CHECK_LIVELINESS(i, m) \
if (!(i)->client_session) { \
phongo_throw_exception( \
PHONGO_ERROR_LOGIC TSRMLS_CC, \
"Cannot call '%s', as the session has already been ended.", \
(m)); \
return; \
}
static bool php_phongo_session_get_timestamp_parts(zval* obj, uint32_t* timestamp, uint32_t* increment TSRMLS_DC)
{
bool retval = false;
#if PHP_VERSION_ID >= 70000
zval ztimestamp = ZVAL_STATIC_INIT;
zval zincrement = ZVAL_STATIC_INIT;
zend_call_method_with_0_params(obj, NULL, NULL, "getTimestamp", &ztimestamp);
if (Z_ISUNDEF(ztimestamp) || EG(exception)) {
goto cleanup;
}
zend_call_method_with_0_params(obj, NULL, NULL, "getIncrement", &zincrement);
if (Z_ISUNDEF(zincrement) || EG(exception)) {
goto cleanup;
}
*timestamp = Z_LVAL(ztimestamp);
*increment = Z_LVAL(zincrement);
#else
zval* ztimestamp = NULL;
zval* zincrement = NULL;
zend_call_method_with_0_params(&obj, NULL, NULL, "getTimestamp", &ztimestamp);
if (Z_ISUNDEF(ztimestamp) || EG(exception)) {
goto cleanup;
}
zend_call_method_with_0_params(&obj, NULL, NULL, "getIncrement", &zincrement);
if (Z_ISUNDEF(zincrement) || EG(exception)) {
goto cleanup;
}
*timestamp = Z_LVAL_P(ztimestamp);
*increment = Z_LVAL_P(zincrement);
#endif
retval = true;
cleanup:
if (!Z_ISUNDEF(ztimestamp)) {
zval_ptr_dtor(&ztimestamp);
}
if (!Z_ISUNDEF(zincrement)) {
zval_ptr_dtor(&zincrement);
}
return retval;
}
/* {{{ proto void MongoDB\Driver\Session::advanceClusterTime(array|object $clusterTime)
Advances the cluster time for this Session */
static PHP_METHOD(Session, advanceClusterTime)
{
php_phongo_session_t* intern;
zval* zcluster_time;
bson_t cluster_time = BSON_INITIALIZER;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "advanceClusterTime")
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "A", &zcluster_time) == FAILURE) {
return;
}
php_phongo_zval_to_bson(zcluster_time, PHONGO_BSON_NONE, &cluster_time, NULL TSRMLS_CC);
/* An exception may be thrown during BSON conversion */
if (EG(exception)) {
goto cleanup;
}
mongoc_client_session_advance_cluster_time(intern->client_session, &cluster_time);
cleanup:
bson_destroy(&cluster_time);
} /* }}} */
/* {{{ proto void MongoDB\Driver\Session::advanceOperationTime(MongoDB\BSON\TimestampInterface $timestamp)
Advances the operation time for this Session */
static PHP_METHOD(Session, advanceOperationTime)
{
php_phongo_session_t* intern;
zval* ztimestamp;
uint32_t timestamp = 0;
uint32_t increment = 0;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "advanceOperationTime")
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &ztimestamp, php_phongo_timestamp_interface_ce) == FAILURE) {
return;
}
if (!php_phongo_session_get_timestamp_parts(ztimestamp, ×tamp, &increment TSRMLS_CC)) {
return;
}
mongoc_client_session_advance_operation_time(intern->client_session, timestamp, increment);
} /* }}} */
/* {{{ proto object|null MongoDB\Driver\Session::getClusterTime()
Returns the cluster time for this Session */
static PHP_METHOD(Session, getClusterTime)
{
php_phongo_session_t* intern;
const bson_t* cluster_time;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getClusterTime")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
cluster_time = mongoc_client_session_get_cluster_time(intern->client_session);
if (!cluster_time) {
RETURN_NULL();
}
if (!php_phongo_bson_to_zval_ex(bson_get_data(cluster_time), cluster_time->len, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
return;
}
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto object MongoDB\Driver\Session::getLogicalSessionId()
Returns the logical session ID for this Session */
static PHP_METHOD(Session, getLogicalSessionId)
{
php_phongo_session_t* intern;
const bson_t* lsid;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getLogicalSessionId")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
lsid = mongoc_client_session_get_lsid(intern->client_session);
if (!php_phongo_bson_to_zval_ex(bson_get_data(lsid), lsid->len, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
return;
}
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&state.zchild, 0, 1);
#else
RETURN_ZVAL(state.zchild, 0, 1);
#endif
} /* }}} */
/* {{{ proto MongoDB\BSON\Timestamp|null MongoDB\Driver\Session::getOperationTime()
Returns the operation time for this Session */
static PHP_METHOD(Session, getOperationTime)
{
php_phongo_session_t* intern;
uint32_t timestamp, increment;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getOperationTime")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
mongoc_client_session_get_operation_time(intern->client_session, ×tamp, &increment);
/* mongoc_client_session_get_operation_time() returns 0 for both parts if
* the session has not been used. According to the causal consistency spec,
* the operation time for an unused session is null. */
if (timestamp == 0 && increment == 0) {
RETURN_NULL();
}
php_phongo_new_timestamp_from_increment_and_timestamp(return_value, increment, timestamp TSRMLS_CC);
} /* }}} */
/* {{{ proto MongoDB\Driver\Server|null MongoDB\Driver\Session::getServer()
Returns the server this session is pinned to */
static PHP_METHOD(Session, getServer)
{
php_phongo_session_t* intern;
uint32_t server_id = 0;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getServer")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
server_id = mongoc_client_session_get_server_id(intern->client_session);
/* For sessions without a pinned server, 0 is returned. */
if (!server_id) {
RETURN_NULL();
}
phongo_server_init(return_value, mongoc_client_session_get_client(intern->client_session), server_id TSRMLS_CC);
} /* }}} */
/* Creates a opts structure from an array optionally containing an RP, RC,
* WC object, and/or maxCommitTimeMS int. Returns NULL if no options were found,
* or there was an invalid option. If there was an invalid option or structure,
* an exception will be thrown too. */
mongoc_transaction_opt_t* php_mongodb_session_parse_transaction_options(zval* options TSRMLS_DC)
{
mongoc_transaction_opt_t* opts = NULL;
if (php_array_existsc(options, "maxCommitTimeMS")) {
int64_t max_commit_time_ms = php_array_fetchc_long(options, "maxCommitTimeMS");
if (max_commit_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxCommitTimeMS\" option to be >= 0, %" PRId64 " given", max_commit_time_ms);
/* Freeing opts is not needed here, as it can't be set yet. The
* code is here to keep it consistent with the others in case more
* options are added before this one. */
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (max_commit_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"maxCommitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_commit_time_ms);
/* Freeing opts is not needed here, as it can't be set yet. The
* code is here to keep it consistent with the others in case more
* options are added before this one. */
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_max_commit_time_ms(opts, max_commit_time_ms);
}
if (php_array_existsc(options, "readConcern")) {
zval* read_concern = php_array_fetchc(options, "readConcern");
if (Z_TYPE_P(read_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_concern), php_phongo_readconcern_ce TSRMLS_CC)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_readconcern_ce->name), PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(read_concern));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_read_concern(opts, phongo_read_concern_from_zval(read_concern TSRMLS_CC));
}
if (php_array_existsc(options, "readPreference")) {
zval* read_preference = php_array_fetchc(options, "readPreference");
if (Z_TYPE_P(read_preference) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_preference), php_phongo_readpreference_ce TSRMLS_CC)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"readPreference\" option to be %s, %s given", ZSTR_VAL(php_phongo_readpreference_ce->name), PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(read_preference));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_read_prefs(opts, phongo_read_preference_from_zval(read_preference TSRMLS_CC));
}
if (php_array_existsc(options, "writeConcern")) {
zval* write_concern = php_array_fetchc(options, "writeConcern");
if (Z_TYPE_P(write_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(write_concern), php_phongo_writeconcern_ce TSRMLS_CC)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected \"writeConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_writeconcern_ce->name), PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(write_concern));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_write_concern(opts, phongo_write_concern_from_zval(write_concern TSRMLS_CC));
}
return opts;
}
/* {{{ proto void MongoDB\Driver\Session::startTransaction([array $options = null])
Starts a new transaction */
static PHP_METHOD(Session, startTransaction)
{
php_phongo_session_t* intern;
zval* options = NULL;
mongoc_transaction_opt_t* txn_options = NULL;
bson_error_t error;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "startTransaction")
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &options) == FAILURE) {
return;
}
if (options) {
txn_options = php_mongodb_session_parse_transaction_options(options TSRMLS_CC);
}
if (EG(exception)) {
return;
}
if (!mongoc_client_session_start_transaction(intern->client_session, txn_options, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
}
if (txn_options) {
mongoc_transaction_opts_destroy(txn_options);
}
} /* }}} */
/* {{{ proto void MongoDB\Driver\Session::commitTransaction(void)
Commits an existing transaction */
static PHP_METHOD(Session, commitTransaction)
{
php_phongo_session_t* intern;
bson_error_t error;
bson_t reply;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "commitTransaction")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!mongoc_client_session_commit_transaction(intern->client_session, &reply, &error)) {
phongo_throw_exception_from_bson_error_t_and_reply(&error, &reply TSRMLS_CC);
bson_destroy(&reply);
}
} /* }}} */
/* {{{ proto void MongoDB\Driver\Session::abortTransaction(void)
Aborts (rolls back) an existing transaction */
static PHP_METHOD(Session, abortTransaction)
{
php_phongo_session_t* intern;
bson_error_t error;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "abortTransaction")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!mongoc_client_session_abort_transaction(intern->client_session, &error)) {
phongo_throw_exception_from_bson_error_t(&error TSRMLS_CC);
}
} /* }}} */
/* {{{ proto void MongoDB\Driver\Session::endSession(void)
Ends the session, and a running transaction if active */
static PHP_METHOD(Session, endSession)
{
php_phongo_session_t* intern;
intern = Z_SESSION_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
mongoc_client_session_destroy(intern->client_session);
intern->client_session = NULL;
} /* }}} */
/* {{{ proto void MongoDB\Driver\Session::isInTransaction(void)
Returns whether a multi-document transaction is in progress */
static PHP_METHOD(Session, isInTransaction)
{
php_phongo_session_t* intern;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "isInTransaction")
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(mongoc_client_session_in_transaction(intern->client_session));
} /* }}} */
/* {{{ MongoDB\Driver\Session function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_Session_advanceClusterTime, 0, 0, 1)
ZEND_ARG_INFO(0, clusterTime)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Session_advanceOperationTime, 0, 0, 1)
ZEND_ARG_INFO(0, timestamp)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Session_startTransaction, 0, 0, 0)
ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_Session_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_session_me[] = {
/* clang-format off */
PHP_ME(Session, abortTransaction, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, advanceClusterTime, ai_Session_advanceClusterTime, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, advanceOperationTime, ai_Session_advanceOperationTime, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, commitTransaction, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, endSession, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, getClusterTime, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, getLogicalSessionId, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, getOperationTime, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, getServer, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, isInTransaction, ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(Session, startTransaction, ai_Session_startTransaction, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_Session_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_Session_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\Session object handlers */
static zend_object_handlers php_phongo_handler_session;
static void php_phongo_session_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_session_t* intern = Z_OBJ_SESSION(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->client_session) {
mongoc_client_session_destroy(intern->client_session);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_session_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_session_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_session_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_session;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_session_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_session;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_session_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_session_t* intern = NULL;
const mongoc_session_opt_t* cs_opts;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_SESSION_OBJ_P(object);
array_init(&retval);
if (intern->client_session) {
const bson_t* lsid;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
/* Use native arrays for debugging output */
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
lsid = mongoc_client_session_get_lsid(intern->client_session);
php_phongo_bson_to_zval_ex(bson_get_data(lsid), lsid->len, &state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "logicalSessionId", &state.zchild);
#else
ADD_ASSOC_ZVAL_EX(&retval, "logicalSessionId", state.zchild);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "logicalSessionId");
}
if (intern->client_session) {
const bson_t* cluster_time;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
/* Use native arrays for debugging output */
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
cluster_time = mongoc_client_session_get_cluster_time(intern->client_session);
if (cluster_time) {
php_phongo_bson_to_zval_ex(bson_get_data(cluster_time), cluster_time->len, &state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "clusterTime", &state.zchild);
#else
ADD_ASSOC_ZVAL_EX(&retval, "clusterTime", state.zchild);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "clusterTime");
}
} else {
ADD_ASSOC_NULL_EX(&retval, "clusterTime");
}
if (intern->client_session) {
cs_opts = mongoc_client_session_get_opts(intern->client_session);
ADD_ASSOC_BOOL_EX(&retval, "causalConsistency", mongoc_session_opts_get_causal_consistency(cs_opts));
} else {
ADD_ASSOC_NULL_EX(&retval, "causalConsistency");
}
if (intern->client_session) {
uint32_t timestamp, increment;
mongoc_client_session_get_operation_time(intern->client_session, ×tamp, &increment);
if (timestamp && increment) {
#if PHP_VERSION_ID >= 70000
zval ztimestamp;
php_phongo_new_timestamp_from_increment_and_timestamp(&ztimestamp, increment, timestamp TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "operationTime", &ztimestamp);
#else
zval* ztimestamp;
MAKE_STD_ZVAL(ztimestamp);
php_phongo_new_timestamp_from_increment_and_timestamp(ztimestamp, increment, timestamp TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "operationTime", ztimestamp);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "operationTime");
}
} else {
ADD_ASSOC_NULL_EX(&retval, "operationTime");
}
if (intern->client_session) {
uint32_t server_id = mongoc_client_session_get_server_id(intern->client_session);
if (server_id) {
#if PHP_VERSION_ID >= 70000
zval server;
phongo_server_init(&server, mongoc_client_session_get_client(intern->client_session), server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
#else
zval* server = NULL;
MAKE_STD_ZVAL(server);
phongo_server_init(server, mongoc_client_session_get_client(intern->client_session), server_id TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "server", server);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "server");
}
} else {
ADD_ASSOC_NULL_EX(&retval, "server");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_session_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Session", php_phongo_session_me);
php_phongo_session_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_session_ce->create_object = php_phongo_session_create_object;
PHONGO_CE_FINAL(php_phongo_session_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_session_ce);
memcpy(&php_phongo_handler_session, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_session.get_debug_info = php_phongo_session_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_session.free_obj = php_phongo_session_free_object;
php_phongo_handler_session.offset = XtOffsetOf(php_phongo_session_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/Session.h 0000644 0000765 0000024 00000001457 13572250757 016340 0 ustar alcaeus staff /*
* Copyright 2017 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.
*/
#ifndef PHP_MONGODB_DRIVER_SESSION_H
#define PHP_MONGODB_DRIVER_SESSION_H
mongoc_transaction_opt_t* php_mongodb_session_parse_transaction_options(zval* txnOptions TSRMLS_DC);
#endif /* PHP_MONGODB_DRIVER_SESSION_H */
mongodb-1.6.1/src/MongoDB/WriteConcern.c 0000644 0000765 0000024 00000043637 13572250757 017320 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_writeconcern_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_writeconcern_init_from_hash(php_phongo_writeconcern_t* intern, HashTable* props TSRMLS_DC) /* {{{ */
{
#if PHP_VERSION_ID >= 70000
zval *w, *wtimeout, *j;
intern->write_concern = mongoc_write_concern_new();
if ((w = zend_hash_str_find(props, "w", sizeof("w") - 1))) {
if (Z_TYPE_P(w) == IS_LONG) {
if (Z_LVAL_P(w) < -3) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"w\" integer field to be >= -3", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
mongoc_write_concern_set_w(intern->write_concern, Z_LVAL_P(w));
} else if (Z_TYPE_P(w) == IS_STRING) {
if (strcmp(Z_STRVAL_P(w), PHONGO_WRITE_CONCERN_W_MAJORITY) == 0) {
mongoc_write_concern_set_w(intern->write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
} else {
mongoc_write_concern_set_wtag(intern->write_concern, Z_STRVAL_P(w));
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"w\" field to be integer or string", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if ((wtimeout = zend_hash_str_find(props, "wtimeout", sizeof("wtimeout") - 1))) {
if (Z_TYPE_P(wtimeout) == IS_LONG) {
if (Z_LVAL_P(wtimeout) < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" integer field to be >= 0", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
if (Z_LVAL_P(wtimeout) > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" integer field to be <= %" PRId32, ZSTR_VAL(php_phongo_writeconcern_ce->name), INT32_MAX);
goto failure;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, (int64_t) Z_LVAL_P(wtimeout));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" field to be integer", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if ((j = zend_hash_str_find(props, "j", sizeof("j") - 1))) {
if (Z_TYPE_P(j) == IS_TRUE || Z_TYPE_P(j) == IS_FALSE) {
mongoc_write_concern_set_journal(intern->write_concern, zend_is_true(j));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"j\" field to be boolean", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
#else
zval **w, **wtimeout, **j;
intern->write_concern = mongoc_write_concern_new();
if (zend_hash_find(props, "w", sizeof("w"), (void**) &w) == SUCCESS) {
if (Z_TYPE_PP(w) == IS_LONG) {
if (Z_LVAL_PP(w) < -3) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"w\" integer field to be >= -3", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
mongoc_write_concern_set_w(intern->write_concern, Z_LVAL_PP(w));
} else if (Z_TYPE_PP(w) == IS_STRING) {
if (strcmp(Z_STRVAL_PP(w), PHONGO_WRITE_CONCERN_W_MAJORITY) == 0) {
mongoc_write_concern_set_w(intern->write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
} else {
mongoc_write_concern_set_wtag(intern->write_concern, Z_STRVAL_PP(w));
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"w\" field to be integer or string", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if (zend_hash_find(props, "wtimeout", sizeof("wtimeout"), (void**) &wtimeout) == SUCCESS) {
if (Z_TYPE_PP(wtimeout) == IS_LONG) {
if (Z_LVAL_PP(wtimeout) < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" integer field to be >= 0", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
if (Z_LVAL_PP(wtimeout) > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" integer field to be <= %" PRId32, ZSTR_VAL(php_phongo_writeconcern_ce->name), INT32_MAX);
goto failure;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, (int64_t) Z_LVAL_PP(wtimeout));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"wtimeout\" field to be integer", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if (zend_hash_find(props, "j", sizeof("j"), (void**) &j) == SUCCESS) {
if (Z_TYPE_PP(j) == IS_BOOL) {
mongoc_write_concern_set_journal(intern->write_concern, Z_BVAL_PP(j));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "%s initialization requires \"j\" field to be boolean", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
#endif
return true;
failure:
mongoc_write_concern_destroy(intern->write_concern);
intern->write_concern = NULL;
return false;
} /* }}} */
/* {{{ proto void MongoDB\Driver\WriteConcern::__construct(integer|string $w[, integer $wtimeout[, boolean $journal]])
Constructs a new WriteConcern */
static PHP_METHOD(WriteConcern, __construct)
{
php_phongo_writeconcern_t* intern;
zend_error_handling error_handling;
zval * w, *journal;
phongo_long wtimeout = 0;
zend_replace_error_handling(EH_THROW, phongo_exception_from_phongo_domain(PHONGO_ERROR_INVALID_ARGUMENT), &error_handling TSRMLS_CC);
intern = Z_WRITECONCERN_OBJ_P(getThis());
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|lz", &w, &wtimeout, &journal) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
intern->write_concern = mongoc_write_concern_new();
if (Z_TYPE_P(w) == IS_LONG) {
if (Z_LVAL_P(w) < -3) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected w to be >= -3, %ld given", Z_LVAL_P(w));
return;
}
mongoc_write_concern_set_w(intern->write_concern, Z_LVAL_P(w));
} else if (Z_TYPE_P(w) == IS_STRING) {
if (strcmp(Z_STRVAL_P(w), PHONGO_WRITE_CONCERN_W_MAJORITY) == 0) {
mongoc_write_concern_set_w(intern->write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
} else {
mongoc_write_concern_set_wtag(intern->write_concern, Z_STRVAL_P(w));
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected w to be integer or string, %s given", PHONGO_ZVAL_CLASS_OR_TYPE_NAME_P(w));
return;
}
switch (ZEND_NUM_ARGS()) {
case 3:
if (Z_TYPE_P(journal) != IS_NULL) {
#ifdef ZEND_ENGINE_3
mongoc_write_concern_set_journal(intern->write_concern, zend_is_true(journal));
#else
mongoc_write_concern_set_journal(intern->write_concern, Z_BVAL_P(journal));
#endif
}
/* fallthrough */
case 2:
if (wtimeout < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected wtimeout to be >= 0, %" PHONGO_LONG_FORMAT " given", wtimeout);
return;
}
if (wtimeout > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT TSRMLS_CC, "Expected wtimeout to be <= %" PRId32 ", %" PHONGO_LONG_FORMAT " given", INT32_MAX, wtimeout);
return;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, (int64_t) wtimeout);
}
} /* }}} */
/* {{{ proto void MongoDB\BSON\WriteConcern::__set_state(array $properties)
*/
static PHP_METHOD(WriteConcern, __set_state)
{
php_phongo_writeconcern_t* intern;
HashTable* props;
zval* array;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {
RETURN_FALSE;
}
object_init_ex(return_value, php_phongo_writeconcern_ce);
intern = Z_WRITECONCERN_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_writeconcern_init_from_hash(intern, props TSRMLS_CC);
} /* }}} */
/* {{{ proto string|integer|null MongoDB\Driver\WriteConcern::getW()
Returns the WriteConcern "w" option */
static PHP_METHOD(WriteConcern, getW)
{
php_phongo_writeconcern_t* intern;
const char* wtag;
intern = Z_WRITECONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
wtag = mongoc_write_concern_get_wtag(intern->write_concern);
if (wtag) {
PHONGO_RETURN_STRING(wtag);
}
if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
PHONGO_RETURN_STRING(PHONGO_WRITE_CONCERN_W_MAJORITY);
}
if (mongoc_write_concern_get_w(intern->write_concern) != MONGOC_WRITE_CONCERN_W_DEFAULT) {
RETURN_LONG(mongoc_write_concern_get_w(intern->write_concern));
}
RETURN_NULL();
} /* }}} */
/* {{{ proto integer MongoDB\Driver\WriteConcern::getWtimeout()
Returns the WriteConcern "wtimeout" option */
static PHP_METHOD(WriteConcern, getWtimeout)
{
php_phongo_writeconcern_t* intern;
intern = Z_WRITECONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
/* Note: PHP currently enforces that wimeoutMS is a 32-bit integer, so
* casting will never truncate the value. This may change with PHPC-1411. */
RETURN_LONG((int32_t) mongoc_write_concern_get_wtimeout_int64(intern->write_concern));
} /* }}} */
/* {{{ proto null|boolean MongoDB\Driver\WriteConcern::getJournal()
Returns the WriteConcern "journal" option */
static PHP_METHOD(WriteConcern, getJournal)
{
php_phongo_writeconcern_t* intern;
intern = Z_WRITECONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
RETURN_BOOL(mongoc_write_concern_get_journal(intern->write_concern));
}
RETURN_NULL();
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\WriteConcern::isDefault()
Returns whether the write concern has not been modified (i.e. from a Manager
with no write concern URI options). */
static PHP_METHOD(WriteConcern, isDefault)
{
php_phongo_writeconcern_t* intern;
intern = Z_WRITECONCERN_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(mongoc_write_concern_is_default(intern->write_concern));
} /* }}} */
static HashTable* php_phongo_write_concern_get_properties_hash(zval* object, bool is_debug TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcern_t* intern;
HashTable* props;
const char* wtag;
int32_t w;
int32_t wtimeout;
intern = Z_WRITECONCERN_OBJ_P(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 4);
if (!intern->write_concern) {
return props;
}
wtag = mongoc_write_concern_get_wtag(intern->write_concern);
w = mongoc_write_concern_get_w(intern->write_concern);
/* Note: PHP currently enforces that wimeoutMS is a 32-bit integer, so
* casting will never truncate the value. This may change with PHPC-1411. */
wtimeout = (int32_t) mongoc_write_concern_get_wtimeout_int64(intern->write_concern);
#if PHP_VERSION_ID >= 70000
{
zval z_w;
if (wtag) {
ZVAL_STRING(&z_w, wtag);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
} else if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
ZVAL_STRING(&z_w, PHONGO_WRITE_CONCERN_W_MAJORITY);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
ZVAL_LONG(&z_w, w);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
zval z_j;
ZVAL_BOOL(&z_j, mongoc_write_concern_get_journal(intern->write_concern));
zend_hash_str_update(props, "j", sizeof("j") - 1, &z_j);
}
if (wtimeout != 0) {
zval z_wtimeout;
ZVAL_LONG(&z_wtimeout, wtimeout);
zend_hash_str_update(props, "wtimeout", sizeof("wtimeout") - 1, &z_wtimeout);
}
#else
{
zval* z_w;
if (wtag) {
MAKE_STD_ZVAL(z_w);
ZVAL_STRING(z_w, wtag, 1);
zend_hash_update(props, "w", sizeof("w"), &z_w, sizeof(z_w), NULL);
} else if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
MAKE_STD_ZVAL(z_w);
ZVAL_STRING(z_w, PHONGO_WRITE_CONCERN_W_MAJORITY, 1);
zend_hash_update(props, "w", sizeof("w"), &z_w, sizeof(z_w), NULL);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
MAKE_STD_ZVAL(z_w);
ZVAL_LONG(z_w, w);
zend_hash_update(props, "w", sizeof("w"), &z_w, sizeof(z_w), NULL);
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
zval* z_j;
MAKE_STD_ZVAL(z_j);
ZVAL_BOOL(z_j, mongoc_write_concern_get_journal(intern->write_concern));
zend_hash_update(props, "j", sizeof("j"), &z_j, sizeof(z_j), NULL);
}
if (wtimeout != 0) {
zval* z_wtimeout;
MAKE_STD_ZVAL(z_wtimeout);
ZVAL_LONG(z_wtimeout, wtimeout);
zend_hash_update(props, "wtimeout", sizeof("wtimeout"), &z_wtimeout, sizeof(z_wtimeout), NULL);
}
#endif
}
return props;
} /* }}} */
/* {{{ proto array MongoDB\Driver\WriteConcern::bsonSerialize()
*/
static PHP_METHOD(WriteConcern, bsonSerialize)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
ZVAL_ARR(return_value, php_phongo_write_concern_get_properties_hash(getThis(), true TSRMLS_CC));
convert_to_object(return_value);
} /* }}} */
/* {{{ MongoDB\Driver\WriteConcern function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteConcern___construct, 0, 0, 1)
ZEND_ARG_INFO(0, w)
ZEND_ARG_INFO(0, wtimeout)
ZEND_ARG_INFO(0, journal)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_WriteConcern___set_state, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, properties, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(ai_WriteConcern_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_writeconcern_me[] = {
/* clang-format off */
PHP_ME(WriteConcern, __construct, ai_WriteConcern___construct, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcern, __set_state, ai_WriteConcern___set_state, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(WriteConcern, getW, ai_WriteConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcern, getWtimeout, ai_WriteConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcern, getJournal, ai_WriteConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcern, isDefault, ai_WriteConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcern, bsonSerialize, ai_WriteConcern_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\WriteConcern object handlers */
static zend_object_handlers php_phongo_handler_writeconcern;
static void php_phongo_writeconcern_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcern_t* intern = Z_OBJ_WRITECONCERN(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->write_concern) {
mongoc_write_concern_destroy(intern->write_concern);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_writeconcern_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcern_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_writeconcern_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_writeconcern;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_writeconcern_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_writeconcern;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_writeconcern_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
*is_temp = 1;
return php_phongo_write_concern_get_properties_hash(object, true TSRMLS_CC);
} /* }}} */
static HashTable* php_phongo_writeconcern_get_properties(zval* object TSRMLS_DC) /* {{{ */
{
return php_phongo_write_concern_get_properties_hash(object, false TSRMLS_CC);
} /* }}} */
void php_phongo_writeconcern_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteConcern", php_phongo_writeconcern_me);
php_phongo_writeconcern_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_writeconcern_ce->create_object = php_phongo_writeconcern_create_object;
PHONGO_CE_FINAL(php_phongo_writeconcern_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_writeconcern_ce);
zend_class_implements(php_phongo_writeconcern_ce TSRMLS_CC, 1, php_phongo_serializable_ce);
memcpy(&php_phongo_handler_writeconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeconcern.get_debug_info = php_phongo_writeconcern_get_debug_info;
php_phongo_handler_writeconcern.get_properties = php_phongo_writeconcern_get_properties;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_writeconcern.free_obj = php_phongo_writeconcern_free_object;
php_phongo_handler_writeconcern.offset = XtOffsetOf(php_phongo_writeconcern_t, std);
#endif
zend_declare_class_constant_stringl(php_phongo_writeconcern_ce, ZEND_STRL("MAJORITY"), ZEND_STRL(PHONGO_WRITE_CONCERN_W_MAJORITY) TSRMLS_CC);
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/WriteConcernError.c 0000644 0000765 0000024 00000013537 13572250757 020326 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_writeconcernerror_ce;
/* {{{ proto integer MongoDB\Driver\WriteConcernError::getCode()
Returns the MongoDB error code */
static PHP_METHOD(WriteConcernError, getCode)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->code);
} /* }}} */
/* {{{ proto mixed MongoDB\Driver\WriteConcernError::getInfo()
Returns additional metadata for the error */
static PHP_METHOD(WriteConcernError, getInfo)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!Z_ISUNDEF(intern->info)) {
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&intern->info, 1, 0);
#else
RETURN_ZVAL(intern->info, 1, 0);
#endif
}
} /* }}} */
/* {{{ proto string MongoDB\Driver\WriteConcernError::getMessage()
Returns the actual error message from the server */
static PHP_METHOD(WriteConcernError, getMessage)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRING(intern->message);
} /* }}} */
/* {{{ MongoDB\Driver\WriteConcernError function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteConcernError_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_writeconcernerror_me[] = {
/* clang-format off */
PHP_ME(WriteConcernError, getCode, ai_WriteConcernError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcernError, getInfo, ai_WriteConcernError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteConcernError, getMessage, ai_WriteConcernError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_WriteConcernError_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_WriteConcernError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\WriteConcernError object handlers */
static zend_object_handlers php_phongo_handler_writeconcernerror;
static void php_phongo_writeconcernerror_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcernerror_t* intern = Z_OBJ_WRITECONCERNERROR(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->message) {
efree(intern->message);
}
if (!Z_ISUNDEF(intern->info)) {
zval_ptr_dtor(&intern->info);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_writeconcernerror_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcernerror_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_writeconcernerror_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_writeconcernerror;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_writeconcernerror_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_writeconcernerror;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_writeconcernerror_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_writeconcernerror_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_WRITECONCERNERROR_OBJ_P(object);
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "message", intern->message);
ADD_ASSOC_LONG_EX(&retval, "code", intern->code);
if (!Z_ISUNDEF(intern->info)) {
#if PHP_VERSION_ID >= 70000
Z_ADDREF(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", &intern->info);
#else
Z_ADDREF_P(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", intern->info);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "info");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_writeconcernerror_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteConcernError", php_phongo_writeconcernerror_me);
php_phongo_writeconcernerror_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_writeconcernerror_ce->create_object = php_phongo_writeconcernerror_create_object;
PHONGO_CE_FINAL(php_phongo_writeconcernerror_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_writeconcernerror_ce);
memcpy(&php_phongo_handler_writeconcernerror, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeconcernerror.get_debug_info = php_phongo_writeconcernerror_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_writeconcernerror.free_obj = php_phongo_writeconcernerror_free_object;
php_phongo_handler_writeconcernerror.offset = XtOffsetOf(php_phongo_writeconcernerror_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/WriteError.c 0000644 0000765 0000024 00000013753 13572250757 017016 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "phongo_compat.h"
#include "php_phongo.h"
zend_class_entry* php_phongo_writeerror_ce;
/* {{{ proto integer MongoDB\Driver\WriteError::getCode()
Returns the MongoDB error code */
static PHP_METHOD(WriteError, getCode)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->code);
} /* }}} */
/* {{{ proto integer MongoDB\Driver\WriteError::getIndex()
Returns the index of the operation in the BulkWrite to which this WriteError
corresponds. */
static PHP_METHOD(WriteError, getIndex)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->index);
} /* }}} */
/* {{{ proto string MongoDB\Driver\WriteError::getMessage()
Returns the actual error message from the server */
static PHP_METHOD(WriteError, getMessage)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_RETURN_STRING(intern->message);
} /* }}} */
/* {{{ proto mixed MongoDB\Driver\WriteError::getInfo()
Returns additional metadata for the error */
static PHP_METHOD(WriteError, getInfo)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!Z_ISUNDEF(intern->info)) {
#if PHP_VERSION_ID >= 70000
RETURN_ZVAL(&intern->info, 1, 0);
#else
RETURN_ZVAL(intern->info, 1, 0);
#endif
}
} /* }}} */
/* {{{ MongoDB\Driver\WriteError function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteError_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_writeerror_me[] = {
/* clang-format off */
PHP_ME(WriteError, getCode, ai_WriteError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteError, getIndex, ai_WriteError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteError, getMessage, ai_WriteError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteError, getInfo, ai_WriteError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_WriteError_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_WriteError_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\WriteError object handlers */
static zend_object_handlers php_phongo_handler_writeerror;
static void php_phongo_writeerror_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_writeerror_t* intern = Z_OBJ_WRITEERROR(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->message) {
efree(intern->message);
}
if (!Z_ISUNDEF(intern->info)) {
zval_ptr_dtor(&intern->info);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_writeerror_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_writeerror_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_writeerror_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_writeerror;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_writeerror_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_writeerror;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_writeerror_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_writeerror_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_WRITEERROR_OBJ_P(object);
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "message", intern->message);
ADD_ASSOC_LONG_EX(&retval, "code", intern->code);
ADD_ASSOC_LONG_EX(&retval, "index", intern->index);
if (!Z_ISUNDEF(intern->info)) {
#if PHP_VERSION_ID >= 70000
Z_ADDREF(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", &intern->info);
#else
Z_ADDREF_P(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", intern->info);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "info");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_writeerror_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteError", php_phongo_writeerror_me);
php_phongo_writeerror_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_writeerror_ce->create_object = php_phongo_writeerror_create_object;
PHONGO_CE_FINAL(php_phongo_writeerror_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_writeerror_ce);
memcpy(&php_phongo_handler_writeerror, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeerror.get_debug_info = php_phongo_writeerror_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_writeerror.free_obj = php_phongo_writeerror_free_object;
php_phongo_handler_writeerror.offset = XtOffsetOf(php_phongo_writeerror_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/MongoDB/WriteResult.c 0000644 0000765 0000024 00000037063 13572250757 017203 0 ustar alcaeus staff /*
* Copyright 2014-2017 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
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_array_api.h"
#include "phongo_compat.h"
#include "php_phongo.h"
#include "php_bson.h"
#define PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(iter, bson, key) \
if (bson_iter_init_find((iter), (bson), (key)) && BSON_ITER_HOLDS_INT32((iter))) { \
RETURN_LONG(bson_iter_int32((iter))); \
}
zend_class_entry* php_phongo_writeresult_ce;
static bool php_phongo_writeresult_get_writeconcernerror(php_phongo_writeresult_t* intern, zval* return_value TSRMLS_DC) /* {{{ */
{
bson_iter_t iter, child;
#if PHP_VERSION_ID >= 70000
zval writeconcernerror;
#else
zval* writeconcernerror = NULL;
#endif
ZVAL_NULL(return_value);
if (bson_iter_init_find(&iter, intern->reply, "writeConcernErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
bson_t cbson;
uint32_t len;
const uint8_t* data;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &len, &data);
if (!bson_init_static(&cbson, data, len)) {
continue;
}
#if PHP_VERSION_ID >= 70000
if (!phongo_writeconcernerror_init(&writeconcernerror, &cbson TSRMLS_CC)) {
zval_ptr_dtor(&writeconcernerror);
return false;
}
ZVAL_ZVAL(return_value, &writeconcernerror, 1, 1);
#else
MAKE_STD_ZVAL(writeconcernerror);
if (!phongo_writeconcernerror_init(writeconcernerror, &cbson TSRMLS_CC)) {
zval_ptr_dtor(&writeconcernerror);
return false;
}
ZVAL_ZVAL(return_value, writeconcernerror, 1, 1);
#endif
return true;
}
}
return true;
} /* }}} */
static bool php_phongo_writeresult_get_writeerrors(php_phongo_writeresult_t* intern, zval* return_value TSRMLS_DC) /* {{{ */
{
bson_iter_t iter, child;
array_init(return_value);
if (bson_iter_init_find(&iter, intern->reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
bson_t cbson;
uint32_t len;
const uint8_t* data;
#if PHP_VERSION_ID >= 70000
zval writeerror;
#else
zval* writeerror = NULL;
#endif
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &len, &data);
if (!bson_init_static(&cbson, data, len)) {
continue;
}
#if PHP_VERSION_ID >= 70000
if (!phongo_writeerror_init(&writeerror, &cbson TSRMLS_CC)) {
zval_ptr_dtor(&writeerror);
continue;
}
add_next_index_zval(return_value, &writeerror);
#else
MAKE_STD_ZVAL(writeerror);
if (!phongo_writeerror_init(writeerror, &cbson TSRMLS_CC)) {
zval_ptr_dtor(&writeerror);
continue;
}
add_next_index_zval(return_value, writeerror);
#endif
}
}
return true;
} /* }}} */
/* {{{ proto integer|null MongoDB\Driver\WriteResult::getInsertedCount()
Returns the number of documents that were inserted */
static PHP_METHOD(WriteResult, getInsertedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nInserted");
} /* }}} */
/* {{{ proto integer|null MongoDB\Driver\WriteResult::getMatchedCount()
Returns the number of documents that matched the update criteria */
static PHP_METHOD(WriteResult, getMatchedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nMatched");
} /* }}} */
/* {{{ proto integer|null MongoDB\Driver\WriteResult::getModifiedCount()
Returns the number of documents that were actually modified by an update */
static PHP_METHOD(WriteResult, getModifiedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nModified");
} /* }}} */
/* {{{ proto integer|null MongoDB\Driver\WriteResult::getDeletedCount()
Returns the number of documents that were deleted */
static PHP_METHOD(WriteResult, getDeletedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nRemoved");
} /* }}} */
/* {{{ proto integer|null MongoDB\Driver\WriteResult::getUpsertedCount()
Returns the number of documents that were upserted */
static PHP_METHOD(WriteResult, getUpsertedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nUpserted");
} /* }}} */
/* {{{ proto MongoDB\Driver\Server MongoDB\Driver\WriteResult::getServer()
Returns the Server from which the result originated */
static PHP_METHOD(WriteResult, getServer)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phongo_server_init(return_value, intern->client, intern->server_id TSRMLS_CC);
} /* }}} */
/* {{{ proto array MongoDB\Driver\WriteResult::getUpsertedIds()
Returns the identifiers generated by the server for upsert operations. */
static PHP_METHOD(WriteResult, getUpsertedIds)
{
bson_iter_t iter, child;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
uint32_t data_len;
const uint8_t* data = NULL;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type so we can
* easily access the "index" and "_id" fields. */
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &data_len, &data);
if (php_phongo_bson_to_zval_ex(data, data_len, &state)) {
#if PHP_VERSION_ID >= 70000
zval* zid = php_array_fetchc(&state.zchild, "_id");
add_index_zval(return_value, php_array_fetchc_long(&state.zchild, "index"), zid);
zval_add_ref(zid);
#else
zval* zid = php_array_fetchc(state.zchild, "_id");
add_index_zval(return_value, php_array_fetchc_long(state.zchild, "index"), zid);
zval_add_ref(&zid);
#endif
}
zval_ptr_dtor(&state.zchild);
}
}
} /* }}} */
/* {{{ proto WriteConcernError MongoDB\Driver\WriteResult::getWriteConcernError()
Return any write concern error that occurred */
static PHP_METHOD(WriteResult, getWriteConcernError)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_writeresult_get_writeconcernerror(intern, return_value TSRMLS_CC);
} /* }}} */
/* {{{ proto WriteError[] MongoDB\Driver\WriteResult::getWriteErrors()
Returns any write errors that occurred */
static PHP_METHOD(WriteResult, getWriteErrors)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_phongo_writeresult_get_writeerrors(intern, return_value TSRMLS_CC);
} /* }}} */
/* {{{ proto boolean MongoDB\Driver\WriteResult::isAcknowledged()
Returns whether the write operation was acknowledged (based on the write
concern). */
static PHP_METHOD(WriteResult, isAcknowledged)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(mongoc_write_concern_is_acknowledged(intern->write_concern));
} /* }}} */
/* {{{ MongoDB\Driver\WriteResult function entries */
ZEND_BEGIN_ARG_INFO_EX(ai_WriteResult_void, 0, 0, 0)
ZEND_END_ARG_INFO()
static zend_function_entry php_phongo_writeresult_me[] = {
/* clang-format off */
PHP_ME(WriteResult, getInsertedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getMatchedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getModifiedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getDeletedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getUpsertedCount, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getServer, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getUpsertedIds, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getWriteConcernError, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, getWriteErrors, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_ME(WriteResult, isAcknowledged, ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__construct, PHP_FN(MongoDB_disabled___construct), ai_WriteResult_void, ZEND_ACC_PRIVATE | ZEND_ACC_FINAL)
ZEND_NAMED_ME(__wakeup, PHP_FN(MongoDB_disabled___wakeup), ai_WriteResult_void, ZEND_ACC_PUBLIC | ZEND_ACC_FINAL)
PHP_FE_END
/* clang-format on */
};
/* }}} */
/* {{{ MongoDB\Driver\WriteResult object handlers */
static zend_object_handlers php_phongo_handler_writeresult;
static void php_phongo_writeresult_free_object(phongo_free_object_arg* object TSRMLS_DC) /* {{{ */
{
php_phongo_writeresult_t* intern = Z_OBJ_WRITERESULT(object);
zend_object_std_dtor(&intern->std TSRMLS_CC);
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->write_concern) {
mongoc_write_concern_destroy(intern->write_concern);
}
#if PHP_VERSION_ID < 70000
efree(intern);
#endif
} /* }}} */
static phongo_create_object_retval php_phongo_writeresult_create_object(zend_class_entry* class_type TSRMLS_DC) /* {{{ */
{
php_phongo_writeresult_t* intern = NULL;
intern = PHONGO_ALLOC_OBJECT_T(php_phongo_writeresult_t, class_type);
zend_object_std_init(&intern->std, class_type TSRMLS_CC);
object_properties_init(&intern->std, class_type);
#if PHP_VERSION_ID >= 70000
intern->std.handlers = &php_phongo_handler_writeresult;
return &intern->std;
#else
{
zend_object_value retval;
retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, php_phongo_writeresult_free_object, NULL TSRMLS_CC);
retval.handlers = &php_phongo_handler_writeresult;
return retval;
}
#endif
} /* }}} */
static HashTable* php_phongo_writeresult_get_debug_info(zval* object, int* is_temp TSRMLS_DC) /* {{{ */
{
php_phongo_writeresult_t* intern;
zval retval = ZVAL_STATIC_INIT;
bson_iter_t iter;
intern = Z_WRITERESULT_OBJ_P(object);
*is_temp = 1;
array_init_size(&retval, 9);
#define PHONGO_WRITERESULT_SCP(field) \
if (bson_iter_init_find(&iter, intern->reply, (field)) && BSON_ITER_HOLDS_INT32(&iter)) { \
ADD_ASSOC_LONG_EX(&retval, (field), bson_iter_int32(&iter)); \
} else { \
ADD_ASSOC_NULL_EX(&retval, (field)); \
}
PHONGO_WRITERESULT_SCP("nInserted");
PHONGO_WRITERESULT_SCP("nMatched");
PHONGO_WRITERESULT_SCP("nModified");
PHONGO_WRITERESULT_SCP("nRemoved");
PHONGO_WRITERESULT_SCP("nUpserted");
#undef PHONGO_WRITERESULT_SCP
if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter)) {
uint32_t len;
const uint8_t* data;
php_phongo_bson_state state = PHONGO_BSON_STATE_INITIALIZER;
/* Use native arrays for debugging output */
state.map.root_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.map.document_type = PHONGO_TYPEMAP_NATIVE_ARRAY;
bson_iter_array(&iter, &len, &data);
php_phongo_bson_to_zval_ex(data, len, &state);
#if PHP_VERSION_ID >= 70000
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &state.zchild);
#else
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", state.zchild);
#endif
} else {
#if PHP_VERSION_ID >= 70000
zval upsertedIds;
array_init(&upsertedIds);
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &upsertedIds);
#else
zval* upsertedIds = NULL;
MAKE_STD_ZVAL(upsertedIds);
array_init(upsertedIds);
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", upsertedIds);
#endif
}
{
#if PHP_VERSION_ID >= 70000
zval writeerrors;
php_phongo_writeresult_get_writeerrors(intern, &writeerrors TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "writeErrors", &writeerrors);
#else
zval* writeerrors = NULL;
MAKE_STD_ZVAL(writeerrors);
php_phongo_writeresult_get_writeerrors(intern, writeerrors TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "writeErrors", writeerrors);
#endif
}
{
#if PHP_VERSION_ID >= 70000
zval writeconcernerror;
php_phongo_writeresult_get_writeconcernerror(intern, &writeconcernerror TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcernError", &writeconcernerror);
#else
zval* writeconcernerror = NULL;
MAKE_STD_ZVAL(writeconcernerror);
php_phongo_writeresult_get_writeconcernerror(intern, writeconcernerror TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcernError", writeconcernerror);
#endif
}
if (intern->write_concern) {
#if PHP_VERSION_ID >= 70000
zval write_concern;
phongo_writeconcern_init(&write_concern, intern->write_concern);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcern", &write_concern);
#else
zval* write_concern = NULL;
MAKE_STD_ZVAL(write_concern);
phongo_writeconcern_init(write_concern, intern->write_concern TSRMLS_CC);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcern", write_concern);
#endif
} else {
ADD_ASSOC_NULL_EX(&retval, "writeConcern");
}
return Z_ARRVAL(retval);
} /* }}} */
/* }}} */
void php_phongo_writeresult_init_ce(INIT_FUNC_ARGS) /* {{{ */
{
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteResult", php_phongo_writeresult_me);
php_phongo_writeresult_ce = zend_register_internal_class(&ce TSRMLS_CC);
php_phongo_writeresult_ce->create_object = php_phongo_writeresult_create_object;
PHONGO_CE_FINAL(php_phongo_writeresult_ce);
PHONGO_CE_DISABLE_SERIALIZATION(php_phongo_writeresult_ce);
memcpy(&php_phongo_handler_writeresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeresult.get_debug_info = php_phongo_writeresult_get_debug_info;
#if PHP_VERSION_ID >= 70000
php_phongo_handler_writeresult.free_obj = php_phongo_writeresult_free_object;
php_phongo_handler_writeresult.offset = XtOffsetOf(php_phongo_writeresult_t, std);
#endif
} /* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
mongodb-1.6.1/src/contrib/php_array_api.h 0000644 0000765 0000024 00000051015 13572250757 017701 0 ustar alcaeus staff /* +----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sara Golemon (pollita@php.net) |
+----------------------------------------------------------------------+
*/
#ifndef PHP_ARRAY_API_H
#define PHP_ARRAY_API_H
#include "zend.h"
#include "zend_execute.h"
#include "zend_API.h"
#include "zend_operators.h"
#include "zend_hash.h"
#include "zend_list.h"
#ifdef ZEND_ENGINE_3
# define PAA_LENGTH_ADJ(l) (l)
# define PAA_SYM_EXISTS zend_symtable_str_exists
# define PAA_SYM_DEL zend_symtable_str_del
# define PAA_LONG zend_long
# define PAA_ULONG zend_ulong
#else
# define PAA_LENGTH_ADJ(l) (l+1)
# define PAA_SYM_EXISTS zend_symtable_exists
# define PAA_SYM_DEL zend_symtable_del
# define PAA_LONG long
# define PAA_ULONG ulong
#endif
/**
* All APIs in this file follow a general format:
*
* php_array_{$verb}{$modifier}_{$type}(zval *zarr, ...)
*
* $verb is one of:
* exists - Boolean check whether the array offset exists
* fetch - Retrieve the value at $zarr[$key]
* unset - Delete the named offset from the array
*
* $modifier specifies what type of offset (key) is being used:
* - NULL terminated string variable, unknown length
* l - NULL terminated string variable, known length
* l_safe - String variable of known length, not necessarily NULL terminated
* n - Long (integer) offset
* c - NULL terminated string literal (e.g. "foo" rather than foo)
* z - zval* offset, type should be NULL, BOOL, LONG, DOUBLE, or STRING
*
* $type is specific to the "fetch" verb:
* - Fetch a zval* of any type
* bool - Fetch a zend_bool (converting as needed)
* long - Fetch a long (converting as needed)
* double - Fetch a double (converting as needed)
* string - Fetch a string (converting as needed, caller may need to free)
* array - Fetch an array (no conversion from other types)
* object - Fetch an object (no conversion, type spec optional)
* resource - Fetch a resource (no conversion, type spec mandatory)
*
* See the specific subsection for additional details
*/
/* isset($zarr[$key]) - Check for the existence of a key within an array
*
* zend_bool php_array_exists(zval *zarr, const char *key)
* zend_bool php_array_existsc(zval *zarr, const char *litstr)
* zend_bool php_array_existsl(zval *zarr, const char *key, int key_len)
* zend_bool php_array_existsl_safe(zval *zarr, const char *key, int key_len)
* zend_bool php_array_existsn(zval *zarr, unsigned long idx)
* zend_bool php_array_existsz(zval *zarr, zval *key)
*/
static inline
zend_bool php_array_exists(zval *zarr, const char *key) {
return PAA_SYM_EXISTS(Z_ARRVAL_P(zarr), key, PAA_LENGTH_ADJ(strlen(key)));
}
#define php_array_existsc(zarr, litstr) \
PAA_SYM_EXISTS(Z_ARRVAL_P(zarr), litstr, PAA_LENGTH_ADJ(sizeof(litstr) - 1))
#define php_array_existsl(zarr, key, len) \
PAA_SYM_EXISTS(Z_ARRVAL_P(zarr), key, PAA_LENGTH_ADJ(len))
static inline
zend_bool php_array_existsl_safe(zval *zarr, const char *key, int key_len) {
#ifdef ZEND_ENGINE_3
zend_string *keystr = zend_string_init(key, key_len, 0);
zend_bool ret = zend_symtable_exists(Z_ARRVAL_P(zarr), keystr);
zend_string_release(keystr);
#else
char *k = estrndup(key, key_len);
zend_bool ret = zend_symtable_exists(Z_ARRVAL_P(zarr), k, key_len + 1);
efree(k);
#endif
return ret;
}
#define php_array_existsn(zarr, idx) \
zend_hash_index_exists(Z_ARRVAL_P(zarr), idx)
static inline
zend_bool php_array_existsz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
return php_array_existsc(zarr, "");
#ifdef ZEND_ENGINE_3
case IS_FALSE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), 0);
case IS_TRUE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), 1);
#else
case IS_BOOL: /* fallthrough */
#endif
case IS_LONG:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), Z_LVAL_P(key));
case IS_DOUBLE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr),
zend_dval_to_lval(Z_DVAL_P(key)));
case IS_STRING:
return php_array_existsl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
default:
return 0;
}
}
/* =$zarr[$key] - Fetch a zval (or appropriate type) from an array
*
* Methods returning pointers yield NULL on key not existing,
* others yield 0, false, etc... as appropriate.
* Callers needing to distinguish empty scalars from non-existent
* scalars should use php_array_exists*() or fetch the zval then convert.
*
* If the type of the value does not match what is requested
* it will be implicitly converted (if possible).
*
* See each type section for specific prototypes
*
* php_array_fetch* - Fetch a zval
* php_array_fetch*_bool - Fetch a boolean
* php_array_fetch*_long - Fetch a long
* php_array_fetch*_double - Fetch a double
* php_array_fetch*_string - Fetch a string (must be efree()'d by caller)
* php_array_fetch*_array - Fetch an array
* php_array_fetch*_resource - Fetch a resource or a specific type
* php_array_fetch*_object - Fetch an object
*
* For each result type, there are six key forms:
* php_array_fetch_T(zval *zarr, const char *key, ...)
* NULL terminated string key
* php_array_fetchc_T(zval *zarr, const char *litkey, ...)
* String literal key
* php_array_fetchl_T(zval *zarr, const char *key, int key_len, ...)
* NULL terminated string key of known length
* php_array_fetchl_safe_T(zval *zarr, const char *key, int key_len, ...)
* String key of known length, may not be NULL terminated
* php_array_fetchn_T(zval *zarr, unsigned long idx, ...)
* Numeric key
* php_array_fetchz_T(zval *zarr, zval *key, ...)
* zval* key
*/
/* Fetch zval*
*
* zval *php_array_fetch(zval *zarr, const char *key)
* zval *php_array_fetchl(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchl_safe(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchn(zval *zarr, unsigned long idx)
* zval *php_array_fetchc(zval *zarr, const char *litstr)
* zval *php_array_fetchz(zval *zarr, zval *key)
*/
static inline
zval *php_array_fetchl(zval *zarr, const char *key, int key_len) {
#ifdef ZEND_ENGINE_3
return zend_symtable_str_find(Z_ARRVAL_P(zarr), key, key_len);
#else
zval **ppzval;
if (FAILURE == zend_symtable_find(Z_ARRVAL_P(zarr),
key, key_len + 1,
(void**)&ppzval)) {
return NULL;
}
return *ppzval;
#endif
}
static inline
zval *php_array_fetch(zval *zarr, const char *key) {
return php_array_fetchl(zarr, key, strlen(key));
}
#define php_array_fetchc(zarr, litstr) php_array_fetchl(zarr, litstr, sizeof(litstr)-1)
static inline
zval *php_array_fetchl_safe(zval *zarr, const char *key, int key_len) {
#ifdef ZEND_ENGINE_3
zend_string *keystr = zend_string_init(key, key_len, 0);
zval *ret = zend_symtable_find(Z_ARRVAL_P(zarr), keystr);
zend_string_release(keystr);
#else
char *k = estrndup(key, key_len);
zval *ret = php_array_fetchl(zarr, k, key_len);
efree(k);
#endif
return ret;
}
static inline
zval *php_array_fetchn(zval *zarr, PAA_ULONG idx) {
#ifdef ZEND_ENGINE_3
return zend_hash_index_find(Z_ARRVAL_P(zarr), idx);
#else
zval **ppzval;
if (FAILURE == zend_hash_index_find(Z_ARRVAL_P(zarr),
idx, (void**)&ppzval)) {
return NULL;
}
return *ppzval;
#endif
}
static inline
zval *php_array_fetchz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
return php_array_fetchn(zarr, 0);
#ifdef ZEND_ENGINE_3
case IS_FALSE:
return php_array_fetchn(zarr, 0);
case IS_TRUE:
return php_array_fetchn(zarr, 1);
#else
case IS_BOOL: /* fallthrough */
#endif
case IS_LONG:
return php_array_fetchn(zarr, Z_LVAL_P(key));
case IS_DOUBLE:
return php_array_fetchn(zarr, (long)Z_DVAL_P(key));
case IS_STRING:
return php_array_fetchl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
default:
return NULL;
}
}
#define PHP_ARRAY_FETCH_TYPE_MAP(ctype, ztype) \
static inline ctype php_array_fetch_##ztype(zval *zarr, const char *key) \
{ return php_array_zval_to_##ztype(php_array_fetch(zarr, key)); } \
static inline ctype php_array_fetchl_##ztype(zval *zarr, const char *key, int key_len) \
{ return php_array_zval_to_##ztype(php_array_fetchl(zarr, key, key_len)); } \
static inline ctype php_array_fetchl_safe_##ztype(zval *zarr, const char *key, int key_len) \
{ return php_array_zval_to_##ztype(php_array_fetchl_safe(zarr, key, key_len)); } \
static inline ctype php_array_fetchn_##ztype(zval *zarr, PAA_ULONG idx) \
{ return php_array_zval_to_##ztype(php_array_fetchn(zarr, idx)); } \
static inline ctype php_array_fetchz_##ztype(zval *zarr, zval *key) \
{ return php_array_zval_to_##ztype(php_array_fetchz(zarr, key)); }
/* Fetch zend_bool
*
* zend_bool php_array_fetch_bool(zval *zarr, const char *key)
* zend_bool php_array_fetchl_bool(zval *zarr, const char *key, int key_len)
* zend_bool php_array_fetchl_safe_bool(zval *zarr, const char *key, int key_len)
* zend_bool php_array_fetchn_bool(zval *zarr, unsigned long idx)
* zend_bool php_array_fetchc_bool(zval *zarr, const char *litstr)
* zend_bool php_array_fetchz_bool(zval *zarr, zval *key)
*/
static inline
zend_bool php_array_zval_to_bool(zval *z) {
return z && zend_is_true(z);
}
PHP_ARRAY_FETCH_TYPE_MAP(zend_bool, bool)
#define php_array_fetchc_bool(zarr, litstr) \
php_array_zval_to_bool(php_array_fetchc(zarr, litstr))
/* Fetch long
*
* long php_array_fetch_long(zval *zarr, const char *key)
* long php_array_fetchl_long(zval *zarr, const char *key, int key_len)
* long php_array_fetchl_safe_long(zval *zarr, const char *key, int key_len)
* long php_array_fetchn_long(zval *zarr, unsigned long idx)
* long php_array_fetchc_long(zval *zarr, const char *litstr)
* long php_array_fetchz_long(zval *zarr, zval *key)
*/
static inline
PAA_LONG php_array_zval_to_long(zval *z) {
if (!z) { return 0; }
switch(Z_TYPE_P(z)) {
case IS_NULL: return 0;
#ifdef ZEND_ENGINE_3
case IS_FALSE: return 0;
case IS_TRUE: return 1;
#else
case IS_BOOL: return Z_BVAL_P(z);
#endif
case IS_LONG: return Z_LVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_long(&c);
return Z_LVAL(c);
}
}
}
PHP_ARRAY_FETCH_TYPE_MAP(PAA_LONG, long)
#define php_array_fetchc_long(zarr, litstr) \
php_array_zval_to_long(php_array_fetchc(zarr, litstr))
/* Fetch double
*
* double php_array_fetch_double(zval *zarr, const char *key)
* double php_array_fetchl_double(zval *zarr, const char *key, int key_len)
* double php_array_fetchl_safe_double(zval *zarr, const char *key, int key_len)
* double php_array_fetchn_double(zval *zarr, unsigned long idx)
* double php_array_fetchc_double(zval *zarr, const char *litstr)
* double php_array_fetchz_double(zval *zarr, zval *key)
*/
static inline
double php_array_zval_to_double(zval *z) {
if (!z) { return 0.0; }
switch (Z_TYPE_P(z)) {
case IS_NULL: return 0.0;
#ifdef ZEND_ENGINE_3
case IS_FALSE: return 0.0;
case IS_TRUE: return 1.0;
#else
case IS_BOOL: return (double)Z_BVAL_P(z);
#endif
case IS_LONG: return (double)Z_LVAL_P(z);
case IS_DOUBLE: return Z_DVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_double(&c);
return Z_DVAL(c);
}
}
}
PHP_ARRAY_FETCH_TYPE_MAP(double, double)
#define php_array_fetchc_double(zarr, litstr) \
php_array_zval_to_double(php_array_fetchc(zarr, litstr))
/* Fetch string
*
* If the pfree is set to 1 on exit, then the return value is owned by the caller
* and must be efree()'d once it is no longer in use.
*
* plen is populated with the binary safe length of the string returned.
*
* char *php_array_fetch_string(zval *zarr, const char *key, int *plen, zend_bool *pfree)
* char *php_array_fetchl_string(zval *zarr, const char *key, int key_len, int *plen, zend_bool *pfree)
* char *php_array_fetchl_safe_string(zval *zarr, const char *key, int key_len, int *plen, zend_bool *pfree)
* char *php_array_fetchn_string(zval *zarr, unsigned long idx, int *plen, zend_bool *pfree)
* char *php_array_fetchc_string(zval *zarr, const char *litstr, int *plen, zend_bool *pfree)
* char *php_array_fetchz_string(zval *zarr, zval *key, int *plen, zend_bool *pfree)
*/
static inline
char *php_array_zval_to_string(zval *z, int *plen, zend_bool *pfree) {
*plen = 0;
*pfree = 0;
if (!z) { return NULL; }
switch (Z_TYPE_P(z)) {
case IS_NULL:
return (char *)"";
case IS_STRING:
*plen = Z_STRLEN_P(z);
return Z_STRVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_string(&c);
#ifdef ZEND_ENGINE_3
*pfree = ! IS_INTERNED(Z_STR(c));
#else
*pfree = ! IS_INTERNED(Z_STRVAL(c));
#endif
*plen = Z_STRLEN(c);
return Z_STRVAL(c);
}
}
}
#define php_array_fetch_string(zarr, key, plen, pfree) \
php_array_zval_to_string(php_array_fetch(zarr, key), plen, pfree)
#define php_array_fetchl_string(zarr, key, key_len, plen, pfree) \
php_array_zval_to_string(php_array_fetchl(zarr, key, key_len), plen, pfree)
#define php_array_fetchl_safe_string(zarr, key, key_len, plen, pfree) \
php_array_zval_to_string(php_array_fetchl_safe(zarr, key, key_len), plen, pfree)
#define php_array_fetchn_string(zarr, idx, plen, pfree) \
php_array_zval_to_string(php_array_fetchn(zarr, idx), plen, pfree)
#define php_array_fetchc_string(zarr, litstr, plen, pfree) \
php_array_zval_to_string(php_array_fetchc(zarr, litstr), plen, pfree)
#define php_array_fetchz_string(zarr, key, plen, pfree) \
php_array_zval_to_string(php_array_fetchz(zarr, key), plen, pfree)
/* Fetch array
*
* No implicit conversion is performed.
*
* If the value is an array, then that zval is returned,
* otherwise NULL is returned.
*
* zval *php_array_fetch_array(zval *zarr, const char *key)
* zval *php_array_fetchl_array(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchl_safe_array(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchn_array(zval *zarr, unsigned long idx)
* zval *php_array_fetchc_array(zval *zarr, const char *litstr)
* zval *php_array_fetchz_array(zval *zarr, zval *key)
*/
static inline zval *php_array_zval_to_array(zval *zarr) {
return (zarr && (Z_TYPE_P(zarr) == IS_ARRAY)) ? zarr : NULL;
}
PHP_ARRAY_FETCH_TYPE_MAP(zval*, array)
#define php_array_fetchc_array(zarr, litstr) \
php_array_zval_to_array(php_array_fetchc(zarr, litstr))
/* count($arr) - Count number of elements in the array
*
* int php_array_count(zval *arr)
*/
#define php_array_count(zarr) zend_hash_num_elements(Z_ARRVAL_P(zarr))
/* Fetch resource
*
* No implicit conversion is performed.
*
* If the value is a resource of the named type,
* then the pointer for it is returned,
* otherwise NULL is returned.
*
* To test for multiple resource types (e.g. 'stream' and 'persistent stream')
* Fetch a generic zval* and use Zend's ZEND_FETCH_RESOURCE() macro.
*
* zval *php_array_fetch_resource(zval *zarr, const char *key, int le)
* zval *php_array_fetchl_resource(zval *zarr, const char *key, int key_len, int le)
* zval *php_array_fetchl_safe_resource(zval *zarr, const char *key, int key_len, int le)
* zval *php_array_fetchn_resource(zval *zarr, unsigned long idx, int le)
* zval *php_array_fetchc_resource(zval *zarr, const char *litstr, int le)
* zval *php_array_fetchz_resource(zval *zarr, zval *key, int le)
*/
static inline
void *php_array_zval_to_resource(zval *z, int le TSRMLS_DC) {
#ifdef ZEND_ENGINE_3
return zend_fetch_resource_ex(z, NULL, le);
#else
void *ret;
int rtype;
if (!z || Z_TYPE_P(z) != IS_RESOURCE) { return NULL; }
ret = zend_list_find(Z_RESVAL_P(z), &rtype);
if (!ret || (rtype != le)) {
return NULL;
}
return ret;
#endif
}
#define php_array_fetch_resource(zarr, key, le) \
php_array_zval_to_resource(php_array_fetch(zarr, key), le TSRMLS_CC)
#define php_array_fetchl_resource(zarr, key, key_len, le) \
php_array_zval_to_resource(php_array_fetchl(zarr, key, key_len), le TSRMLS_CC)
#define php_array_fetchl_safe_resource(zarr, key, key_len, le) \
php_array_zval_to_resource(php_array_fetchl_safe(zarr, key, key_len), le TSRMLS_CC)
#define php_array_fetchn_resource(zarr, idx, le) \
php_array_zval_to_resource(php_array_fetchn(zarr, idx), le TSRMLS_CC)
#define php_array_fetchc_resource(zarr, litstr, le) \
php_array_zval_to_resource(php_array_fetchc(zarr, litstr), le TSRMLS_CC)
#define php_array_fetchz_resource(zarr, key, le) \
php_array_zval_to_resource(php_array_fetchz(zarr, key), le TSRMLS_CC)
/* Fetch Object
*
* Fetch an object of a specific or non-specific type (pass ce == NULL)
*
* No implicit conversion is performed
*
* zval *php_array_fetch_object(zval *zarr, const char *key, zend_class_entry *ce)
* zval *php_array_fetchl_object(zval *zarr, const char *key, int key_len, zend_class_entry *ce)
* zval *php_array_fetchl_safe_object(zval *zarr, const char *key, int key_len, zend_class_entry *ce)
* zval *php_array_fetchn_object(zval *zarr, unsigned long idx, zend_class_entry *ce)
* zval *php_array_fetchc_object(zval *zarr, const char *litstr, zend_class_entry *ce)
* zval *php_array_fetchz_object(zval *zarr, zval *key, zend_class_entry *ce)
*/
static inline
zval *php_array_zval_to_object(zval *z, zend_class_entry *ce TSRMLS_DC) {
return (z && (Z_TYPE_P(z) == IS_OBJECT) &&
((!ce) || instanceof_function(Z_OBJCE_P(z), ce TSRMLS_CC))) ? z : NULL;
}
#define php_array_fetch_object(zarr, key, ce) \
php_array_zval_to_object(php_array_fetch(zarr, key), ce TSRMLS_CC)
#define php_array_fetchl_object(zarr, key, len, ce) \
php_array_zval_to_object(php_array_fetchl(zarr, key, len), ce TSRMLS_CC)
#define php_array_fetchl_safe_object(zarr, key, len, ce) \
php_array_zval_to_object(php_array_fetchl_safe(zarr, key, len), ce TSRMLS_CC)
#define php_array_fetchn_object(zarr, idx, ce) \
php_array_zval_to_object(php_array_fetchn(zarr, idx), ce TSRMLS_CC)
#define php_array_fetchc_object(zarr, litstr, ce) \
php_array_zval_to_object(php_array_fetchc(zarr, litstr), ce TSRMLS_CC)
#define php_array_fetchz_object(zarr, key, ce) \
php_array_zval_to_object(php_array_fetchz(zarr, key), ce TSRMLS_CC)
/* unset($zarr[$key]) - Erase a key from an array
*
* void php_array_unset(zval *zarr, const char *key)
* void php_array_unsetl(zval *zarr, const char *key, int key_len)
* void php_array_unsetl_safe(zval *zarr, const char *key, int key_len)
* void php_array_unsetn(zval *zarr, long idx)
* void php_array_unsetc(zval *zarr, const char *litstr)
* void php_array_unsetz(zval *zarr, zval *key)
*/
static inline
void php_array_unset(zval *zarr, const char *key) {
PAA_SYM_DEL(Z_ARRVAL_P(zarr), key, PAA_LENGTH_ADJ(strlen(key)));
}
#define php_array_unsetl(zarr, key, len) \
PAA_SYM_DEL(Z_ARRVAL_P(zarr), key, PAA_LENGTH_ADJ(len))
static inline
void php_array_unsetl_safe(zval *zarr, const char *key, int key_len) {
char *k = estrndup(key, key_len);
PAA_SYM_DEL(Z_ARRVAL_P(zarr), k, PAA_LENGTH_ADJ(key_len));
efree(k);
}
#define php_array_unsetn(zarr, idx) \
zend_symtable_index_del(Z_ARRVAL_P(zarr), idx)
#define php_array_unsetc(zarr, litstr) \
PAA_SYM_DEL(Z_ARRVAL_P(zarr), litstr, PAA_LENGTH_ADJ(sizeof(litstr) - 1))
static inline void php_array_unsetz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
zend_hash_index_del(Z_ARRVAL_P(zarr), 0);
return;
#ifdef ZEND_ENGINE_3
case IS_FALSE:
zend_hash_index_del(Z_ARRVAL_P(zarr), 0);
return;
case IS_TRUE:
zend_hash_index_del(Z_ARRVAL_P(zarr), 1);
return;
#else
case IS_BOOL: /* fallthrough */
#endif
case IS_LONG:
zend_hash_index_del(Z_ARRVAL_P(zarr), Z_LVAL_P(key));
return;
case IS_DOUBLE:
zend_hash_index_del(Z_ARRVAL_P(zarr), (long)Z_DVAL_P(key));
break;
case IS_STRING:
php_array_unsetl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
break;
}
}
#endif /* PHP_ARRAY_API_H */
mongodb-1.6.1/src/libmongoc/src/common/common-b64-private.h 0000644 0000765 0000024 00000001674 13572250757 023012 0 ustar alcaeus staff /*
* Copyright 2018-present 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 "common-prelude.h"
#ifndef COMMON_B64_PRIVATE_H
#define COMMON_B64_PRIVATE_H
#include
int
bson_b64_ntop (uint8_t const *src,
size_t srclength,
char *target,
size_t targsize);
int
bson_b64_pton (char const *src, uint8_t *target, size_t targsize);
#endif /* COMMON_B64_PRIVATE_H */
mongodb-1.6.1/src/libmongoc/src/common/common-b64.c 0000644 0000765 0000024 00000043500 13572250757 021327 0 ustar alcaeus staff /*
* Copyright (c) 1996, 1998 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
/*
* Portions Copyright (c) 1995 by International Business Machines, Inc.
*
* International Business Machines, Inc. (hereinafter called IBM) grants
* permission under its copyrights to use, copy, modify, and distribute this
* Software with or without fee, provided that the above copyright notice and
* all paragraphs of this notice appear in all copies, and that the name of IBM
* not be used in connection with the marketing of any product incorporating
* the Software or modifications thereof, without specific, written prior
* permission.
*
* To the extent it has a right to do so, IBM grants an immunity from suit
* under its patents, if any, for the use, sale or manufacture of products to
* the extent that such products are used for performing Domain Name System
* dynamic updates in TCP/IP networks by means of the Software. No immunity is
* granted for any product per se or for any other function of any product.
*
* THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
* DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
* IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#include "bson/bson.h"
#include "common-b64-private.h"
#define Assert(Cond) \
if (!(Cond)) \
abort ()
static const char Base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char Pad64 = '=';
/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
* The following encoding technique is taken from RFC 1521 by Borenstein
* and Freed. It is reproduced here in a slightly edited form for
* convenience.
*
* A 65-character subset of US-ASCII is used, enabling 6 bits to be
* represented per printable character. (The extra 65th character, "=",
* is used to signify a special processing function.)
*
* The encoding process represents 24-bit groups of input bits as output
* strings of 4 encoded characters. Proceeding from left to right, a
* 24-bit input group is formed by concatenating 3 8-bit input groups.
* These 24 bits are then treated as 4 concatenated 6-bit groups, each
* of which is translated into a single digit in the base64 alphabet.
*
* Each 6-bit group is used as an index into an array of 64 printable
* characters. The character referenced by the index is placed in the
* output string.
*
* Table 1: The Base64 Alphabet
*
* Value Encoding Value Encoding Value Encoding Value Encoding
* 0 A 17 R 34 i 51 z
* 1 B 18 S 35 j 52 0
* 2 C 19 T 36 k 53 1
* 3 D 20 U 37 l 54 2
* 4 E 21 V 38 m 55 3
* 5 F 22 W 39 n 56 4
* 6 G 23 X 40 o 57 5
* 7 H 24 Y 41 p 58 6
* 8 I 25 Z 42 q 59 7
* 9 J 26 a 43 r 60 8
* 10 K 27 b 44 s 61 9
* 11 L 28 c 45 t 62 +
* 12 M 29 d 46 u 63 /
* 13 N 30 e 47 v
* 14 O 31 f 48 w (pad) =
* 15 P 32 g 49 x
* 16 Q 33 h 50 y
*
* Special processing is performed if fewer than 24 bits are available
* at the end of the data being encoded. A full encoding quantum is
* always completed at the end of a quantity. When fewer than 24 input
* bits are available in an input group, zero bits are added (on the
* right) to form an integral number of 6-bit groups. Padding at the
* end of the data is performed using the '=' character.
*
* Since all base64 input is an integral number of octets, only the
* following cases can arise:
*
* (1) the final quantum of encoding input is an integral
* multiple of 24 bits; here, the final unit of encoded
* output will be an integral multiple of 4 characters
* with no "=" padding,
* (2) the final quantum of encoding input is exactly 8 bits;
* here, the final unit of encoded output will be two
* characters followed by two "=" padding characters, or
* (3) the final quantum of encoding input is exactly 16 bits;
* here, the final unit of encoded output will be three
* characters followed by one "=" padding character.
*/
int
bson_b64_ntop (uint8_t const *src,
size_t srclength,
char *target,
size_t targsize)
{
size_t datalength = 0;
uint8_t input[3];
uint8_t output[4];
size_t i;
while (2 < srclength) {
input[0] = *src++;
input[1] = *src++;
input[2] = *src++;
srclength -= 3;
output[0] = input[0] >> 2;
output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
output[3] = input[2] & 0x3f;
Assert (output[0] < 64);
Assert (output[1] < 64);
Assert (output[2] < 64);
Assert (output[3] < 64);
if (datalength + 4 > targsize) {
return -1;
}
target[datalength++] = Base64[output[0]];
target[datalength++] = Base64[output[1]];
target[datalength++] = Base64[output[2]];
target[datalength++] = Base64[output[3]];
}
/* Now we worry about padding. */
if (0 != srclength) {
/* Get what's left. */
input[0] = input[1] = input[2] = '\0';
for (i = 0; i < srclength; i++) {
input[i] = *src++;
}
output[0] = input[0] >> 2;
output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
Assert (output[0] < 64);
Assert (output[1] < 64);
Assert (output[2] < 64);
if (datalength + 4 > targsize) {
return -1;
}
target[datalength++] = Base64[output[0]];
target[datalength++] = Base64[output[1]];
if (srclength == 1) {
target[datalength++] = Pad64;
} else {
target[datalength++] = Base64[output[2]];
}
target[datalength++] = Pad64;
}
if (datalength >= targsize) {
return -1;
}
target[datalength] = '\0'; /* Returned value doesn't count \0. */
return (int) datalength;
}
/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
The following encoding technique is taken from RFC 1521 by Borenstein
and Freed. It is reproduced here in a slightly edited form for
convenience.
A 65-character subset of US-ASCII is used, enabling 6 bits to be
represented per printable character. (The extra 65th character, "=",
is used to signify a special processing function.)
The encoding process represents 24-bit groups of input bits as output
strings of 4 encoded characters. Proceeding from left to right, a
24-bit input group is formed by concatenating 3 8-bit input groups.
These 24 bits are then treated as 4 concatenated 6-bit groups, each
of which is translated into a single digit in the base64 alphabet.
Each 6-bit group is used as an index into an array of 64 printable
characters. The character referenced by the index is placed in the
output string.
Table 1: The Base64 Alphabet
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
Special processing is performed if fewer than 24 bits are available
at the end of the data being encoded. A full encoding quantum is
always completed at the end of a quantity. When fewer than 24 input
bits are available in an input group, zero bits are added (on the
right) to form an integral number of 6-bit groups. Padding at the
end of the data is performed using the '=' character.
Since all base64 input is an integral number of octets, only the
following cases can arise:
(1) the final quantum of encoding input is an integral
multiple of 24 bits; here, the final unit of encoded
output will be an integral multiple of 4 characters
with no "=" padding,
(2) the final quantum of encoding input is exactly 8 bits;
here, the final unit of encoded output will be two
characters followed by two "=" padding characters, or
(3) the final quantum of encoding input is exactly 16 bits;
here, the final unit of encoded output will be three
characters followed by one "=" padding character.
*/
/* skips all whitespace anywhere.
converts characters, four at a time, starting at (or after)
src from base - 64 numbers into three 8 bit bytes in the target area.
it returns the number of data bytes stored at the target, or -1 on error.
*/
static uint8_t mongoc_b64rmap[256];
static const uint8_t mongoc_b64rmap_special = 0xf0;
static const uint8_t mongoc_b64rmap_end = 0xfd;
static const uint8_t mongoc_b64rmap_space = 0xfe;
static const uint8_t mongoc_b64rmap_invalid = 0xff;
/* initializing the reverse map isn't thread safe, do it in pthread_once */
#if defined(BSON_OS_UNIX)
#include
#define mongoc_common_once_t pthread_once_t
#define mongoc_common_once pthread_once
#define MONGOC_COMMON_ONCE_FUN(n) void n (void)
#define MONGOC_COMMON_ONCE_RETURN return
#define MONGOC_COMMON_ONCE_INIT PTHREAD_ONCE_INIT
#else
#define mongoc_common_once_t INIT_ONCE
#define MONGOC_COMMON_ONCE_INIT INIT_ONCE_STATIC_INIT
#define mongoc_common_once(o, c) InitOnceExecuteOnce (o, c, NULL, NULL)
#define MONGOC_COMMON_ONCE_FUN(n) \
BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c)
#define MONGOC_COMMON_ONCE_RETURN return true
#endif
static MONGOC_COMMON_ONCE_FUN (bson_b64_initialize_rmap)
{
int i;
unsigned char ch;
/* Null: end of string, stop parsing */
mongoc_b64rmap[0] = mongoc_b64rmap_end;
for (i = 1; i < 256; ++i) {
ch = (unsigned char) i;
/* Whitespaces */
if (isspace (ch))
mongoc_b64rmap[i] = mongoc_b64rmap_space;
/* Padding: stop parsing */
else if (ch == Pad64)
mongoc_b64rmap[i] = mongoc_b64rmap_end;
/* Non-base64 char */
else
mongoc_b64rmap[i] = mongoc_b64rmap_invalid;
}
/* Fill reverse mapping for base64 chars */
for (i = 0; Base64[i] != '\0'; ++i)
mongoc_b64rmap[(uint8_t) Base64[i]] = i;
MONGOC_COMMON_ONCE_RETURN;
}
static int
mongoc_b64_pton_do (char const *src, uint8_t *target, size_t targsize)
{
int tarindex, state, ch;
uint8_t ofs;
state = 0;
tarindex = 0;
while (1) {
ch = *src++;
ofs = mongoc_b64rmap[ch];
if (ofs >= mongoc_b64rmap_special) {
/* Ignore whitespaces */
if (ofs == mongoc_b64rmap_space)
continue;
/* End of base64 characters */
if (ofs == mongoc_b64rmap_end)
break;
/* A non-base64 character. */
return (-1);
}
switch (state) {
case 0:
if ((size_t) tarindex >= targsize)
return (-1);
target[tarindex] = ofs << 2;
state = 1;
break;
case 1:
if ((size_t) tarindex + 1 >= targsize)
return (-1);
target[tarindex] |= ofs >> 4;
target[tarindex + 1] = (ofs & 0x0f) << 4;
tarindex++;
state = 2;
break;
case 2:
if ((size_t) tarindex + 1 >= targsize)
return (-1);
target[tarindex] |= ofs >> 2;
target[tarindex + 1] = (ofs & 0x03) << 6;
tarindex++;
state = 3;
break;
case 3:
if ((size_t) tarindex >= targsize)
return (-1);
target[tarindex] |= ofs;
tarindex++;
state = 0;
break;
default:
abort ();
}
}
/*
* We are done decoding Base-64 chars. Let's see if we ended
* on a byte boundary, and/or with erroneous trailing characters.
*/
if (ch == Pad64) { /* We got a pad char. */
ch = *src++; /* Skip it, get next. */
switch (state) {
case 0: /* Invalid = in first position */
case 1: /* Invalid = in second position */
return (-1);
case 2: /* Valid, means one byte of info */
/* Skip any number of spaces. */
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
break;
/* Make sure there is another trailing = sign. */
if (ch != Pad64)
return (-1);
ch = *src++; /* Skip the = */
/* Fall through to "single trailing =" case. */
/* FALLTHROUGH */
case 3: /* Valid, means two bytes of info */
/*
* We know this char is an =. Is there anything but
* whitespace after it?
*/
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
return (-1);
/*
* Now make sure for cases 2 and 3 that the "extra"
* bits that slopped past the last full byte were
* zeros. If we don't check them, they become a
* subliminal channel.
*/
if (target[tarindex] != 0)
return (-1);
default:
break;
}
} else {
/*
* We ended by seeing the end of the string. Make sure we
* have no partial bytes lying around.
*/
if (state != 0)
return (-1);
}
return (tarindex);
}
static int
mongoc_b64_pton_len (char const *src)
{
int tarindex, state, ch;
uint8_t ofs;
state = 0;
tarindex = 0;
while (1) {
ch = *src++;
ofs = mongoc_b64rmap[ch];
if (ofs >= mongoc_b64rmap_special) {
/* Ignore whitespaces */
if (ofs == mongoc_b64rmap_space)
continue;
/* End of base64 characters */
if (ofs == mongoc_b64rmap_end)
break;
/* A non-base64 character. */
return (-1);
}
switch (state) {
case 0:
state = 1;
break;
case 1:
tarindex++;
state = 2;
break;
case 2:
tarindex++;
state = 3;
break;
case 3:
tarindex++;
state = 0;
break;
default:
abort ();
}
}
/*
* We are done decoding Base-64 chars. Let's see if we ended
* on a byte boundary, and/or with erroneous trailing characters.
*/
if (ch == Pad64) { /* We got a pad char. */
ch = *src++; /* Skip it, get next. */
switch (state) {
case 0: /* Invalid = in first position */
case 1: /* Invalid = in second position */
return (-1);
case 2: /* Valid, means one byte of info */
/* Skip any number of spaces. */
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
break;
/* Make sure there is another trailing = sign. */
if (ch != Pad64)
return (-1);
ch = *src++; /* Skip the = */
/* Fall through to "single trailing =" case. */
/* FALLTHROUGH */
case 3: /* Valid, means two bytes of info */
/*
* We know this char is an =. Is there anything but
* whitespace after it?
*/
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
return (-1);
default:
break;
}
} else {
/*
* We ended by seeing the end of the string. Make sure we
* have no partial bytes lying around.
*/
if (state != 0)
return (-1);
}
return (tarindex);
}
int
bson_b64_pton (char const *src, uint8_t *target, size_t targsize)
{
static mongoc_common_once_t once = MONGOC_COMMON_ONCE_INIT;
mongoc_common_once (&once, bson_b64_initialize_rmap);
if (target)
return mongoc_b64_pton_do (src, target, targsize);
else
return mongoc_b64_pton_len (src);
}
mongodb-1.6.1/src/libmongoc/src/common/common-md5-private.h 0000644 0000765 0000024 00000001704 13572250757 023076 0 ustar alcaeus staff /*
* Copyright 2018-present 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 "common-prelude.h"
#ifndef COMMON_MD5_PRIVATE_H
#define COMMON_MD5_PRIVATE_H
#include "bson/bson.h"
BSON_BEGIN_DECLS
void
_bson_md5_init (bson_md5_t *pms);
void
_bson_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes);
void
_bson_md5_finish (bson_md5_t *pms, uint8_t digest[16]);
BSON_END_DECLS
#endif /* COMMON_MD5_PRIVATE_H */
mongodb-1.6.1/src/libmongoc/src/common/common-md5.c 0000644 0000765 0000024 00000031000 13572250757 021411 0 ustar alcaeus staff /*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
/*
* The following MD5 implementation has been modified to use types as
* specified in libbson.
*/
#include
#include "common-md5-private.h"
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#if BSON_BYTE_ORDER == BSON_BIG_ENDIAN
#define BYTE_ORDER 1
#else
#define BYTE_ORDER -1
#endif
#define T_MASK ((uint32_t) ~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void
bson_md5_process (bson_md5_t *md5, const uint8_t *data)
{
uint32_t a = md5->abcd[0];
uint32_t b = md5->abcd[1];
uint32_t c = md5->abcd[2];
uint32_t d = md5->abcd[3];
uint32_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
uint32_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
uint32_t xbuf[16];
const uint32_t *X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const uint8_t *) &w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const uint8_t *) 0) & 3)) {
/* data are properly aligned */
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
#endif
X = (const uint32_t *) data;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
} else {
/* not aligned */
memcpy (xbuf, data, sizeof (xbuf));
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const uint8_t *xp = data;
int i;
#if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
#else
#define xbuf X /* (static only) */
#endif
for (i = 0; i < 16; ++i, xp += 4)
xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + F (b, c, d) + X[k] + Ti; \
a = ROTATE_LEFT (t, s) + b
/* Do the following 16 operations. */
SET (a, b, c, d, 0, 7, T1);
SET (d, a, b, c, 1, 12, T2);
SET (c, d, a, b, 2, 17, T3);
SET (b, c, d, a, 3, 22, T4);
SET (a, b, c, d, 4, 7, T5);
SET (d, a, b, c, 5, 12, T6);
SET (c, d, a, b, 6, 17, T7);
SET (b, c, d, a, 7, 22, T8);
SET (a, b, c, d, 8, 7, T9);
SET (d, a, b, c, 9, 12, T10);
SET (c, d, a, b, 10, 17, T11);
SET (b, c, d, a, 11, 22, T12);
SET (a, b, c, d, 12, 7, T13);
SET (d, a, b, c, 13, 12, T14);
SET (c, d, a, b, 14, 17, T15);
SET (b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + G (b, c, d) + X[k] + Ti; \
a = ROTATE_LEFT (t, s) + b
/* Do the following 16 operations. */
SET (a, b, c, d, 1, 5, T17);
SET (d, a, b, c, 6, 9, T18);
SET (c, d, a, b, 11, 14, T19);
SET (b, c, d, a, 0, 20, T20);
SET (a, b, c, d, 5, 5, T21);
SET (d, a, b, c, 10, 9, T22);
SET (c, d, a, b, 15, 14, T23);
SET (b, c, d, a, 4, 20, T24);
SET (a, b, c, d, 9, 5, T25);
SET (d, a, b, c, 14, 9, T26);
SET (c, d, a, b, 3, 14, T27);
SET (b, c, d, a, 8, 20, T28);
SET (a, b, c, d, 13, 5, T29);
SET (d, a, b, c, 2, 9, T30);
SET (c, d, a, b, 7, 14, T31);
SET (b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti) \
t = a + H (b, c, d) + X[k] + Ti; \
a = ROTATE_LEFT (t, s) + b
/* Do the following 16 operations. */
SET (a, b, c, d, 5, 4, T33);
SET (d, a, b, c, 8, 11, T34);
SET (c, d, a, b, 11, 16, T35);
SET (b, c, d, a, 14, 23, T36);
SET (a, b, c, d, 1, 4, T37);
SET (d, a, b, c, 4, 11, T38);
SET (c, d, a, b, 7, 16, T39);
SET (b, c, d, a, 10, 23, T40);
SET (a, b, c, d, 13, 4, T41);
SET (d, a, b, c, 0, 11, T42);
SET (c, d, a, b, 3, 16, T43);
SET (b, c, d, a, 6, 23, T44);
SET (a, b, c, d, 9, 4, T45);
SET (d, a, b, c, 12, 11, T46);
SET (c, d, a, b, 15, 16, T47);
SET (b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti) \
t = a + I (b, c, d) + X[k] + Ti; \
a = ROTATE_LEFT (t, s) + b
/* Do the following 16 operations. */
SET (a, b, c, d, 0, 6, T49);
SET (d, a, b, c, 7, 10, T50);
SET (c, d, a, b, 14, 15, T51);
SET (b, c, d, a, 5, 21, T52);
SET (a, b, c, d, 12, 6, T53);
SET (d, a, b, c, 3, 10, T54);
SET (c, d, a, b, 10, 15, T55);
SET (b, c, d, a, 1, 21, T56);
SET (a, b, c, d, 8, 6, T57);
SET (d, a, b, c, 15, 10, T58);
SET (c, d, a, b, 6, 15, T59);
SET (b, c, d, a, 13, 21, T60);
SET (a, b, c, d, 4, 6, T61);
SET (d, a, b, c, 11, 10, T62);
SET (c, d, a, b, 2, 15, T63);
SET (b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
md5->abcd[0] += a;
md5->abcd[1] += b;
md5->abcd[2] += c;
md5->abcd[3] += d;
}
void
_bson_md5_init (bson_md5_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
void
_bson_md5_append (bson_md5_t *pms, const uint8_t *data, uint32_t nbytes)
{
const uint8_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
uint32_t nbits = (uint32_t) (nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy (pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
bson_md5_process (pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
bson_md5_process (pms, p);
/* Process a final partial block. */
if (left)
memcpy (pms->buf, p, left);
}
void
_bson_md5_finish (bson_md5_t *pms, uint8_t digest[16])
{
static const uint8_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint8_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (uint8_t) (pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
_bson_md5_append (pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
_bson_md5_append (pms, data, sizeof (data));
for (i = 0; i < 16; ++i)
digest[i] = (uint8_t) (pms->abcd[i >> 2] >> ((i & 3) << 3));
}
mongodb-1.6.1/src/libmongoc/src/common/common-prelude.h 0000644 0000765 0000024 00000001445 13572250757 022403 0 ustar alcaeus staff /*
* Copyright 2018-present 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.
*/
#if !defined(MONGOC_INSIDE) && !defined(MONGOC_COMPILATION) && \
!defined(BSON_COMPILATION) && !defined(BSON_INSIDE)
#error "Only or can be included directly."
#endif mongodb-1.6.1/src/libmongoc/src/common/common-thread-private.h 0000644 0000765 0000024 00000004314 13572250757 023660 0 ustar alcaeus staff /*
* Copyright 2013-present 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 "common-prelude.h"
#ifndef COMMON_THREAD_PRIVATE_H
#define COMMON_THREAD_PRIVATE_H
#define BSON_INSIDE
#include "bson/bson-compat.h"
#include "bson/bson-config.h"
#include "bson/bson-macros.h"
#undef BSON_INSIDE
BSON_BEGIN_DECLS
#if defined(BSON_OS_UNIX)
#include
#define BSON_ONCE_FUN(n) void n (void)
#define BSON_ONCE_RETURN return
#define BSON_ONCE_INIT PTHREAD_ONCE_INIT
#define bson_mutex_destroy pthread_mutex_destroy
#define bson_mutex_init(_n) pthread_mutex_init ((_n), NULL)
#define bson_mutex_lock pthread_mutex_lock
#define bson_mutex_t pthread_mutex_t
#define bson_mutex_unlock pthread_mutex_unlock
#define bson_once pthread_once
#define bson_once_t pthread_once_t
#define bson_thread_create(_t, _f, _d) pthread_create ((_t), NULL, (_f), (_d))
#define bson_thread_join(_n) pthread_join ((_n), NULL)
#define bson_thread_t pthread_t
#else
#define BSON_ONCE_FUN(n) \
BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c)
#define BSON_ONCE_INIT INIT_ONCE_STATIC_INIT
#define BSON_ONCE_RETURN return true
#define bson_mutex_destroy DeleteCriticalSection
#define bson_mutex_init InitializeCriticalSection
#define bson_mutex_lock EnterCriticalSection
#define bson_mutex_t CRITICAL_SECTION
#define bson_mutex_unlock LeaveCriticalSection
#define bson_once(o, c) InitOnceExecuteOnce (o, c, NULL, NULL)
#define bson_once_t INIT_ONCE
#define bson_thread_create(_t, _f, _d) \
(!(*(_t) = CreateThread (NULL, 0, (void *) _f, _d, 0, NULL)))
#define bson_thread_join(_n) WaitForSingleObject ((_n), INFINITE)
#define bson_thread_t HANDLE
#endif
BSON_END_DECLS
#endif /* COMMON_THREAD_PRIVATE_H */
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bcon.c 0000644 0000765 0000024 00000065457 13572250757 022276 0 ustar alcaeus staff /*
* @file bcon.c
* @brief BCON (BSON C Object Notation) Implementation
*/
/* Copyright 2009-2013 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
#include "bson/bcon.h"
#include "bson/bson-config.h"
/* These stack manipulation macros are used to manage append recursion in
* bcon_append_ctx_va(). They take care of some awkward dereference rules (the
* real bson object isn't in the stack, but accessed by pointer) and add in run
* time asserts to make sure we don't blow the stack in either direction */
#define STACK_ELE(_delta, _name) (ctx->stack[(_delta) + ctx->n]._name)
#define STACK_BSON(_delta) \
(((_delta) + ctx->n) == 0 ? bson : &STACK_ELE (_delta, bson))
#define STACK_ITER(_delta) \
(((_delta) + ctx->n) == 0 ? &root_iter : &STACK_ELE (_delta, iter))
#define STACK_BSON_PARENT STACK_BSON (-1)
#define STACK_BSON_CHILD STACK_BSON (0)
#define STACK_ITER_PARENT STACK_ITER (-1)
#define STACK_ITER_CHILD STACK_ITER (0)
#define STACK_I STACK_ELE (0, i)
#define STACK_IS_ARRAY STACK_ELE (0, is_array)
#define STACK_PUSH_ARRAY(statement) \
do { \
BSON_ASSERT (ctx->n < (BCON_STACK_MAX - 1)); \
ctx->n++; \
STACK_I = 0; \
STACK_IS_ARRAY = 1; \
statement; \
} while (0)
#define STACK_PUSH_DOC(statement) \
do { \
BSON_ASSERT (ctx->n < (BCON_STACK_MAX - 1)); \
ctx->n++; \
STACK_IS_ARRAY = 0; \
statement; \
} while (0)
#define STACK_POP_ARRAY(statement) \
do { \
BSON_ASSERT (STACK_IS_ARRAY); \
BSON_ASSERT (ctx->n != 0); \
statement; \
ctx->n--; \
} while (0)
#define STACK_POP_DOC(statement) \
do { \
BSON_ASSERT (!STACK_IS_ARRAY); \
BSON_ASSERT (ctx->n != 0); \
statement; \
ctx->n--; \
} while (0)
/* This is a landing pad union for all of the types we can process with bcon.
* We need actual storage for this to capture the return value of va_arg, which
* takes multiple calls to get everything we need for some complex types */
typedef union bcon_append {
char *UTF8;
double DOUBLE;
bson_t *DOCUMENT;
bson_t *ARRAY;
bson_t *BCON;
struct {
bson_subtype_t subtype;
uint8_t *binary;
uint32_t length;
} BIN;
bson_oid_t *OID;
bool BOOL;
int64_t DATE_TIME;
struct {
char *regex;
char *flags;
} REGEX;
struct {
char *collection;
bson_oid_t *oid;
} DBPOINTER;
const char *CODE;
char *SYMBOL;
struct {
const char *js;
bson_t *scope;
} CODEWSCOPE;
int32_t INT32;
struct {
uint32_t timestamp;
uint32_t increment;
} TIMESTAMP;
int64_t INT64;
bson_decimal128_t *DECIMAL128;
const bson_iter_t *ITER;
} bcon_append_t;
/* same as bcon_append_t. Some extra symbols and varying types that handle the
* differences between bson_append and bson_iter */
typedef union bcon_extract {
bson_type_t TYPE;
bson_iter_t *ITER;
const char *key;
const char **UTF8;
double *DOUBLE;
bson_t *DOCUMENT;
bson_t *ARRAY;
struct {
bson_subtype_t *subtype;
const uint8_t **binary;
uint32_t *length;
} BIN;
const bson_oid_t **OID;
bool *BOOL;
int64_t *DATE_TIME;
struct {
const char **regex;
const char **flags;
} REGEX;
struct {
const char **collection;
const bson_oid_t **oid;
} DBPOINTER;
const char **CODE;
const char **SYMBOL;
struct {
const char **js;
bson_t *scope;
} CODEWSCOPE;
int32_t *INT32;
struct {
uint32_t *timestamp;
uint32_t *increment;
} TIMESTAMP;
int64_t *INT64;
bson_decimal128_t *DECIMAL128;
} bcon_extract_t;
static const char *gBconMagic = "BCON_MAGIC";
static const char *gBconeMagic = "BCONE_MAGIC";
const char *
bson_bcon_magic (void)
{
return gBconMagic;
}
const char *
bson_bcone_magic (void)
{
return gBconeMagic;
}
static void
_noop (void)
{
}
/* appends val to the passed bson object. Meant to be a super simple dispatch
* table */
static void
_bcon_append_single (bson_t *bson,
bcon_type_t type,
const char *key,
bcon_append_t *val)
{
switch ((int) type) {
case BCON_TYPE_UTF8:
BSON_ASSERT (bson_append_utf8 (bson, key, -1, val->UTF8, -1));
break;
case BCON_TYPE_DOUBLE:
BSON_ASSERT (bson_append_double (bson, key, -1, val->DOUBLE));
break;
case BCON_TYPE_BIN: {
BSON_ASSERT (bson_append_binary (
bson, key, -1, val->BIN.subtype, val->BIN.binary, val->BIN.length));
break;
}
case BCON_TYPE_UNDEFINED:
BSON_ASSERT (bson_append_undefined (bson, key, -1));
break;
case BCON_TYPE_OID:
BSON_ASSERT (bson_append_oid (bson, key, -1, val->OID));
break;
case BCON_TYPE_BOOL:
BSON_ASSERT (bson_append_bool (bson, key, -1, (bool) val->BOOL));
break;
case BCON_TYPE_DATE_TIME:
BSON_ASSERT (bson_append_date_time (bson, key, -1, val->DATE_TIME));
break;
case BCON_TYPE_NULL:
BSON_ASSERT (bson_append_null (bson, key, -1));
break;
case BCON_TYPE_REGEX: {
BSON_ASSERT (
bson_append_regex (bson, key, -1, val->REGEX.regex, val->REGEX.flags));
break;
}
case BCON_TYPE_DBPOINTER: {
BSON_ASSERT (bson_append_dbpointer (
bson, key, -1, val->DBPOINTER.collection, val->DBPOINTER.oid));
break;
}
case BCON_TYPE_CODE:
BSON_ASSERT (bson_append_code (bson, key, -1, val->CODE));
break;
case BCON_TYPE_SYMBOL:
BSON_ASSERT (bson_append_symbol (bson, key, -1, val->SYMBOL, -1));
break;
case BCON_TYPE_CODEWSCOPE:
BSON_ASSERT (bson_append_code_with_scope (
bson, key, -1, val->CODEWSCOPE.js, val->CODEWSCOPE.scope));
break;
case BCON_TYPE_INT32:
BSON_ASSERT (bson_append_int32 (bson, key, -1, val->INT32));
break;
case BCON_TYPE_TIMESTAMP: {
BSON_ASSERT (bson_append_timestamp (
bson, key, -1, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment));
break;
}
case BCON_TYPE_INT64:
BSON_ASSERT (bson_append_int64 (bson, key, -1, val->INT64));
break;
case BCON_TYPE_DECIMAL128:
BSON_ASSERT (bson_append_decimal128 (bson, key, -1, val->DECIMAL128));
break;
case BCON_TYPE_MAXKEY:
BSON_ASSERT (bson_append_maxkey (bson, key, -1));
break;
case BCON_TYPE_MINKEY:
BSON_ASSERT (bson_append_minkey (bson, key, -1));
break;
case BCON_TYPE_ARRAY: {
BSON_ASSERT (bson_append_array (bson, key, -1, val->ARRAY));
break;
}
case BCON_TYPE_DOCUMENT: {
BSON_ASSERT (bson_append_document (bson, key, -1, val->DOCUMENT));
break;
}
case BCON_TYPE_ITER:
BSON_ASSERT (bson_append_iter (bson, key, -1, val->ITER));
break;
default:
BSON_ASSERT (0);
break;
}
}
#define CHECK_TYPE(_type) \
do { \
if (bson_iter_type (iter) != (_type)) { \
return false; \
} \
} while (0)
/* extracts the value under the iterator and writes it to val. returns false
* if the iterator type doesn't match the token type.
*
* There are two magic tokens:
*
* BCONE_SKIP -
* Let's us verify that a key has a type, without caring about its value.
* This allows for wider declarative BSON verification
*
* BCONE_ITER -
* Returns the underlying iterator. This could allow for more complicated,
* procedural verification (if a parameter could have multiple types).
* */
static bool
_bcon_extract_single (const bson_iter_t *iter,
bcon_type_t type,
bcon_extract_t *val)
{
switch ((int) type) {
case BCON_TYPE_UTF8:
CHECK_TYPE (BSON_TYPE_UTF8);
*val->UTF8 = bson_iter_utf8 (iter, NULL);
break;
case BCON_TYPE_DOUBLE:
CHECK_TYPE (BSON_TYPE_DOUBLE);
*val->DOUBLE = bson_iter_double (iter);
break;
case BCON_TYPE_BIN:
CHECK_TYPE (BSON_TYPE_BINARY);
bson_iter_binary (
iter, val->BIN.subtype, val->BIN.length, val->BIN.binary);
break;
case BCON_TYPE_UNDEFINED:
CHECK_TYPE (BSON_TYPE_UNDEFINED);
break;
case BCON_TYPE_OID:
CHECK_TYPE (BSON_TYPE_OID);
*val->OID = bson_iter_oid (iter);
break;
case BCON_TYPE_BOOL:
CHECK_TYPE (BSON_TYPE_BOOL);
*val->BOOL = bson_iter_bool (iter);
break;
case BCON_TYPE_DATE_TIME:
CHECK_TYPE (BSON_TYPE_DATE_TIME);
*val->DATE_TIME = bson_iter_date_time (iter);
break;
case BCON_TYPE_NULL:
CHECK_TYPE (BSON_TYPE_NULL);
break;
case BCON_TYPE_REGEX:
CHECK_TYPE (BSON_TYPE_REGEX);
*val->REGEX.regex = bson_iter_regex (iter, val->REGEX.flags);
break;
case BCON_TYPE_DBPOINTER:
CHECK_TYPE (BSON_TYPE_DBPOINTER);
bson_iter_dbpointer (
iter, NULL, val->DBPOINTER.collection, val->DBPOINTER.oid);
break;
case BCON_TYPE_CODE:
CHECK_TYPE (BSON_TYPE_CODE);
*val->CODE = bson_iter_code (iter, NULL);
break;
case BCON_TYPE_SYMBOL:
CHECK_TYPE (BSON_TYPE_SYMBOL);
*val->SYMBOL = bson_iter_symbol (iter, NULL);
break;
case BCON_TYPE_CODEWSCOPE: {
const uint8_t *buf;
uint32_t len;
CHECK_TYPE (BSON_TYPE_CODEWSCOPE);
*val->CODEWSCOPE.js = bson_iter_codewscope (iter, NULL, &len, &buf);
BSON_ASSERT (bson_init_static (val->CODEWSCOPE.scope, buf, len));
break;
}
case BCON_TYPE_INT32:
CHECK_TYPE (BSON_TYPE_INT32);
*val->INT32 = bson_iter_int32 (iter);
break;
case BCON_TYPE_TIMESTAMP:
CHECK_TYPE (BSON_TYPE_TIMESTAMP);
bson_iter_timestamp (
iter, val->TIMESTAMP.timestamp, val->TIMESTAMP.increment);
break;
case BCON_TYPE_INT64:
CHECK_TYPE (BSON_TYPE_INT64);
*val->INT64 = bson_iter_int64 (iter);
break;
case BCON_TYPE_DECIMAL128:
CHECK_TYPE (BSON_TYPE_DECIMAL128);
BSON_ASSERT (bson_iter_decimal128 (iter, val->DECIMAL128));
break;
case BCON_TYPE_MAXKEY:
CHECK_TYPE (BSON_TYPE_MAXKEY);
break;
case BCON_TYPE_MINKEY:
CHECK_TYPE (BSON_TYPE_MINKEY);
break;
case BCON_TYPE_ARRAY: {
const uint8_t *buf;
uint32_t len;
CHECK_TYPE (BSON_TYPE_ARRAY);
bson_iter_array (iter, &len, &buf);
BSON_ASSERT (bson_init_static (val->ARRAY, buf, len));
break;
}
case BCON_TYPE_DOCUMENT: {
const uint8_t *buf;
uint32_t len;
CHECK_TYPE (BSON_TYPE_DOCUMENT);
bson_iter_document (iter, &len, &buf);
BSON_ASSERT (bson_init_static (val->DOCUMENT, buf, len));
break;
}
case BCON_TYPE_SKIP:
CHECK_TYPE (val->TYPE);
break;
case BCON_TYPE_ITER:
memcpy (val->ITER, iter, sizeof *iter);
break;
default:
BSON_ASSERT (0);
break;
}
return true;
}
/* Consumes ap, storing output values into u and returning the type of the
* captured token.
*
* The basic workflow goes like this:
*
* 1. Look at the current arg. It will be a char *
* a. If it's a NULL, we're done processing.
* b. If it's BCON_MAGIC (a symbol with storage in this module)
* I. The next token is the type
* II. The type specifies how many args to eat and their types
* c. Otherwise it's either recursion related or a raw string
* I. If the first byte is '{', '}', '[', or ']' pass back an
* appropriate recursion token
* II. If not, just call it a UTF8 token and pass that back
*/
static bcon_type_t
_bcon_append_tokenize (va_list *ap, bcon_append_t *u)
{
char *mark;
bcon_type_t type;
mark = va_arg (*ap, char *);
BSON_ASSERT (mark != BCONE_MAGIC);
if (mark == NULL) {
type = BCON_TYPE_END;
} else if (mark == BCON_MAGIC) {
type = va_arg (*ap, bcon_type_t);
switch ((int) type) {
case BCON_TYPE_UTF8:
u->UTF8 = va_arg (*ap, char *);
break;
case BCON_TYPE_DOUBLE:
u->DOUBLE = va_arg (*ap, double);
break;
case BCON_TYPE_DOCUMENT:
u->DOCUMENT = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_ARRAY:
u->ARRAY = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_BIN:
u->BIN.subtype = va_arg (*ap, bson_subtype_t);
u->BIN.binary = va_arg (*ap, uint8_t *);
u->BIN.length = va_arg (*ap, uint32_t);
break;
case BCON_TYPE_UNDEFINED:
break;
case BCON_TYPE_OID:
u->OID = va_arg (*ap, bson_oid_t *);
break;
case BCON_TYPE_BOOL:
u->BOOL = va_arg (*ap, int);
break;
case BCON_TYPE_DATE_TIME:
u->DATE_TIME = va_arg (*ap, int64_t);
break;
case BCON_TYPE_NULL:
break;
case BCON_TYPE_REGEX:
u->REGEX.regex = va_arg (*ap, char *);
u->REGEX.flags = va_arg (*ap, char *);
break;
case BCON_TYPE_DBPOINTER:
u->DBPOINTER.collection = va_arg (*ap, char *);
u->DBPOINTER.oid = va_arg (*ap, bson_oid_t *);
break;
case BCON_TYPE_CODE:
u->CODE = va_arg (*ap, char *);
break;
case BCON_TYPE_SYMBOL:
u->SYMBOL = va_arg (*ap, char *);
break;
case BCON_TYPE_CODEWSCOPE:
u->CODEWSCOPE.js = va_arg (*ap, char *);
u->CODEWSCOPE.scope = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_INT32:
u->INT32 = va_arg (*ap, int32_t);
break;
case BCON_TYPE_TIMESTAMP:
u->TIMESTAMP.timestamp = va_arg (*ap, uint32_t);
u->TIMESTAMP.increment = va_arg (*ap, uint32_t);
break;
case BCON_TYPE_INT64:
u->INT64 = va_arg (*ap, int64_t);
break;
case BCON_TYPE_DECIMAL128:
u->DECIMAL128 = va_arg (*ap, bson_decimal128_t *);
break;
case BCON_TYPE_MAXKEY:
break;
case BCON_TYPE_MINKEY:
break;
case BCON_TYPE_BCON:
u->BCON = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_ITER:
u->ITER = va_arg (*ap, const bson_iter_t *);
break;
default:
BSON_ASSERT (0);
break;
}
} else {
switch (mark[0]) {
case '{':
type = BCON_TYPE_DOC_START;
break;
case '}':
type = BCON_TYPE_DOC_END;
break;
case '[':
type = BCON_TYPE_ARRAY_START;
break;
case ']':
type = BCON_TYPE_ARRAY_END;
break;
default:
type = BCON_TYPE_UTF8;
u->UTF8 = mark;
break;
}
}
return type;
}
/* Consumes ap, storing output values into u and returning the type of the
* captured token.
*
* The basic workflow goes like this:
*
* 1. Look at the current arg. It will be a char *
* a. If it's a NULL, we're done processing.
* b. If it's BCONE_MAGIC (a symbol with storage in this module)
* I. The next token is the type
* II. The type specifies how many args to eat and their types
* c. Otherwise it's either recursion related or a raw string
* I. If the first byte is '{', '}', '[', or ']' pass back an
* appropriate recursion token
* II. If not, just call it a UTF8 token and pass that back
*/
static bcon_type_t
_bcon_extract_tokenize (va_list *ap, bcon_extract_t *u)
{
char *mark;
bcon_type_t type;
mark = va_arg (*ap, char *);
BSON_ASSERT (mark != BCON_MAGIC);
if (mark == NULL) {
type = BCON_TYPE_END;
} else if (mark == BCONE_MAGIC) {
type = va_arg (*ap, bcon_type_t);
switch ((int) type) {
case BCON_TYPE_UTF8:
u->UTF8 = va_arg (*ap, const char **);
break;
case BCON_TYPE_DOUBLE:
u->DOUBLE = va_arg (*ap, double *);
break;
case BCON_TYPE_DOCUMENT:
u->DOCUMENT = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_ARRAY:
u->ARRAY = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_BIN:
u->BIN.subtype = va_arg (*ap, bson_subtype_t *);
u->BIN.binary = va_arg (*ap, const uint8_t **);
u->BIN.length = va_arg (*ap, uint32_t *);
break;
case BCON_TYPE_UNDEFINED:
break;
case BCON_TYPE_OID:
u->OID = va_arg (*ap, const bson_oid_t **);
break;
case BCON_TYPE_BOOL:
u->BOOL = va_arg (*ap, bool *);
break;
case BCON_TYPE_DATE_TIME:
u->DATE_TIME = va_arg (*ap, int64_t *);
break;
case BCON_TYPE_NULL:
break;
case BCON_TYPE_REGEX:
u->REGEX.regex = va_arg (*ap, const char **);
u->REGEX.flags = va_arg (*ap, const char **);
break;
case BCON_TYPE_DBPOINTER:
u->DBPOINTER.collection = va_arg (*ap, const char **);
u->DBPOINTER.oid = va_arg (*ap, const bson_oid_t **);
break;
case BCON_TYPE_CODE:
u->CODE = va_arg (*ap, const char **);
break;
case BCON_TYPE_SYMBOL:
u->SYMBOL = va_arg (*ap, const char **);
break;
case BCON_TYPE_CODEWSCOPE:
u->CODEWSCOPE.js = va_arg (*ap, const char **);
u->CODEWSCOPE.scope = va_arg (*ap, bson_t *);
break;
case BCON_TYPE_INT32:
u->INT32 = va_arg (*ap, int32_t *);
break;
case BCON_TYPE_TIMESTAMP:
u->TIMESTAMP.timestamp = va_arg (*ap, uint32_t *);
u->TIMESTAMP.increment = va_arg (*ap, uint32_t *);
break;
case BCON_TYPE_INT64:
u->INT64 = va_arg (*ap, int64_t *);
break;
case BCON_TYPE_DECIMAL128:
u->DECIMAL128 = va_arg (*ap, bson_decimal128_t *);
break;
case BCON_TYPE_MAXKEY:
break;
case BCON_TYPE_MINKEY:
break;
case BCON_TYPE_SKIP:
u->TYPE = va_arg (*ap, bson_type_t);
break;
case BCON_TYPE_ITER:
u->ITER = va_arg (*ap, bson_iter_t *);
break;
default:
BSON_ASSERT (0);
break;
}
} else {
switch (mark[0]) {
case '{':
type = BCON_TYPE_DOC_START;
break;
case '}':
type = BCON_TYPE_DOC_END;
break;
case '[':
type = BCON_TYPE_ARRAY_START;
break;
case ']':
type = BCON_TYPE_ARRAY_END;
break;
default:
type = BCON_TYPE_RAW;
u->key = mark;
break;
}
}
return type;
}
/* This trivial utility function is useful for concatenating a bson object onto
* the end of another, ignoring the keys from the source bson object and
* continuing to use and increment the keys from the source. It's only useful
* when called from bcon_append_ctx_va */
static void
_bson_concat_array (bson_t *dest, const bson_t *src, bcon_append_ctx_t *ctx)
{
bson_iter_t iter;
const char *key;
char i_str[16];
bool r;
r = bson_iter_init (&iter, src);
if (!r) {
fprintf (stderr, "Invalid BSON document, possible memory coruption.\n");
return;
}
STACK_I--;
while (bson_iter_next (&iter)) {
bson_uint32_to_string (STACK_I, &key, i_str, sizeof i_str);
STACK_I++;
BSON_ASSERT (bson_append_iter (dest, key, -1, &iter));
}
}
/* Append_ctx_va consumes the va_list until NULL is found, appending into bson
* as tokens are found. It can receive or return an in-progress bson object
* via the ctx param. It can also operate on the middle of a va_list, and so
* can be wrapped inside of another varargs function.
*
* Note that passing in a va_list that isn't perferectly formatted for BCON
* ingestion will almost certainly result in undefined behavior
*
* The workflow relies on the passed ctx object, which holds a stack of bson
* objects, along with metadata (if the emedded layer is an array, and which
* element it is on if so). We iterate, generating tokens from the va_list,
* until we reach an END token. If any errors occur, we just blow up (the
* var_args stuff is already incredibly fragile to mistakes, and we have no way
* of introspecting, so just don't screw it up).
*
* There are also a few STACK_* macros in here which manimpulate ctx that are
* defined up top.
* */
void
bcon_append_ctx_va (bson_t *bson, bcon_append_ctx_t *ctx, va_list *ap)
{
bcon_type_t type;
const char *key;
char i_str[16];
bcon_append_t u = {0};
while (1) {
if (STACK_IS_ARRAY) {
bson_uint32_to_string (STACK_I, &key, i_str, sizeof i_str);
STACK_I++;
} else {
type = _bcon_append_tokenize (ap, &u);
if (type == BCON_TYPE_END) {
return;
}
if (type == BCON_TYPE_DOC_END) {
STACK_POP_DOC (
bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD));
continue;
}
if (type == BCON_TYPE_BCON) {
bson_concat (STACK_BSON_CHILD, u.BCON);
continue;
}
BSON_ASSERT (type == BCON_TYPE_UTF8);
key = u.UTF8;
}
type = _bcon_append_tokenize (ap, &u);
BSON_ASSERT (type != BCON_TYPE_END);
switch ((int) type) {
case BCON_TYPE_BCON:
BSON_ASSERT (STACK_IS_ARRAY);
_bson_concat_array (STACK_BSON_CHILD, u.BCON, ctx);
break;
case BCON_TYPE_DOC_START:
STACK_PUSH_DOC (bson_append_document_begin (
STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD));
break;
case BCON_TYPE_DOC_END:
STACK_POP_DOC (
bson_append_document_end (STACK_BSON_PARENT, STACK_BSON_CHILD));
break;
case BCON_TYPE_ARRAY_START:
STACK_PUSH_ARRAY (bson_append_array_begin (
STACK_BSON_PARENT, key, -1, STACK_BSON_CHILD));
break;
case BCON_TYPE_ARRAY_END:
STACK_POP_ARRAY (
bson_append_array_end (STACK_BSON_PARENT, STACK_BSON_CHILD));
break;
default:
_bcon_append_single (STACK_BSON_CHILD, type, key, &u);
break;
}
}
}
/* extract_ctx_va consumes the va_list until NULL is found, extracting values
* as tokens are found. It can receive or return an in-progress bson object
* via the ctx param. It can also operate on the middle of a va_list, and so
* can be wrapped inside of another varargs function.
*
* Note that passing in a va_list that isn't perferectly formatted for BCON
* ingestion will almost certainly result in undefined behavior
*
* The workflow relies on the passed ctx object, which holds a stack of iterator
* objects, along with metadata (if the emedded layer is an array, and which
* element it is on if so). We iterate, generating tokens from the va_list,
* until we reach an END token. If any errors occur, we just blow up (the
* var_args stuff is already incredibly fragile to mistakes, and we have no way
* of introspecting, so just don't screw it up).
*
* There are also a few STACK_* macros in here which manimpulate ctx that are
* defined up top.
*
* The function returns true if all tokens could be successfully matched, false
* otherwise.
* */
bool
bcon_extract_ctx_va (bson_t *bson, bcon_extract_ctx_t *ctx, va_list *ap)
{
bcon_type_t type;
const char *key;
bson_iter_t root_iter;
bson_iter_t current_iter;
char i_str[16];
bcon_extract_t u = {0};
BSON_ASSERT (bson_iter_init (&root_iter, bson));
while (1) {
if (STACK_IS_ARRAY) {
bson_uint32_to_string (STACK_I, &key, i_str, sizeof i_str);
STACK_I++;
} else {
type = _bcon_extract_tokenize (ap, &u);
if (type == BCON_TYPE_END) {
return true;
}
if (type == BCON_TYPE_DOC_END) {
STACK_POP_DOC (_noop ());
continue;
}
BSON_ASSERT (type == BCON_TYPE_RAW);
key = u.key;
}
type = _bcon_extract_tokenize (ap, &u);
BSON_ASSERT (type != BCON_TYPE_END);
if (type == BCON_TYPE_DOC_END) {
STACK_POP_DOC (_noop ());
} else if (type == BCON_TYPE_ARRAY_END) {
STACK_POP_ARRAY (_noop ());
} else {
memcpy (¤t_iter, STACK_ITER_CHILD, sizeof current_iter);
if (!bson_iter_find (¤t_iter, key)) {
return false;
}
switch ((int) type) {
case BCON_TYPE_DOC_START:
if (bson_iter_type (¤t_iter) != BSON_TYPE_DOCUMENT) {
return false;
}
STACK_PUSH_DOC (
bson_iter_recurse (¤t_iter, STACK_ITER_CHILD));
break;
case BCON_TYPE_ARRAY_START:
if (bson_iter_type (¤t_iter) != BSON_TYPE_ARRAY) {
return false;
}
STACK_PUSH_ARRAY (
bson_iter_recurse (¤t_iter, STACK_ITER_CHILD));
break;
default:
if (!_bcon_extract_single (¤t_iter, type, &u)) {
return false;
}
break;
}
}
}
}
void
bcon_extract_ctx_init (bcon_extract_ctx_t *ctx)
{
ctx->n = 0;
ctx->stack[0].is_array = false;
}
bool
bcon_extract (bson_t *bson, ...)
{
va_list ap;
bcon_extract_ctx_t ctx;
bool r;
bcon_extract_ctx_init (&ctx);
va_start (ap, bson);
r = bcon_extract_ctx_va (bson, &ctx, &ap);
va_end (ap);
return r;
}
void
bcon_append (bson_t *bson, ...)
{
va_list ap;
bcon_append_ctx_t ctx;
bcon_append_ctx_init (&ctx);
va_start (ap, bson);
bcon_append_ctx_va (bson, &ctx, &ap);
va_end (ap);
}
void
bcon_append_ctx (bson_t *bson, bcon_append_ctx_t *ctx, ...)
{
va_list ap;
va_start (ap, ctx);
bcon_append_ctx_va (bson, ctx, &ap);
va_end (ap);
}
void
bcon_extract_ctx (bson_t *bson, bcon_extract_ctx_t *ctx, ...)
{
va_list ap;
va_start (ap, ctx);
bcon_extract_ctx_va (bson, ctx, &ap);
va_end (ap);
}
void
bcon_append_ctx_init (bcon_append_ctx_t *ctx)
{
ctx->n = 0;
ctx->stack[0].is_array = 0;
}
bson_t *
bcon_new (void *unused, ...)
{
va_list ap;
bcon_append_ctx_t ctx;
bson_t *bson;
bcon_append_ctx_init (&ctx);
bson = bson_new ();
va_start (ap, unused);
bcon_append_ctx_va (bson, &ctx, &ap);
va_end (ap);
return bson;
}
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bcon.h 0000644 0000765 0000024 00000025336 13572250757 022273 0 ustar alcaeus staff /*
* @file bcon.h
* @brief BCON (BSON C Object Notation) Declarations
*/
#include "bson/bson-prelude.h"
/* Copyright 2009-2013 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.
*/
#ifndef BCON_H_
#define BCON_H_
#include "bson/bson.h"
BSON_BEGIN_DECLS
#define BCON_STACK_MAX 100
#define BCON_ENSURE_DECLARE(fun, type) \
static BSON_INLINE type bcon_ensure_##fun (type _t) \
{ \
return _t; \
}
#define BCON_ENSURE(fun, val) bcon_ensure_##fun (val)
#define BCON_ENSURE_STORAGE(fun, val) bcon_ensure_##fun (&(val))
BCON_ENSURE_DECLARE (const_char_ptr, const char *)
BCON_ENSURE_DECLARE (const_char_ptr_ptr, const char **)
BCON_ENSURE_DECLARE (double, double)
BCON_ENSURE_DECLARE (double_ptr, double *)
BCON_ENSURE_DECLARE (const_bson_ptr, const bson_t *)
BCON_ENSURE_DECLARE (bson_ptr, bson_t *)
BCON_ENSURE_DECLARE (subtype, bson_subtype_t)
BCON_ENSURE_DECLARE (subtype_ptr, bson_subtype_t *)
BCON_ENSURE_DECLARE (const_uint8_ptr, const uint8_t *)
BCON_ENSURE_DECLARE (const_uint8_ptr_ptr, const uint8_t **)
BCON_ENSURE_DECLARE (uint32, uint32_t)
BCON_ENSURE_DECLARE (uint32_ptr, uint32_t *)
BCON_ENSURE_DECLARE (const_oid_ptr, const bson_oid_t *)
BCON_ENSURE_DECLARE (const_oid_ptr_ptr, const bson_oid_t **)
BCON_ENSURE_DECLARE (int32, int32_t)
BCON_ENSURE_DECLARE (int32_ptr, int32_t *)
BCON_ENSURE_DECLARE (int64, int64_t)
BCON_ENSURE_DECLARE (int64_ptr, int64_t *)
BCON_ENSURE_DECLARE (const_decimal128_ptr, const bson_decimal128_t *)
BCON_ENSURE_DECLARE (bool, bool)
BCON_ENSURE_DECLARE (bool_ptr, bool *)
BCON_ENSURE_DECLARE (bson_type, bson_type_t)
BCON_ENSURE_DECLARE (bson_iter_ptr, bson_iter_t *)
BCON_ENSURE_DECLARE (const_bson_iter_ptr, const bson_iter_t *)
#define BCON_UTF8(_val) \
BCON_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE (const_char_ptr, (_val))
#define BCON_DOUBLE(_val) \
BCON_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE (double, (_val))
#define BCON_DOCUMENT(_val) \
BCON_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE (const_bson_ptr, (_val))
#define BCON_ARRAY(_val) \
BCON_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE (const_bson_ptr, (_val))
#define BCON_BIN(_subtype, _binary, _length) \
BCON_MAGIC, BCON_TYPE_BIN, BCON_ENSURE (subtype, (_subtype)), \
BCON_ENSURE (const_uint8_ptr, (_binary)), \
BCON_ENSURE (uint32, (_length))
#define BCON_UNDEFINED BCON_MAGIC, BCON_TYPE_UNDEFINED
#define BCON_OID(_val) \
BCON_MAGIC, BCON_TYPE_OID, BCON_ENSURE (const_oid_ptr, (_val))
#define BCON_BOOL(_val) BCON_MAGIC, BCON_TYPE_BOOL, BCON_ENSURE (bool, (_val))
#define BCON_DATE_TIME(_val) \
BCON_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE (int64, (_val))
#define BCON_NULL BCON_MAGIC, BCON_TYPE_NULL
#define BCON_REGEX(_regex, _flags) \
BCON_MAGIC, BCON_TYPE_REGEX, BCON_ENSURE (const_char_ptr, (_regex)), \
BCON_ENSURE (const_char_ptr, (_flags))
#define BCON_DBPOINTER(_collection, _oid) \
BCON_MAGIC, BCON_TYPE_DBPOINTER, \
BCON_ENSURE (const_char_ptr, (_collection)), \
BCON_ENSURE (const_oid_ptr, (_oid))
#define BCON_CODE(_val) \
BCON_MAGIC, BCON_TYPE_CODE, BCON_ENSURE (const_char_ptr, (_val))
#define BCON_SYMBOL(_val) \
BCON_MAGIC, BCON_TYPE_SYMBOL, BCON_ENSURE (const_char_ptr, (_val))
#define BCON_CODEWSCOPE(_js, _scope) \
BCON_MAGIC, BCON_TYPE_CODEWSCOPE, BCON_ENSURE (const_char_ptr, (_js)), \
BCON_ENSURE (const_bson_ptr, (_scope))
#define BCON_INT32(_val) \
BCON_MAGIC, BCON_TYPE_INT32, BCON_ENSURE (int32, (_val))
#define BCON_TIMESTAMP(_timestamp, _increment) \
BCON_MAGIC, BCON_TYPE_TIMESTAMP, BCON_ENSURE (int32, (_timestamp)), \
BCON_ENSURE (int32, (_increment))
#define BCON_INT64(_val) \
BCON_MAGIC, BCON_TYPE_INT64, BCON_ENSURE (int64, (_val))
#define BCON_DECIMAL128(_val) \
BCON_MAGIC, BCON_TYPE_DECIMAL128, BCON_ENSURE (const_decimal128_ptr, (_val))
#define BCON_MAXKEY BCON_MAGIC, BCON_TYPE_MAXKEY
#define BCON_MINKEY BCON_MAGIC, BCON_TYPE_MINKEY
#define BCON(_val) \
BCON_MAGIC, BCON_TYPE_BCON, BCON_ENSURE (const_bson_ptr, (_val))
#define BCON_ITER(_val) \
BCON_MAGIC, BCON_TYPE_ITER, BCON_ENSURE (const_bson_iter_ptr, (_val))
#define BCONE_UTF8(_val) \
BCONE_MAGIC, BCON_TYPE_UTF8, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val))
#define BCONE_DOUBLE(_val) \
BCONE_MAGIC, BCON_TYPE_DOUBLE, BCON_ENSURE_STORAGE (double_ptr, (_val))
#define BCONE_DOCUMENT(_val) \
BCONE_MAGIC, BCON_TYPE_DOCUMENT, BCON_ENSURE_STORAGE (bson_ptr, (_val))
#define BCONE_ARRAY(_val) \
BCONE_MAGIC, BCON_TYPE_ARRAY, BCON_ENSURE_STORAGE (bson_ptr, (_val))
#define BCONE_BIN(subtype, binary, length) \
BCONE_MAGIC, BCON_TYPE_BIN, BCON_ENSURE_STORAGE (subtype_ptr, (subtype)), \
BCON_ENSURE_STORAGE (const_uint8_ptr_ptr, (binary)), \
BCON_ENSURE_STORAGE (uint32_ptr, (length))
#define BCONE_UNDEFINED BCONE_MAGIC, BCON_TYPE_UNDEFINED
#define BCONE_OID(_val) \
BCONE_MAGIC, BCON_TYPE_OID, BCON_ENSURE_STORAGE (const_oid_ptr_ptr, (_val))
#define BCONE_BOOL(_val) \
BCONE_MAGIC, BCON_TYPE_BOOL, BCON_ENSURE_STORAGE (bool_ptr, (_val))
#define BCONE_DATE_TIME(_val) \
BCONE_MAGIC, BCON_TYPE_DATE_TIME, BCON_ENSURE_STORAGE (int64_ptr, (_val))
#define BCONE_NULL BCONE_MAGIC, BCON_TYPE_NULL
#define BCONE_REGEX(_regex, _flags) \
BCONE_MAGIC, BCON_TYPE_REGEX, \
BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_regex)), \
BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_flags))
#define BCONE_DBPOINTER(_collection, _oid) \
BCONE_MAGIC, BCON_TYPE_DBPOINTER, \
BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_collection)), \
BCON_ENSURE_STORAGE (const_oid_ptr_ptr, (_oid))
#define BCONE_CODE(_val) \
BCONE_MAGIC, BCON_TYPE_CODE, BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val))
#define BCONE_SYMBOL(_val) \
BCONE_MAGIC, BCON_TYPE_SYMBOL, \
BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_val))
#define BCONE_CODEWSCOPE(_js, _scope) \
BCONE_MAGIC, BCON_TYPE_CODEWSCOPE, \
BCON_ENSURE_STORAGE (const_char_ptr_ptr, (_js)), \
BCON_ENSURE_STORAGE (bson_ptr, (_scope))
#define BCONE_INT32(_val) \
BCONE_MAGIC, BCON_TYPE_INT32, BCON_ENSURE_STORAGE (int32_ptr, (_val))
#define BCONE_TIMESTAMP(_timestamp, _increment) \
BCONE_MAGIC, BCON_TYPE_TIMESTAMP, \
BCON_ENSURE_STORAGE (int32_ptr, (_timestamp)), \
BCON_ENSURE_STORAGE (int32_ptr, (_increment))
#define BCONE_INT64(_val) \
BCONE_MAGIC, BCON_TYPE_INT64, BCON_ENSURE_STORAGE (int64_ptr, (_val))
#define BCONE_DECIMAL128(_val) \
BCONE_MAGIC, BCON_TYPE_DECIMAL128, \
BCON_ENSURE_STORAGE (const_decimal128_ptr, (_val))
#define BCONE_MAXKEY BCONE_MAGIC, BCON_TYPE_MAXKEY
#define BCONE_MINKEY BCONE_MAGIC, BCON_TYPE_MINKEY
#define BCONE_SKIP(_val) \
BCONE_MAGIC, BCON_TYPE_SKIP, BCON_ENSURE (bson_type, (_val))
#define BCONE_ITER(_val) \
BCONE_MAGIC, BCON_TYPE_ITER, BCON_ENSURE_STORAGE (bson_iter_ptr, (_val))
#define BCON_MAGIC bson_bcon_magic ()
#define BCONE_MAGIC bson_bcone_magic ()
typedef enum {
BCON_TYPE_UTF8,
BCON_TYPE_DOUBLE,
BCON_TYPE_DOCUMENT,
BCON_TYPE_ARRAY,
BCON_TYPE_BIN,
BCON_TYPE_UNDEFINED,
BCON_TYPE_OID,
BCON_TYPE_BOOL,
BCON_TYPE_DATE_TIME,
BCON_TYPE_NULL,
BCON_TYPE_REGEX,
BCON_TYPE_DBPOINTER,
BCON_TYPE_CODE,
BCON_TYPE_SYMBOL,
BCON_TYPE_CODEWSCOPE,
BCON_TYPE_INT32,
BCON_TYPE_TIMESTAMP,
BCON_TYPE_INT64,
BCON_TYPE_DECIMAL128,
BCON_TYPE_MAXKEY,
BCON_TYPE_MINKEY,
BCON_TYPE_BCON,
BCON_TYPE_ARRAY_START,
BCON_TYPE_ARRAY_END,
BCON_TYPE_DOC_START,
BCON_TYPE_DOC_END,
BCON_TYPE_END,
BCON_TYPE_RAW,
BCON_TYPE_SKIP,
BCON_TYPE_ITER,
BCON_TYPE_ERROR,
} bcon_type_t;
typedef struct bcon_append_ctx_frame {
int i;
bool is_array;
bson_t bson;
} bcon_append_ctx_frame_t;
typedef struct bcon_extract_ctx_frame {
int i;
bool is_array;
bson_iter_t iter;
} bcon_extract_ctx_frame_t;
typedef struct _bcon_append_ctx_t {
bcon_append_ctx_frame_t stack[BCON_STACK_MAX];
int n;
} bcon_append_ctx_t;
typedef struct _bcon_extract_ctx_t {
bcon_extract_ctx_frame_t stack[BCON_STACK_MAX];
int n;
} bcon_extract_ctx_t;
BSON_EXPORT (void)
bcon_append (bson_t *bson, ...) BSON_GNUC_NULL_TERMINATED;
BSON_EXPORT (void)
bcon_append_ctx (bson_t *bson,
bcon_append_ctx_t *ctx,
...) BSON_GNUC_NULL_TERMINATED;
BSON_EXPORT (void)
bcon_append_ctx_va (bson_t *bson, bcon_append_ctx_t *ctx, va_list *va);
BSON_EXPORT (void)
bcon_append_ctx_init (bcon_append_ctx_t *ctx);
BSON_EXPORT (void)
bcon_extract_ctx_init (bcon_extract_ctx_t *ctx);
BSON_EXPORT (void)
bcon_extract_ctx (bson_t *bson,
bcon_extract_ctx_t *ctx,
...) BSON_GNUC_NULL_TERMINATED;
BSON_EXPORT (bool)
bcon_extract_ctx_va (bson_t *bson, bcon_extract_ctx_t *ctx, va_list *ap);
BSON_EXPORT (bool)
bcon_extract (bson_t *bson, ...) BSON_GNUC_NULL_TERMINATED;
BSON_EXPORT (bool)
bcon_extract_va (bson_t *bson,
bcon_extract_ctx_t *ctx,
...) BSON_GNUC_NULL_TERMINATED;
BSON_EXPORT (bson_t *)
bcon_new (void *unused, ...) BSON_GNUC_NULL_TERMINATED;
/**
* The bcon_..() functions are all declared with __attribute__((sentinel)).
*
* From GCC manual for "sentinel": "A valid NULL in this context is defined as
* zero with any pointer type. If your system defines the NULL macro with an
* integer type then you need to add an explicit cast."
* Case in point: GCC on Solaris (at least)
*/
#define BCON_APPEND(_bson, ...) \
bcon_append ((_bson), __VA_ARGS__, (void *) NULL)
#define BCON_APPEND_CTX(_bson, _ctx, ...) \
bcon_append_ctx ((_bson), (_ctx), __VA_ARGS__, (void *) NULL)
#define BCON_EXTRACT(_bson, ...) \
bcon_extract ((_bson), __VA_ARGS__, (void *) NULL)
#define BCON_EXTRACT_CTX(_bson, _ctx, ...) \
bcon_extract ((_bson), (_ctx), __VA_ARGS__, (void *) NULL)
#define BCON_NEW(...) bcon_new (NULL, __VA_ARGS__, (void *) NULL)
BSON_EXPORT (const char *)
bson_bcon_magic (void) BSON_GNUC_PURE;
BSON_EXPORT (const char *)
bson_bcone_magic (void) BSON_GNUC_PURE;
BSON_END_DECLS
#endif
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bson-atomic.c 0000644 0000765 0000024 00000003232 13572250757 023547 0 ustar alcaeus staff /*
* Copyright 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 "bson/bson-atomic.h"
/*
* We should only ever hit these on non-Windows systems, for which we require
* pthread support. Therefore, we will avoid making a threading portability
* for threads here and just use pthreads directly.
*/
#ifdef __BSON_NEED_BARRIER
#include
static pthread_mutex_t gBarrier = PTHREAD_MUTEX_INITIALIZER;
void
bson_memory_barrier (void)
{
pthread_mutex_lock (&gBarrier);
pthread_mutex_unlock (&gBarrier);
}
#endif
#ifdef __BSON_NEED_ATOMIC_32
#include
static pthread_mutex_t gSync32 = PTHREAD_MUTEX_INITIALIZER;
int32_t
bson_atomic_int_add (volatile int32_t *p, int32_t n)
{
int ret;
pthread_mutex_lock (&gSync32);
*p += n;
ret = *p;
pthread_mutex_unlock (&gSync32);
return ret;
}
#endif
#ifdef __BSON_NEED_ATOMIC_64
#include
static pthread_mutex_t gSync64 = PTHREAD_MUTEX_INITIALIZER;
int64_t
bson_atomic_int64_add (volatile int64_t *p, int64_t n)
{
int64_t ret;
pthread_mutex_lock (&gSync64);
*p += n;
ret = *p;
pthread_mutex_unlock (&gSync64);
return ret;
}
#endif
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bson-atomic.h 0000644 0000765 0000024 00000005503 13572250757 023557 0 ustar alcaeus staff /*
* Copyright 2013-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 "bson/bson-prelude.h"
#ifndef BSON_ATOMIC_H
#define BSON_ATOMIC_H
#include "bson/bson-config.h"
#include "bson/bson-compat.h"
#include "bson/bson-macros.h"
BSON_BEGIN_DECLS
#if defined(__sun) && defined(__SVR4)
/* Solaris */
#include
#define bson_atomic_int_add(p, v) \
atomic_add_32_nv ((volatile uint32_t *) p, (v))
#define bson_atomic_int64_add(p, v) \
atomic_add_64_nv ((volatile uint64_t *) p, (v))
#elif defined(_WIN32)
/* MSVC/MinGW */
#define bson_atomic_int_add(p, v) \
(InterlockedExchangeAdd ((volatile LONG *) (p), (LONG) (v)) + (LONG) (v))
#define bson_atomic_int64_add(p, v) \
(InterlockedExchangeAdd64 ((volatile LONGLONG *) (p), (LONGLONG) (v)) + \
(LONGLONG) (v))
#else
#ifdef BSON_HAVE_ATOMIC_32_ADD_AND_FETCH
#define bson_atomic_int_add(p, v) __sync_add_and_fetch ((p), (v))
#else
#define __BSON_NEED_ATOMIC_32
#endif
#ifdef BSON_HAVE_ATOMIC_64_ADD_AND_FETCH
#if BSON_GNUC_IS_VERSION(4, 1)
/*
* GCC 4.1 on i386 can generate buggy 64-bit atomic increment.
* So we will work around with a fallback.
*
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=40693
*/
#define __BSON_NEED_ATOMIC_64
#else
#define bson_atomic_int64_add(p, v) \
__sync_add_and_fetch ((volatile int64_t *) (p), (int64_t) (v))
#endif
#else
#define __BSON_NEED_ATOMIC_64
#endif
#endif
#ifdef __BSON_NEED_ATOMIC_32
BSON_EXPORT (int32_t)
bson_atomic_int_add (volatile int32_t *p, int32_t n);
#endif
#ifdef __BSON_NEED_ATOMIC_64
BSON_EXPORT (int64_t)
bson_atomic_int64_add (volatile int64_t *p, int64_t n);
#endif
#if defined(_WIN32)
#define bson_memory_barrier() MemoryBarrier ()
#elif defined(__GNUC__)
#if BSON_GNUC_CHECK_VERSION(4, 1)
#define bson_memory_barrier() __sync_synchronize ()
#else
#warning "GCC Pre-4.1 discovered, using inline assembly for memory barrier."
#define bson_memory_barrier() __asm__ volatile("" ::: "memory")
#endif
#elif defined(__SUNPRO_C)
#include
#define bson_memory_barrier() __machine_rw_barrier ()
#elif defined(__xlC__)
#define bson_memory_barrier() __sync ()
#else
#define __BSON_NEED_BARRIER 1
#warning "Unknown compiler, using lock for compiler barrier."
BSON_EXPORT (void)
bson_memory_barrier (void);
#endif
BSON_END_DECLS
#endif /* BSON_ATOMIC_H */
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bson-clock.c 0000644 0000765 0000024 00000007655 13572250757 023403 0 ustar alcaeus staff /*
* Copyright 2013 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.
*/
#ifdef __APPLE__
#include
#include
#include
#include
#endif
#include "bson/bson-config.h"
#include "bson/bson-compat.h"
#if defined(BSON_HAVE_CLOCK_GETTIME)
#include
#include
#endif
#include "bson/bson-clock.h"
/*
*--------------------------------------------------------------------------
*
* bson_gettimeofday --
*
* A wrapper around gettimeofday() with fallback support for Windows.
*
* Returns:
* 0 if successful.
*
* Side effects:
* @tv is set.
*
*--------------------------------------------------------------------------
*/
int
bson_gettimeofday (struct timeval *tv) /* OUT */
{
#if defined(_WIN32)
#if defined(_MSC_VER)
#define DELTA_EPOCH_IN_MICROSEC 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSEC 11644473600000000ULL
#endif
FILETIME ft;
uint64_t tmp = 0;
/*
* The const value is shamelessly stolen from
* http://www.boost.org/doc/libs/1_55_0/boost/chrono/detail/inlined/win/chrono.hpp
*
* File times are the number of 100 nanosecond intervals elapsed since
* 12:00 am Jan 1, 1601 UTC. I haven't check the math particularly hard
*
* ... good luck
*/
if (tv) {
GetSystemTimeAsFileTime (&ft);
/* pull out of the filetime into a 64 bit uint */
tmp |= ft.dwHighDateTime;
tmp <<= 32;
tmp |= ft.dwLowDateTime;
/* convert from 100's of nanosecs to microsecs */
tmp /= 10;
/* adjust to unix epoch */
tmp -= DELTA_EPOCH_IN_MICROSEC;
tv->tv_sec = (long) (tmp / 1000000UL);
tv->tv_usec = (long) (tmp % 1000000UL);
}
return 0;
#else
return gettimeofday (tv, NULL);
#endif
}
/*
*--------------------------------------------------------------------------
*
* bson_get_monotonic_time --
*
* Returns the monotonic system time, if available. A best effort is
* made to use the monotonic clock. However, some systems may not
* support such a feature.
*
* Returns:
* The monotonic clock in microseconds.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
int64_t
bson_get_monotonic_time (void)
{
#if defined(BSON_HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
struct timespec ts;
/* ts.tv_sec may be a four-byte integer on 32 bit machines, so cast to
* int64_t to avoid truncation. */
clock_gettime (CLOCK_MONOTONIC, &ts);
return (((int64_t) ts.tv_sec * 1000000) + (ts.tv_nsec / 1000));
#elif defined(__APPLE__)
static mach_timebase_info_data_t info = {0};
static double ratio = 0.0;
if (!info.denom) {
/* the value from mach_absolute_time () * info.numer / info.denom
* is in nano seconds. So we have to divid by 1000.0 to get micro
* seconds*/
mach_timebase_info (&info);
ratio = (double) info.numer / (double) info.denom / 1000.0;
}
return mach_absolute_time () * ratio;
#elif defined(_WIN32)
/* Despite it's name, this is in milliseconds! */
int64_t ticks = GetTickCount64 ();
return (ticks * 1000);
#elif defined(__hpux__)
int64_t nanosec = gethrtime ();
return (nanosec / 1000UL);
#else
#warning "Monotonic clock is not yet supported on your platform."
struct timeval tv;
bson_gettimeofday (&tv);
return ((int64_t) tv.tv_sec * 1000000) + tv.tv_usec;
#endif
}
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bson-clock.h 0000644 0000765 0000024 00000001654 13572250757 023401 0 ustar alcaeus staff /*
* Copyright 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 "bson/bson-prelude.h"
#ifndef BSON_CLOCK_H
#define BSON_CLOCK_H
#include "bson/bson-compat.h"
#include "bson/bson-macros.h"
#include "bson/bson-types.h"
BSON_BEGIN_DECLS
BSON_EXPORT (int64_t)
bson_get_monotonic_time (void);
BSON_EXPORT (int)
bson_gettimeofday (struct timeval *tv);
BSON_END_DECLS
#endif /* BSON_CLOCK_H */
mongodb-1.6.1/src/libmongoc/src/libbson/src/bson/bson-compat.h 0000644 0000765 0000024 00000007121 13572250757 023564 0 ustar alcaeus staff /*
* Copyright 2013 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 "bson/bson-prelude.h"
#ifndef BSON_COMPAT_H
#define BSON_COMPAT_H
#if defined(__MINGW32__)
#if defined(__USE_MINGW_ANSI_STDIO)
#if __USE_MINGW_ANSI_STDIO < 1
#error "__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros"
#endif
#else
#define __USE_MINGW_ANSI_STDIO 1
#endif
#endif
#include "bson/bson-config.h"
#include "bson/bson-macros.h"
#ifdef BSON_OS_WIN32
#if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600)
#undef _WIN32_WINNT
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include
#undef WIN32_LEAN_AND_MEAN
#else
#include
#endif
#include
#include
#endif
#ifdef BSON_OS_UNIX
#include
#include
#endif
#include "bson/bson-macros.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include