Example #1
0
/* {{{ proto bool SolrInputDocument::addField(string field_name, field_value [, float field_boost])
   Adds a field to the document. Can be called multiple times. */
PHP_METHOD(SolrInputDocument, addField)
{
	solr_char_t *field_name = NULL, *field_value = NULL;
	COMPAT_ARG_SIZE_T field_name_length  = 0, field_value_length = 0;
	solr_document_t *doc_entry = NULL;
	double field_boost = 0.0;


	/* Process the parameters passed to the method */
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|d", &field_name,
	        &field_name_length, &field_value, &field_value_length, &field_boost) == FAILURE) {
		RETURN_FALSE;
	}

	if (!field_name_length) {
		RETURN_FALSE;
	}

	/* Retrieve the document entry for the SolrDocument instance */
	if (solr_fetch_document_entry(getThis(), &doc_entry TSRMLS_CC) == SUCCESS)
	{
		solr_field_list_t *field_values      = NULL;

		/* If the field already exists in the SolrDocument instance append the value to the field list queue */
		if ((field_values = (solr_field_list_t *)zend_hash_str_find_ptr(doc_entry->fields, field_name, field_name_length)) != NULL) {
			if (solr_document_insert_field_value(field_values, (solr_char_t *)field_value, field_boost) == FAILURE) {
				RETURN_FALSE;
			}
		} else {

			/* Otherwise, create a new one and add it to the hash table */
			field_values     = (solr_field_list_t *)  pemalloc(sizeof(solr_field_list_t), SOLR_DOCUMENT_FIELD_PERSISTENT);

			memset(field_values, 0, sizeof(solr_field_list_t));

			field_values->count       = 0L;
			field_values->field_boost = 0.0;
			field_values->field_name  = (solr_char_t *) pestrdup((char *)field_name, SOLR_DOCUMENT_FIELD_PERSISTENT);
			field_values->head        = NULL;
			field_values->last        = NULL;

			if (solr_document_insert_field_value(field_values, field_value, field_boost) == FAILURE) {
				solr_destroy_field_list(field_values);
				RETURN_FALSE;
			}

			if (zend_hash_str_add_ptr(doc_entry->fields, field_name, field_name_length,(void *) field_values) == NULL) {
				solr_destroy_field_list(field_values);
				RETURN_FALSE;
			}

			/* Increment field count only when HEAD is added */
			doc_entry->field_count++;
		}

		RETURN_TRUE;
	}

	RETURN_FALSE;
}
/* {{{ void field_copy_constructor(solr_field_list_t **original_field_queue) */
PHP_SOLR_API void field_copy_constructor(solr_field_list_t **original_field_queue)
{
	solr_field_list_t *new_field_queue = NULL;
	solr_field_value_t *ptr = (*original_field_queue)->head;

	if (ptr == NULL)
	{
		return;
	}

	new_field_queue = (solr_field_list_t *) pemalloc(sizeof(solr_field_list_t), SOLR_DOCUMENT_FIELD_PERSISTENT);

	new_field_queue->count       = 0L;
	new_field_queue->field_name  = (solr_char_t *) pestrdup((char *) (*original_field_queue)->field_name, SOLR_DOCUMENT_FIELD_PERSISTENT);
	new_field_queue->head        = NULL;
	new_field_queue->last        = NULL;
	new_field_queue->field_boost = (*original_field_queue)->field_boost;

	while(ptr != NULL)
	{
		solr_document_insert_field_value(new_field_queue, ptr->field_value, 0);

		ptr = ptr->next;
	}

	*original_field_queue = new_field_queue;
}
Example #3
0
/* {{{ proto bool SolrInputDocument::updateField(string fieldName, int modifier, string value) */
PHP_METHOD(SolrInputDocument, updateField)
{
    solr_char_t *field_name = NULL, *field_value = NULL;
    COMPAT_ARG_SIZE_T field_name_length = 0, field_value_len = 0;
    solr_document_t *doc_entry;
    solr_field_list_t *field;
    uint field_exists = 0;

    long modifier = 0L;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sls", &field_name, &field_name_length, &modifier, &field_value, &field_value_len) == FAILURE) {
        return;
    }

    if (!field_name_length || !field_value_len) {
        RETURN_FALSE;
    }

    if (solr_fetch_document_entry(getThis(), &doc_entry TSRMLS_CC) == FAILURE)  {
        return;
    }

    switch (modifier) {
    case SOLR_FIELD_VALUE_MOD_ADD:
    case SOLR_FIELD_VALUE_MOD_REMOVE:
    case SOLR_FIELD_VALUE_MOD_REMOVEREGEX:
    case SOLR_FIELD_VALUE_MOD_SET:
    case SOLR_FIELD_VALUE_MOD_INC:
        break;

    default:
        solr_throw_exception_ex(solr_ce_SolrIllegalArgumentException, SOLR_ERROR_4003 TSRMLS_CC, SOLR_FILE_LINE_FUNC, SOLR_ERROR_4003_MSG);
        return;
    }

    if ((field = zend_hash_str_find_ptr(doc_entry->fields, field_name, field_name_length)) == NULL){
        field = (solr_field_list_t *)pemalloc(sizeof(solr_field_list_t), SOLR_DOCUMENT_FIELD_PERSISTENT);
        memset(field, 0, sizeof(solr_field_list_t));
        field->field_name = pestrdup(field_name, SOLR_DOCUMENT_FIELD_PERSISTENT);
        field->count = 1;
        field->head = NULL;
        field->last = NULL;
        if (modifier > 0) {
            field->modified = 1;
        }
        doc_entry->field_count++;
        if (zend_hash_str_add_ptr(doc_entry->fields, field_name, field_name_length, field) == NULL) {
            RETURN_FALSE;
        }
    } else if (field->modified == 0) {
        solr_throw_exception_ex(solr_ce_SolrIllegalOperationException, SOLR_ERROR_4004 TSRMLS_CC, SOLR_FILE_LINE_FUNC, SOLR_ERROR_4004_MSG);
        RETURN_FALSE;
    }


    solr_document_insert_field_value(field, field_value, 0.0, modifier);
}
/* {{{ PHP_SOLR_API int solr_document_insert_field_value(solr_field_list_t *queue, const solr_char_t *field_value, double field_boost) */
PHP_SOLR_API int solr_document_insert_field_value(solr_field_list_t *queue, const solr_char_t *field_value, double field_boost)
{
	solr_field_value_t *new_entry = (solr_field_value_t *) pemalloc(sizeof(solr_field_value_t), SOLR_DOCUMENT_FIELD_PERSISTENT);

	if (new_entry == NULL) {

		return FAILURE;
	}

	new_entry->field_value = (solr_char_t *) pestrdup((char *) field_value, SOLR_DOCUMENT_FIELD_PERSISTENT);

	if (new_entry->field_value == NULL) {

		return FAILURE;
	}

	new_entry->next = NULL;

	if (queue->head == NULL) {

		/* This is the first and only item in the field list */
		queue->head = new_entry;
		queue->last = new_entry;

		/* Update the field boost value */
		if (field_boost > 0.0) {

			queue->field_boost = field_boost;
		}

	} else { /* There are already entries in the list. */

		/* Append to the end of the queue */
		queue->last->next = new_entry;

		/* Set the last item in the queue to the latest entry */
		queue->last       = new_entry;

		/* Update the field boost value */
		if (field_boost > 0.0) {

			if (queue->field_boost > 0.0) {

				queue->field_boost *= field_boost;

			} else {

				queue->field_boost = field_boost;
			}
		}
	}

	queue->count++;

	return SUCCESS;
}
Example #5
0
int _pdo_sqlite_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line) /* {{{ */
{
	pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data;
	pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
	pdo_sqlite_error_info *einfo = &H->einfo;

	einfo->errcode = sqlite3_errcode(H->db);
	einfo->file = file;
	einfo->line = line;

	if (einfo->errcode != SQLITE_OK) {
		if (einfo->errmsg) {
			pefree(einfo->errmsg, dbh->is_persistent);
		}
		einfo->errmsg = pestrdup((char*)sqlite3_errmsg(H->db), dbh->is_persistent);
	} else { /* no error */
		strncpy(*pdo_err, PDO_ERR_NONE, sizeof(PDO_ERR_NONE));
		return 0;
	}
	switch (einfo->errcode) {
		case SQLITE_NOTFOUND:
			strncpy(*pdo_err, "42S02", sizeof("42S02"));
			break;

		case SQLITE_INTERRUPT:
			strncpy(*pdo_err, "01002", sizeof("01002"));
			break;

		case SQLITE_NOLFS:
			strncpy(*pdo_err, "HYC00", sizeof("HYC00"));
			break;

		case SQLITE_TOOBIG:
			strncpy(*pdo_err, "22001", sizeof("22001"));
			break;

		case SQLITE_CONSTRAINT:
			strncpy(*pdo_err, "23000", sizeof("23000"));
			break;

		case SQLITE_ERROR:
		default:
			strncpy(*pdo_err, "HY000", sizeof("HY000"));
			break;
	}

	if (!dbh->methods) {
		zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode, "SQLSTATE[%s] [%d] %s",
				*pdo_err, einfo->errcode, einfo->errmsg);
	}

	return einfo->errcode;
}
Example #6
0
mongo_server* mongo_util_server_copy(const mongo_server *source, mongo_server *dest, int persist TSRMLS_DC) {
  // we assume if def was persistent it will still be persistent and visa versa

  if (dest) {
    php_mongo_server_free(dest, persist TSRMLS_CC);
  }

  dest = (mongo_server*)pemalloc(sizeof(mongo_server), persist);
  memset(dest, 0, sizeof(mongo_server));

  dest->host = pestrdup(source->host, persist);
  dest->port = source->port;
  dest->label = pestrdup(source->label, persist);

  if (source->username && source->password && source->db) {
    dest->username = pestrdup(source->username, persist);
    dest->password = pestrdup(source->password, persist);
    dest->db = pestrdup(source->db, persist);
  }

  mongo_util_pool_get(dest, 0 TSRMLS_CC);

  return dest;
}
Example #7
0
int _record_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line, const char *sql_state,  int error_code, const char *error_message)
{
	pdo_nuodb_db_handle *H = (pdo_nuodb_db_handle *)dbh->driver_data;
	pdo_error_type *pdo_err;
	pdo_nuodb_error_info *einfo;
	pdo_nuodb_stmt *S = NULL;

	PDO_DBG_ENTER("_record_error");
	PDO_DBG_INF_FMT("file=%s line=%d", file, line);
	PDO_DBG_INF_FMT("sql_state=%s  error_code=%d  error_message=%s", sql_state, error_code, error_message);
	if (stmt) {
		S = (pdo_nuodb_stmt*)stmt->driver_data;
		PDO_DBG_INF_FMT("sql=%s", S->sql);
		pdo_err = &stmt->error_code;
		einfo   = &S->einfo;
	} else {
		pdo_err = &dbh->error_code;
		einfo   = &H->einfo;
	}

	einfo->errcode = error_code;
	einfo->file = file;
	einfo->line = line;
	if (einfo->errmsg) {
		pefree(einfo->errmsg, dbh->is_persistent);
		einfo->errmsg = NULL;
	}

	if (!einfo->errcode) { /* no error */
		strcpy(*pdo_err, PDO_ERR_NONE);
		PDO_DBG_RETURN(0);
	}

	einfo->errmsg = pestrdup(error_message, dbh->is_persistent);
	strncpy(*pdo_err, sql_state, 6);


	if (!dbh->methods) {
		TSRMLS_FETCH();
		PDO_DBG_INF("Throwing exception");
		zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
				*pdo_err, einfo->errcode, einfo->errmsg);
	}

	PDO_DBG_RETURN(einfo->errcode);

}
Example #8
0
int _pdo_4d_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC) /* {{{ */
{
	pdo_4d_db_handle *H = (pdo_4d_db_handle *)dbh->driver_data;
	pdo_error_type *pdo_err; 
	pdo_4d_error_info *einfo;
	pdo_4d_stmt *S = NULL;
	
	if (stmt) {
		S = (pdo_4d_stmt*)stmt->driver_data;
		pdo_err = &stmt->error_code;
		einfo   = &S->einfo;
	} else {
		pdo_err = &dbh->error_code;
		einfo   = &H->einfo;
	}
	
	//pdo_err = &dbh->error_code;
	//einfo   = &H->einfo;
	einfo->errcode = fourd_errno(H->server);
	einfo->file = file;
	einfo->line = line;
	
	/* free memory of last error message */
	if (einfo->errmsg) {
		pefree(einfo->errmsg, dbh->is_persistent);
		einfo->errmsg = NULL;
	}
	strncpy(*pdo_err, fourd_sqlstate(H->server),5);
	*pdo_err[5]=0;
	/* if error_code is not null => get error message */
	/* printf("einfo->errcode:%d\n",einfo->errcode); */
	if (einfo->errcode) {
		/* printf("copy errmsg\n"); */
		einfo->errmsg = pestrdup(fourd_error(H->server), dbh->is_persistent);
	}
	else {
		strcpy(*pdo_err, PDO_ERR_NONE);
		return 0;
	}
	if (!dbh->methods) {
		zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
				*pdo_err, einfo->errcode, einfo->errmsg);
	}
	
	return einfo->errcode;
}
Example #9
0
/**
 * {{{ proto bool SolrInputDocument::setVersion(int version)
 * Enable optimistic concurrency using assertions  */
PHP_METHOD(SolrInputDocument, setVersion)
{
    long version = 0;
    solr_document_t *doc_entry = NULL;
    solr_field_list_t *field = NULL;
    solr_char_t *field_name = "_version_";
    COMPAT_ARG_SIZE_T field_name_length = sizeof("_version_");
    char version_str[80];
    zend_error_handling error_handling;

    zend_replace_error_handling(EH_THROW, solr_ce_SolrIllegalArgumentException, &error_handling TSRMLS_CC);
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &version) == FAILURE) {
        zend_restore_error_handling(&error_handling TSRMLS_CC);
        return;
    }
    zend_restore_error_handling(&error_handling TSRMLS_CC);

    if (solr_fetch_document_entry(getThis(), &doc_entry TSRMLS_CC) == FAILURE) {
        return;
    }

    field = pemalloc(sizeof(solr_field_list_t), SOLR_DOCUMENT_FIELD_PERSISTENT);

    field->count = 0L;
    field->field_boost = 0.0f;
    field->field_name = pestrdup(field_name, SOLR_DOCUMENT_FIELD_PERSISTENT);
    field->head = field->last = NULL;

    snprintf(version_str, 80, "%ld", version);

    solr_document_insert_field_value(field, version_str, 0.0);

    if ((zend_hash_str_update_ptr(doc_entry->fields, field_name, field_name_length, field) == NULL )) {
        solr_throw_exception_ex(solr_ce_SolrException, SOLR_ERROR_1008 TSRMLS_CC, SOLR_FILE_LINE_FUNC, SOLR_ERROR_1008_MSG);
        solr_destroy_field_list(&field);
        return;
    }

    RETURN_TRUE;
}
Example #10
0
void _pdo_oledb_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, HRESULT result, const char *file, int line TSRMLS_DC)
{
	pdo_oledb_db_handle *H = (pdo_oledb_db_handle *)dbh->driver_data;
	pdo_error_type *pdo_err;
	pdo_oledb_error_info *einfo;
	pdo_oledb_stmt *S;
	int persistent = 0;

	if (!H) return;

	if (stmt) {
		S = (pdo_oledb_stmt*)stmt->driver_data;
		pdo_err = &stmt->error_code;
		einfo   = &S->einfo;
	} else {
		pdo_err = &dbh->error_code;
		einfo   = &H->einfo;
		persistent = dbh->is_persistent;
	}

	einfo->file = file;
	einfo->line = line;
	einfo->errcode = result;

	if (einfo->errmsg) {
		pefree(einfo->errmsg, persistent);
		einfo->errmsg = NULL;
	}

	if (!SUCCEEDED(result)) {
		HRESULT hr;
		IErrorInfo *pIErrorInfo = NULL;
		IErrorRecords *pIErrorRecords = NULL;
		ISQLErrorInfo *pISQLErrorInfo = NULL;

		/* get the error object */
		hr = GetErrorInfo(0, &pIErrorInfo);
		if (pIErrorInfo) {
			BSTR descr_w = NULL;
			BSTR sql_state_w = NULL;
			LONG native_error = 0;
			char *descr = NULL;

			/* use IErrorRecords if possible */
			hr = QUERY_INTERFACE(pIErrorInfo, IID_IErrorRecords, pIErrorRecords);
			if (pIErrorRecords) {
				BSTR *record_descrs;
				LONG record_count = 0, i;
				
				hr = CALL(GetRecordCount, pIErrorRecords, &record_count);
				record_descrs = (BSTR *) ecalloc(record_count, sizeof(*record_descrs));
				for (i = 0; i < record_count; i++) {
					IErrorInfo *pIErrorRecordInfo = NULL;
					hr = CALL(GetErrorInfo, pIErrorRecords, i, 0x0409, &pIErrorRecordInfo);
					if (pIErrorRecordInfo) {
						hr = CALL(GetDescription, pIErrorRecordInfo, &record_descrs[i]);
						RELEASE(pIErrorRecordInfo);
					}
				}

				if (record_descrs) {
					/* join the descriptions together */
					int total_len = 0, offset = 0;
					for (i = 0; i < record_count; i++) {
						if (record_descrs[i]) {
							total_len += wcslen(record_descrs[i]) + 1;
						}
					}
					descr_w = SysAllocStringLen(NULL, total_len);
					for (i = 0; i < record_count; i++) {
						/* don't append description if it's the same as the previous one */
						if (record_descrs[i] && (i == 0 || wcscmp(record_descrs[i], record_descrs[i - 1]) != 0)) {
							if(offset != 0) {
								descr_w[offset - 1] = ' ';
							}
							wcscpy(descr_w + offset, record_descrs[i]);
							offset += wcslen(record_descrs[i]) + 1;
							SysFreeString(record_descrs[i]);
						}
					}
					efree(record_descrs);
				}

				for (i = 0; i < record_count; i++) {
					/* get a ISQLErrorInfo interface to retrieve the SQL state */
					hr = CALL(GetCustomErrorObject, pIErrorRecords, i, &IID_ISQLErrorInfo, (IUnknown **) &pISQLErrorInfo);
					if (pISQLErrorInfo) {
						hr = CALL(GetSQLInfo, pISQLErrorInfo, &sql_state_w, &native_error);
						if (SUCCEEDED(hr)) {
							/* use the first one obtained */
							break;
						}
					}
				}
			} else {
				hr = CALL(GetDescription, pIErrorInfo, &descr_w);
			}

			if (sql_state_w) {
				char *sql_state;
				int sql_state_len;
				oledb_convert_bstr(H->conv, sql_state_w, -1, &sql_state, &sql_state_len, CONVERT_FROM_UNICODE_TO_OUTPUT);
				if(sql_state_len <= 5) {
					strcpy(*pdo_err, sql_state);
				}
				efree(sql_state);
			} else {
				/* don't know what happened */
				strcpy(*pdo_err, "58004");
			}
			if (descr_w) {
				oledb_convert_bstr(H->conv, descr_w, -1, &descr, NULL, CONVERT_FROM_UNICODE_TO_OUTPUT);
				if (persistent) {
					einfo->errmsg = pestrdup(descr, persistent);
					efree(descr);
				} else {
					einfo->errmsg = descr;
				}
			}

			SysFreeString(descr_w);
			SysFreeString(sql_state_w);

			SAFE_RELEASE(pISQLErrorInfo);
			SAFE_RELEASE(pIErrorInfo);
			SAFE_RELEASE(pIErrorRecords);
		} else {
			/* no IErrorInfo, see if it's a pre-defined OLE-DB error  */
			const char *msg = oledb_hresult_text(result);
			if (msg) {
				einfo->errmsg = pestrdup(msg, persistent);
			} else {
				/* maybe it's a generic Windows error */
				LPVOID lpMsgBuf;
				FormatMessage( 
					FORMAT_MESSAGE_ALLOCATE_BUFFER | 
					FORMAT_MESSAGE_FROM_SYSTEM | 
					FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL,
					result,
					MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
					(LPTSTR) &lpMsgBuf,
					0,
					NULL 
				);
				if (lpMsgBuf) {
					einfo->errmsg = pestrdup((char *) lpMsgBuf, persistent);
					LocalFree(lpMsgBuf);
				}
			}
		}

		if (!dbh->methods) {
			zend_throw_exception_ex(_php_pdo_get_exception(), 0 TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
					*pdo_err, einfo->errcode, einfo->errmsg);
		}
	} else { /* no error */
		strcpy(*pdo_err, PDO_ERR_NONE);
	}
}
Example #11
0
/* {{{ _pdo_mysql_error */
int _pdo_mysql_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)
{
	pdo_mysql_db_handle *H = (pdo_mysql_db_handle *)dbh->driver_data;
	pdo_error_type *pdo_err; 
	pdo_mysql_error_info *einfo;
	pdo_mysql_stmt *S = NULL;

	PDO_DBG_ENTER("_pdo_mysql_error");
	PDO_DBG_INF_FMT("file=%s line=%d", file, line);
	if (stmt) {
		S = (pdo_mysql_stmt*)stmt->driver_data;
		pdo_err = &stmt->error_code;
		einfo   = &S->einfo;
	} else {
		pdo_err = &dbh->error_code;
		einfo   = &H->einfo;
	}

	if (S && S->stmt) {
		einfo->errcode = mysql_stmt_errno(S->stmt);
	} else {
		einfo->errcode = mysql_errno(H->server);
	}

	einfo->file = file;
	einfo->line = line;

	if (einfo->errmsg) {
		pefree(einfo->errmsg, dbh->is_persistent);
		einfo->errmsg = NULL;
	}

	if (einfo->errcode) {
		if (einfo->errcode == 2014) {
			einfo->errmsg = pestrdup(
				"Cannot execute queries while other unbuffered queries are active.  "
				"Consider using PDOStatement::fetchAll().  Alternatively, if your code "
				"is only ever going to run against mysql, you may enable query "
				"buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.",
				dbh->is_persistent);
		} else if (einfo->errcode == 2057) {
			einfo->errmsg = pestrdup(
				"A stored procedure returning result sets of different size was called. "
				"This is not supported by libmysql",
				dbh->is_persistent);

		} else {
			einfo->errmsg = pestrdup(mysql_error(H->server), dbh->is_persistent);
		}
	} else { /* no error */
		strcpy(*pdo_err, PDO_ERR_NONE);
		PDO_DBG_RETURN(0);
	}

	if (S && S->stmt) {
		strcpy(*pdo_err, mysql_stmt_sqlstate(S->stmt));
	} else {
		strcpy(*pdo_err, mysql_sqlstate(H->server));
	}

	if (!dbh->methods) {
		PDO_DBG_INF("Throwing exception");
		zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
				*pdo_err, einfo->errcode, einfo->errmsg);
	}

	PDO_DBG_RETURN(einfo->errcode);
}
Example #12
0
PHP_METHOD(Bucket, __construct)
{
    bucket_object *data = PCBC_PHP_THISOBJ();
    zval *zdsn = NULL;
    zval *zname = NULL;
    zval *zpassword = NULL;
    char *dsn = NULL;
    char *name = NULL;
    char *password = NULL;
    lcb_error_t err;
    lcb_t instance;
    struct lcb_create_st create_options;
    char *connkey = NULL;
    pcbc_lcb *conn_iter, *conn;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zzz",
                              &zdsn, &zname, &zpassword) == FAILURE) {
        RETURN_NULL();
    }

    if (zap_zval_is_undef(zdsn)) {
        zdsn = NULL;
    }
    if (zap_zval_is_undef(zname)) {
        zname = NULL;
    }
    if (zap_zval_is_undef(zpassword)) {
        zpassword = NULL;
    }

    if (zdsn) {
        if (Z_TYPE_P(zdsn) == IS_STRING) {
            dsn = estrndup(Z_STRVAL_P(zdsn), Z_STRLEN_P(zdsn));
        } else {
            throw_pcbc_exception("Expected dsn as string", LCB_EINVAL);
            RETURN_NULL();
        }
    }

    if (zname) {
        if (Z_TYPE_P(zname) == IS_STRING) {
            name = estrndup(Z_STRVAL_P(zname), Z_STRLEN_P(zname));
        } else {
            throw_pcbc_exception("Expected bucket name as string", LCB_EINVAL);
            if (dsn) efree(dsn);
            RETURN_NULL();
        }
    }

    if (zpassword) {
        if (Z_TYPE_P(zpassword) == IS_STRING) {
            password = estrndup(Z_STRVAL_P(zpassword), Z_STRLEN_P(zpassword));
        } else {
            throw_pcbc_exception("Expected bucket password as string", LCB_EINVAL);
            if (dsn) efree(dsn);
            if (name) efree(name);
            RETURN_NULL();
        }
    }

    spprintf(&connkey, 512, "%s|%s|%s",
             dsn ? dsn : "",
             name ? name : "",
             password ? password : "");

    conn_iter = PCBCG(first_bconn);
    while (conn_iter) {
        if (strcmp(conn_iter->key, connkey) == 0) {
            break;
        }
        conn_iter = conn_iter->next;
    }

    if (!conn_iter)
    {
        memset(&create_options, 0, sizeof(create_options));
        create_options.version = 3;
        create_options.v.v3.connstr = dsn;
        create_options.v.v3.username = name;
        create_options.v.v3.passwd = password;
        create_options.v.v3.type = LCB_TYPE_BUCKET;
        err = lcb_create(&instance, &create_options);

        if (dsn) efree(dsn);
        if (password) efree(password);

        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            throw_lcb_exception(err);
            RETURN_NULL();
        }
        lcb_cntl(instance, LCB_CNTL_SET, LCB_CNTL_CLIENT_STRING, pcbc_client_string);

        lcb_install_callback3(instance, LCB_CALLBACK_GET, get_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_UNLOCK, unlock_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_STORE, store_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_STOREDUR, store_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_REMOVE, remove_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_TOUCH, touch_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_COUNTER, counter_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_SDLOOKUP, subdoc_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_SDMUTATE, subdoc_callback);
        lcb_install_callback3(instance, LCB_CALLBACK_HTTP, http_callback);

        lcb_set_durability_callback(instance, durability_callback);


        err = lcb_connect(instance);
        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            lcb_destroy(instance);
            throw_lcb_exception(err);
            RETURN_NULL();
        }

        // We use lcb_wait here as no callbacks are invoked by connect.
        lcb_wait(instance);

        err = lcb_get_bootstrap_status(instance);
        if (err != LCB_SUCCESS) {
            efree(connkey);
            efree(name);
            lcb_destroy(instance);
            throw_lcb_exception(err);
            RETURN_NULL();
        }

        conn = pemalloc(sizeof(pcbc_lcb), 1);
        conn->bucket = pestrdup(name, 1);
        efree(name);
        conn->key = pestrdup(connkey, 1);
        conn->lcb = instance;
        conn->next = NULL;
        data->conn = conn;

        if (PCBCG(last_bconn)) {
            PCBCG(last_bconn)->next = conn;
            PCBCG(last_bconn) = conn;
        } else {
            PCBCG(first_bconn) = conn;
            PCBCG(last_bconn) = conn;
        }
    } else {
        if (dsn) efree(dsn);
        if (name) efree(name);
        if (password) efree(password);

        data->conn = conn_iter;
    }

    efree(connkey);
}
Example #13
0
// file_get_contents
// and then 
// parse all tags
static void parse_sys_tags(const char *filename) 
{
	long size, maxsize;
	int error = 0;

	FILE *fp = VCWD_FOPEN(filename, "rb");
	if (!fp) {
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename);
		return ;
	}
	fseek(fp, 0, SEEK_END);
	maxsize = ftell(fp);
	rewind(fp);
	if (maxsize > 2097152) // 2M limit
		maxsize = 2097152;
	char *contents = (char *)emalloc(maxsize + 1);
	size = fread(contents, 1, maxsize, fp);
	fclose(fp);
	if (size < 0)
		php_error_docref(NULL TSRMLS_CC, E_WARNING, "tpl_tags file error(%s)", filename);
	if (size <= 0)
		return;
	contents[size] = '\0';

	// parse
	const int S_KEY_START = 0, S_KEY_END = 1, S_CONT_START = 2;
	int state = S_KEY_START;
	char *tag_name, *tag_content;
	char *p, *cur = contents, *end = contents + size - 1;
	while (cur < end) {
		p = strstr(cur, "---");
		if (p == NULL) {
			cur = end;
			if (state != S_CONT_START)
				break;
		} else {
			cur = p + 3;
			p--;
		}
		if (state == S_CONT_START) {
			if (p == NULL)
				p = end;
			while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
				p--;
			*++p = '\0';
			// add tag
			char *tmp_s = pestrdup(tag_content, 1);
			zend_hash_update(STU_G(tpl_tags_sys), tag_name, strlen(tag_name) + 1, &tmp_s, sizeof(char *), NULL);
			state = S_KEY_START;
			if (cur == end) 
				break;
		}
		if (state == S_KEY_START) {
			while (cur < end && (*cur == ' ' || *cur == '\t' || *cur == '-')) // cannot has newline arround tag_name
				cur++;
			if ((*cur >= 'A' && *cur <= 'Z') || (*cur >= 'a' && *cur <= 'z') || *cur == '_')
				tag_name = cur;
			else {
				// tag name must start with [a-zA-Z_]
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "tag name must start with [a-zA-Z_] (%s)", tag_name);
				break;
			}
			state = S_KEY_END;
		} else if (state == S_KEY_END) {
			while (*p == ' ' || *p == '\t' || *cur == '-') // cannot has newline arround tag_name
				p--;
			*++p = '\0';
			while (cur < end && (*cur == ' ' || *cur++ == '\t' || *cur == '\n' || *cur == '\r'))
				cur++;
			tag_content = cur;
			state = S_CONT_START;
		}
	}
	efree(contents);
}
Example #14
0
/* {{{ static int solr_document_set_field(zval *objptr, solr_char_t *field_name, int field_name_length, solr_char_t *field_value, int field_value_length TSRMLS_DC) */
static int solr_document_set_field(zval *objptr, solr_char_t *field_name, int field_name_length, solr_char_t *field_value, int field_value_length TSRMLS_DC)
{
	double field_boost = 0.0f;

	solr_document_t *doc_entry = NULL;

	if (!field_name_length) {

		return FAILURE;
	}

	if (!field_value_length)
	{
		return FAILURE;
	}

	/* Retrieve the document entry for the SolrDocument instance */
	if (solr_fetch_document_entry(objptr, &doc_entry TSRMLS_CC) == SUCCESS)
	{
		solr_field_list_t **field_values_ptr = NULL;
		solr_field_list_t *field_values      = NULL;

		/* If the field already exists in the SolrDocument instance append the value to the field list queue */
		if (zend_hash_find(doc_entry->fields, field_name, field_name_length, (void **) &field_values_ptr) == SUCCESS) {

			if (solr_document_insert_field_value(*field_values_ptr, field_value, field_boost) == FAILURE) {

				return FAILURE;
			}

		} else {

			/* Otherwise, create a new one and add it to the hash table */
			field_values = (solr_field_list_t *)  pemalloc(sizeof(solr_field_list_t), SOLR_DOCUMENT_FIELD_PERSISTENT);

			memset(field_values, 0, sizeof(solr_field_list_t));

			field_values_ptr = &field_values;

			field_values->count       = 0L;
			field_values->field_boost = 0.0;
			field_values->field_name  = (solr_char_t *) pestrdup(field_name,SOLR_DOCUMENT_FIELD_PERSISTENT);
			field_values->head        = NULL;
			field_values->last        = NULL;

			if (solr_document_insert_field_value(field_values, field_value, field_boost) == FAILURE) {

				solr_destroy_field_list(&field_values);

				return FAILURE;
			}

			if (zend_hash_add(doc_entry->fields, field_name, field_name_length, (void *) field_values_ptr, sizeof(solr_field_list_t *), (void **) NULL) == FAILURE) {

				solr_destroy_field_list(&field_values);

				return FAILURE;
			}

			/* Increment field count only when HEAD is added */
			doc_entry->field_count++;
		}

		return SUCCESS;
	}

	return FAILURE;
}
Example #15
0
static ZEND_INI_MH(OnUpdateSuhosin_perdir)
{
        char *tmp;

	if (SUHOSIN_G(perdir)) {
    		pefree(SUHOSIN_G(perdir), 1);
	}
	SUHOSIN_G(perdir) = NULL;
    
        /* Initialize the perdir flags */
        SUHOSIN_G(log_perdir) = 0;
        SUHOSIN_G(exec_perdir) = 0;
        SUHOSIN_G(get_perdir) = 0;
        SUHOSIN_G(cookie_perdir) = 0;
        SUHOSIN_G(post_perdir) = 0;
        SUHOSIN_G(request_perdir) = 0;
        SUHOSIN_G(sql_perdir) = 0;
        SUHOSIN_G(upload_perdir) = 0;
        SUHOSIN_G(misc_perdir) = 0;
    
	if (new_value == NULL) {
		return SUCCESS;
	}
	
        tmp = SUHOSIN_G(perdir) = pestrdup(new_value,1);
        
        /* trim the whitespace */
        while (isspace(*tmp)) tmp++;
        
        /* should we deactivate perdir completely? */
        if (*tmp == 0 || *tmp == '0') {
            return SUCCESS;
        }
        
        /* no deactivation so check the flags */
        while (*tmp) {
            switch (*tmp) {
                case 'l':
                case 'L':
                    SUHOSIN_G(log_perdir) = 1;
                    break;
                case 'e':
                case 'E':
                    SUHOSIN_G(exec_perdir) = 1;
                    break;
                case 'g':
                case 'G':
                    SUHOSIN_G(get_perdir) = 1;
                    break;
                case 'c':
                case 'C':
                    SUHOSIN_G(cookie_perdir) = 1;
                    break;
                case 'p':
                case 'P':
                    SUHOSIN_G(post_perdir) = 1;
                    break;
                case 'r':
                case 'R':
                    SUHOSIN_G(request_perdir) = 1;
                    break;
                case 's':
                case 'S':
                    SUHOSIN_G(sql_perdir) = 1;
                    break;
                case 'u':
                case 'U':
                    SUHOSIN_G(upload_perdir) = 1;
                    break;
                case 'm':
                case 'M':
                    SUHOSIN_G(misc_perdir) = 1;
                    break;
            }
            tmp++;
        }        
	return SUCCESS;
}
Example #16
0
File: dba.c Project: Jille/php-src
/* {{{ php_dba_open
 */
static void php_dba_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
	zval *args = NULL;
	int ac = ZEND_NUM_ARGS();
	dba_mode_t modenr;
	dba_info *info, *other;
	dba_handler *hptr;
	char *key = NULL, *error = NULL;
	int keylen = 0;
	int i;
	int lock_mode, lock_flag, lock_dbf = 0;
	char *file_mode;
	char mode[4], *pmode, *lock_file_mode = NULL;
	int persistent_flag = persistent ? STREAM_OPEN_PERSISTENT : 0;
	zend_string *opened_path = NULL;
	char *lock_name;

	if (ac < 2) {
		WRONG_PARAM_COUNT;
	}

	/* we pass additional args to the respective handler */
	args = safe_emalloc(ac, sizeof(zval), 0);
	if (zend_get_parameters_array_ex(ac, args) != SUCCESS) {
		efree(args);
		WRONG_PARAM_COUNT;
	}

	/* we only take string arguments */
	for (i = 0; i < ac; i++) {
		if (Z_TYPE(args[i]) != IS_STRING) {
			convert_to_string_ex(&args[i]);
		} else if (Z_REFCOUNTED(args[i])) {
			Z_ADDREF(args[i]);
		}
		keylen += Z_STRLEN(args[i]);
	}

	if (persistent) {
		zend_resource *le;

		/* calculate hash */
		key = safe_emalloc(keylen, 1, 1);
		key[keylen] = '\0';
		keylen = 0;

		for(i = 0; i < ac; i++) {
			memcpy(key+keylen, Z_STRVAL(args[i]), Z_STRLEN(args[i]));
			keylen += Z_STRLEN(args[i]);
		}

		/* try to find if we already have this link in our persistent list */
		if ((le = zend_hash_str_find_ptr(&EG(persistent_list), key, keylen)) != NULL) {
			FREENOW;

			if (le->type != le_pdb) {
				RETURN_FALSE;
			}

			info = (dba_info *)le->ptr;

			GC_REFCOUNT(le)++;
			RETURN_RES(le);
			return;
		}
	}

	if (ac==2) {
		hptr = DBA_G(default_hptr);
		if (!hptr) {
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No default handler selected");
			FREENOW;
			RETURN_FALSE;
		}
	} else {
		for (hptr = handler; hptr->name && strcasecmp(hptr->name, Z_STRVAL(args[2])); hptr++);
	}

	if (!hptr->name) {
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "No such handler: %s", Z_STRVAL(args[2]));
		FREENOW;
		RETURN_FALSE;
	}

	/* Check mode: [rwnc][fl]?t?
	 * r: Read
	 * w: Write
	 * n: Create/Truncate
	 * c: Create
	 *
	 * d: force lock on database file
	 * l: force lock on lck file
	 * -: ignore locking
	 *
	 * t: test open database, warning if locked
	 */
	strlcpy(mode, Z_STRVAL(args[1]), sizeof(mode));
	pmode = &mode[0];
	if (pmode[0] && (pmode[1]=='d' || pmode[1]=='l' || pmode[1]=='-')) { /* force lock on db file or lck file or disable locking */
		switch (pmode[1]) {
		case 'd':
			lock_dbf = 1;
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				lock_flag = (hptr->flags & DBA_LOCK_ALL);
				break;
			}
			/* no break */
		case 'l':
			lock_flag = DBA_LOCK_ALL;
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_NOTICE, "Handler %s does locking internally", hptr->name);
			}
			break;
		default:
		case '-':
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Locking cannot be disabled for handler %s", hptr->name);
				FREENOW;
				RETURN_FALSE;
			}
			lock_flag = 0;
			break;
		}
	} else {
		lock_flag = (hptr->flags&DBA_LOCK_ALL);
		lock_dbf = 1;
	}
	switch (*pmode++) {
		case 'r':
			modenr = DBA_READER;
			lock_mode = (lock_flag & DBA_LOCK_READER) ? LOCK_SH : 0;
			file_mode = "r";
			break;
		case 'w':
			modenr = DBA_WRITER;
			lock_mode = (lock_flag & DBA_LOCK_WRITER) ? LOCK_EX : 0;
			file_mode = "r+b";
			break;
		case 'c':
			modenr = DBA_CREAT;
			lock_mode = (lock_flag & DBA_LOCK_CREAT) ? LOCK_EX : 0;
			if (lock_mode) {
				if (lock_dbf) {
					/* the create/append check will be done on the lock
					 * when the lib opens the file it is already created
					 */
					file_mode = "r+b";       /* read & write, seek 0 */
					lock_file_mode = "a+b";  /* append */
				} else {
					file_mode = "a+b";       /* append */
					lock_file_mode = "w+b";  /* create/truncate */
				}
			} else {
				file_mode = "a+b";
			}
			/* In case of the 'a+b' append mode, the handler is responsible
			 * to handle any rewind problems (see flatfile handler).
			 */
			break;
		case 'n':
			modenr = DBA_TRUNC;
			lock_mode = (lock_flag & DBA_LOCK_TRUNC) ? LOCK_EX : 0;
			file_mode = "w+b";
			break;
		default:
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
			FREENOW;
			RETURN_FALSE;
	}
	if (!lock_file_mode) {
		lock_file_mode = file_mode;
	}
	if (*pmode=='d' || *pmode=='l' || *pmode=='-') {
		pmode++; /* done already - skip here */
	}
	if (*pmode=='t') {
		pmode++;
		if (!lock_flag) {
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "You cannot combine modifiers - (no lock) and t (test lock)");
			FREENOW;
			RETURN_FALSE;
		}
		if (!lock_mode) {
			if ((hptr->flags & DBA_LOCK_ALL) == 0) {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s uses its own locking which doesn't support mode modifier t (test lock)", hptr->name);
				FREENOW;
				RETURN_FALSE;
			} else {
				php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Handler %s doesn't uses locking for this mode which makes modifier t (test lock) obsolete", hptr->name);
				FREENOW;
				RETURN_FALSE;
			}
		} else {
			lock_mode |= LOCK_NB; /* test =: non blocking */
		}
	}
	if (*pmode) {
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Illegal DBA mode");
		FREENOW;
		RETURN_FALSE;
	}

	info = pemalloc(sizeof(dba_info), persistent);
	memset(info, 0, sizeof(dba_info));
	info->path = pestrdup(Z_STRVAL(args[0]), persistent);
	info->mode = modenr;
	info->argc = ac - 3;
	info->argv = args + 3;
	info->flags = (hptr->flags & ~DBA_LOCK_ALL) | (lock_flag & DBA_LOCK_ALL) | (persistent ? DBA_PERSISTENT : 0);
	info->lock.mode = lock_mode;

	/* if any open call is a locking call:
	 * check if we already habe a locking call open that should block this call
	 * the problem is some systems would allow read during write
	 */
	if (hptr->flags & DBA_LOCK_ALL) {
		if ((other = php_dba_find(info->path)) != NULL) {
			if (   ( (lock_mode&LOCK_EX)        && (other->lock.mode&(LOCK_EX|LOCK_SH)) )
			    || ( (other->lock.mode&LOCK_EX) && (lock_mode&(LOCK_EX|LOCK_SH))        )
			   ) {
				error = "Unable to establish lock (database file already open)"; /* force failure exit */
			}
		}
	}

	if (!error && lock_mode) {
		if (lock_dbf) {
			lock_name = Z_STRVAL(args[0]);
		} else {
			spprintf(&lock_name, 0, "%s.lck", info->path);
			if (!strcmp(file_mode, "r")) {
				/* when in read only mode try to use existing .lck file first */
				/* do not log errors for .lck file while in read ony mode on .lck file */
				lock_file_mode = "rb";
				info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|IGNORE_PATH|persistent_flag, &opened_path);
			}
			if (!info->lock.fp) {
				/* when not in read mode or failed to open .lck file read only. now try again in create(write) mode and log errors */
				lock_file_mode = "a+b";
			} else {
				if (opened_path) {
					info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
					zend_string_release(opened_path);
				}
			}
		}
		if (!info->lock.fp) {
			info->lock.fp = php_stream_open_wrapper(lock_name, lock_file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, &opened_path);
			if (info->lock.fp) {
				if (lock_dbf) {
					/* replace the path info with the real path of the opened file */
					pefree(info->path, persistent);
					info->path = pestrndup(opened_path->val, opened_path->len, persistent);
				}
				/* now store the name of the lock */
				info->lock.name = pestrndup(opened_path->val, opened_path->len, persistent);
				zend_string_release(opened_path);
			}
		}
		if (!lock_dbf) {
			efree(lock_name);
		}
		if (!info->lock.fp) {
			dba_close(info);
			/* stream operation already wrote an error message */
			FREENOW;
			RETURN_FALSE;
		}
		if (!php_stream_supports_lock(info->lock.fp)) {
			error = "Stream does not support locking";
		}
		if (php_stream_lock(info->lock.fp, lock_mode)) {
			error = "Unable to establish lock"; /* force failure exit */
		}
	}

	/* centralised open stream for builtin */
	if (!error && (hptr->flags&DBA_STREAM_OPEN)==DBA_STREAM_OPEN) {
		if (info->lock.fp && lock_dbf) {
			info->fp = info->lock.fp; /* use the same stream for locking and database access */
		} else {
			info->fp = php_stream_open_wrapper(info->path, file_mode, STREAM_MUST_SEEK|REPORT_ERRORS|IGNORE_PATH|persistent_flag, NULL);
		}
		if (!info->fp) {
			dba_close(info);
			/* stream operation already wrote an error message */
			FREENOW;
			RETURN_FALSE;
		}
		if (hptr->flags & (DBA_NO_APPEND|DBA_CAST_AS_FD)) {
			/* Needed because some systems do not allow to write to the original
			 * file contents with O_APPEND being set.
			 */
			if (SUCCESS != php_stream_cast(info->fp, PHP_STREAM_AS_FD, (void*)&info->fd, 1)) {
				php_error_docref(NULL, E_WARNING, "Could not cast stream");
				dba_close(info);
				FREENOW;
				RETURN_FALSE;
#ifdef F_SETFL
			} else if (modenr == DBA_CREAT) {
				int flags = fcntl(info->fd, F_SETFL);
				fcntl(info->fd, F_SETFL, flags & ~O_APPEND);
#endif
			}

		}
	}

	if (error || hptr->open(info, &error) != SUCCESS) {
		dba_close(info);
		php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Driver initialization failed for handler: %s%s%s", hptr->name, error?": ":"", error?error:"");
		FREENOW;
		RETURN_FALSE;
	}

	info->hnd = hptr;
	info->argc = 0;
	info->argv = NULL;

	if (persistent) {
		zend_resource new_le;

		new_le.type = le_pdb;
		new_le.ptr = info;
		if (zend_hash_str_update_mem(&EG(persistent_list), key, keylen, &new_le, sizeof(zend_resource)) == NULL) {
			dba_close(info);
			php_error_docref2(NULL, Z_STRVAL(args[0]), Z_STRVAL(args[1]), E_WARNING, "Could not register persistent resource");
			FREENOW;
			RETURN_FALSE;
		}
	}

	RETVAL_RES(zend_register_resource(info, (persistent ? le_pdb : le_db)));
	FREENOW;
}
Example #17
0
//PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(char *regex, int regex_len TSRMLS_DC)
pcre *compileRegex( char *regex , int regex_len , char *msg , int msglen ) 
{
	pcre				*re = NULL;
	pcre_extra			*extra;
	int					 coptions = 0;
	int					 soptions = 0;
	const char			*error;
	int					 erroffset;
	char				 delimiter;
	char				 start_delimiter;
	char				 end_delimiter;
	char				*p, *pp;
	char				*pattern;
	int					 do_study = 0;
	int					 poptions = 0;
	unsigned const char *tables = NULL;
    char buf[ 1024 ] ;

#if HAVE_SETLOCALE
	char				*locale = setlocale(LC_CTYPE, NULL);
#endif

    //R.A.W.
	//pcre_cache_entry	*pce;
	//pcre_cache_entry	 new_entry;
    if( msglen )
    {
        *msg = '\0';
    }

	/* Try to lookup the cached regex entry, and if successful, just pass
	   back the compiled pattern, otherwise go on and compile it. */
	regex_len = strlen(regex);

//R.A.W.
#if 0  

	if (zend_hash_find(&PCRE_G(pcre_cache), regex, regex_len+1, (void **)&pce) == SUCCESS) {
		/*
		 * We use a quick pcre_info() check to see whether cache is corrupted, and if it
		 * is, we flush it and compile the pattern from scratch.
		 */
		if (pcre_info(pce->re, NULL, NULL) == PCRE_ERROR_BADMAGIC) {
			zend_hash_clean(&PCRE_G(pcre_cache));
		} else {
#if HAVE_SETLOCALE
			if (!strcmp(pce->locale, locale)) {
#endif
				return pce;
#if HAVE_SETLOCALE
			}
#endif
		}
	}
#endif
	p = regex;
	
	/* Parse through the leading whitespace, and display a warning if we
	   get to the end without encountering a delimiter. */
	while (isspace((int)*(unsigned char *)p)) p++;
	if (*p == 0) {

        // R.A.W.
		//php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty regular expression");
        strncpy(msg, "Empty regular expression" , msglen );

		return NULL;
	}
	
	/* Get the delimiter and display a warning if it is alphanumeric
	   or a backslash. */
	delimiter = *p++;
	if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
		//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Delimiter must not be alphanumeric or backslash");
		strncpy( msg, "Delimiter must not be alphanumeric or backslash",msglen);
		return NULL;
	}

	start_delimiter = delimiter;
	if ((pp = strchr("([{< )]}> )]}>", delimiter)))
		delimiter = pp[5];
	end_delimiter = delimiter;

	if (start_delimiter == end_delimiter) {
		/* We need to iterate through the pattern, searching for the ending delimiter,
		   but skipping the backslashed delimiters.  If the ending delimiter is not
		   found, display a warning. */
		pp = p;
		while (*pp != 0) {
			if (*pp == '\\' && pp[1] != 0) pp++;
			else if (*pp == delimiter)
				break;
			pp++;
		}
		if (*pp == 0) {
			//php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending delimiter '%c' found", delimiter);

            //R.A.W.
            strncpy( msg, "No ending delimiter found" ,msglen ) ;
			return NULL;
		}
	} else {
		/* We iterate through the pattern, searching for the matching ending
		 * delimiter. For each matching starting delimiter, we increment nesting
		 * level, and decrement it for each matching ending delimiter. If we
		 * reach the end of the pattern without matching, display a warning.
		 */
		int brackets = 1; 	/* brackets nesting level */
		pp = p;
		while (*pp != 0) {
			if (*pp == '\\' && pp[1] != 0) pp++;
			else if (*pp == end_delimiter && --brackets <= 0)
				break;
			else if (*pp == start_delimiter)
				brackets++;
			pp++;
		}
		if (*pp == 0) {
			//php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending matching delimiter '%c' found", end_delimiter);
			strncpy( msg,"No ending matching delimiter found",msglen ) ;
			return NULL;
		}
	}
	
	/* Make a copy of the actual pattern. */
    // R.A.W.
	//pattern = strndup(p, pp-p);
    // osx compile is complaining about strndup and since I have te
    // other function anyway and since I'll someday rewrite this fn, just
    // call that other function now :>)
    pattern = ghstrndup( p,pp-p) ;


	/* Move on to the options */
	pp++;

	/* Parse through the options, setting appropriate flags.  Display
	   a warning if we encounter an unknown modifier. */	
	while (*pp != 0) {
		switch (*pp++) {
			/* Perl compatible options */
			case 'i':	coptions |= PCRE_CASELESS;		break;
			case 'm':	coptions |= PCRE_MULTILINE;		break;
			case 's':	coptions |= PCRE_DOTALL;		break;
			case 'x':	coptions |= PCRE_EXTENDED;		break;
			
			/* PCRE specific options */
			case 'A':	coptions |= PCRE_ANCHORED;		break;
			case 'D':	coptions |= PCRE_DOLLAR_ENDONLY;break;
			case 'S':	do_study  = 1;					break;
			case 'U':	coptions |= PCRE_UNGREEDY;		break;
			case 'X':	coptions |= PCRE_EXTRA;			break;
			case 'u':	coptions |= PCRE_UTF8;			break;

                // R.A.W.
			/* Custom preg options */
                //case 'e':	poptions |= PREG_REPLACE_EVAL;	break;
			
			case ' ':
			case '\n':
				break;

			default:
				//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Unknown modifier '%c'", pp[-1]);
                strncpy( msg,"Unknown modifier",msglen ) ;
				free(pattern);
				return NULL;
		}
	}

    //R.A.W.
    tables = NULL ;
#if 0 
#if HAVE_SETLOCALE
	if (strcmp(locale, "C"))
		tables = pcre_maketables();
#endif
#endif

	/* Compile pattern and display a warning if compilation failed. */
	re = pcre_compile(pattern,
					  coptions,
					  &error,
					  &erroffset,
					  tables);

	if (re == NULL) {
		//php_error_docref(NULL TSRMLS_CC,E_WARNING, "Compilation failed: %s at offset %d", error, erroffset);

        // R.A.W.
		sprintf(buf, "Compilation of /%s/ failed: %s at offset %d",pattern, error, erroffset);
		//sprintf(buf, "Compilation failed: %s at offset %d",error, erroffset);
        strncpy( msg, buf , msglen ) ;
		free(pattern);
        // R.A.W.
		//if (tables) {
			//pefree((void*)tables, 1);
        //}
		return NULL;
	}

	/* If study option was specified, study the pattern and
	   store the result in extra for passing to pcre_exec. */
	if (do_study) {
		extra = pcre_study(re, soptions, &error);
		if (extra) {
			extra->flags |= PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
		}
		if (error != NULL) {
			strncpy( msg, "Error while studying pattern",msglen);
		}
	} else {
		extra = NULL;
	}

	free(pattern);


//R.A.W.
#if 0 
	/*
	 * If we reached cache limit, clean out the items from the head of the list;
	 * these are supposedly the oldest ones (but not necessarily the least used
	 * ones).
	 */
	if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
		int num_clean = PCRE_CACHE_SIZE / 8;
		zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean TSRMLS_CC);
	}

	/* Store the compiled pattern and extra info in the cache. */
	new_entry.re = re;
	new_entry.extra = extra;
	new_entry.preg_options = poptions;
	new_entry.compile_options = coptions;
#if HAVE_SETLOCALE
	new_entry.locale = pestrdup(locale, 1);
	new_entry.tables = tables;
#endif
	zend_hash_update(&PCRE_G(pcre_cache), regex, regex_len+1, (void *)&new_entry,
						sizeof(pcre_cache_entry), (void**)&pce);

#endif

    //	return pce;
    //R.A.W.
    return re ;
}