Custom sorting with MongoDB and PHP - php

I connect to Mongodb using the PECL PHP module Mongo. But I'm unable to find a solution to perform a custom server side sorting by passing an own Javascript function to the server.
$client = new \MongoClient( 'mongodb://localhost:27017', array() );
$collection = $client->selectCollection( 'mydata', 'users' );
$cursor = $collection->find( <my-query> );
$cursor->sort( <custom-sorting> );
In the Mongodb console this command works fine:
db.eval(
function() {
return db.users.find().toArray().sort(
function( doc1, doc2 ) {
return doc1.email < doc2.email;
}
)
}
);
But I'm unable to pass such a sorting function to the server using the PECL module. I found nothing in the documentation until yet.

Related

Cannot create glossary in Cloud Translation API v3

I'm playing around with Cloud Translation API v3 in PHP. I went through setup process and tried simple translation shown here and it worked. Then I wanted to test glossaries so I tried to add one as described here. When I'm trying to call the function:
protected function createGlossary()
{
$translationServiceClient = new TranslationServiceClient();
$projectId = 'my-project-id';
$glossaryId = 'my-new-glossary';
$inputUri = 'gs://bucket/file.csv';
$formattedParent = $translationServiceClient->locationName(
$projectId,
'us-central1'
);
$formattedName = $translationServiceClient->glossaryName(
$projectId,
'us-central1',
$glossaryId
);
$languageCodesElement = 'pl';
$languageCodesElement2 = 'en';
$languageCodes = [$languageCodesElement, $languageCodesElement2];
$languageCodesSet = new LanguageCodesSet();
$languageCodesSet->setLanguageCodes($languageCodes);
$gcsSource = (new GcsSource())
->setInputUri($inputUri);
$inputConfig = (new GlossaryInputConfig())
->setGcsSource($gcsSource);
$glossary = (new Glossary())
->setName($formattedName)
->setLanguageCodesSet($languageCodesSet)
->setInputConfig($inputConfig);
try {
$operationResponse = $translationServiceClient->createGlossary(
$formattedParent,
$glossary
);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$response = $operationResponse->getResult();
printf('Created Glossary.' . PHP_EOL);
printf('Glossary name: %s' . PHP_EOL, $response->getName());
printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
printf(
'Input URI: %s' . PHP_EOL,
$response->getInputConfig()
->getGcsSource()
->getInputUri()
);
} else {
$error = $operationResponse->getError();
// handleError($error)
}
} finally {
$translationServiceClient->close();
}
}
it returns an error:
Failed to build request, as the provided path (google.longrunning.Operations/GetOperation) was not found in the configuration.
It throws error at $operationResponse->pollUntilComplete();. The file in bucket contains just one line - test,test.
Then when I try to call function that lists all glossaries, it works but it doesn't return any.
What can cause this problem and how do I add glossary?
You need to install gRPC extension for PHP.
Info: https://cloud.google.com/php/grpc
Install gRPC for PHP
gRPC is a modern, open-source, high-performance remote procedure call framework. If you want to use PHP client libraries for gRPC-enabled APIs, you must install gRPC for PHP. This tutorial explains how to install and enable gRPC.
Install the gRPC extension for PHP.
sudo pecl install grpc
Enable the gRPC extension for PHP.
Add this line anywhere in your php.ini file, for example, /etc/php7/cli/php.ini. You can find this file by running php --ini.
extension=grpc.so

Wordpress PHP Fatal Error with Openshift

When I try to access the plugins or themes section of my wordpress site from the admin panel I am presented with a blank screen. When I run the logs I get the following error:
Navigating to wp-admin/plugins.php:
PHP Fatal error: Call to undefined function wp_json_encode() in /var/lib/openshift/{userID}/app-root/data/current/wp-includes/update.php on line 277
Navigating to wp-admin/themes.php:
PHP Fatal error: Call to undefined function wp_json_encode() in /var/lib/openshift/{userID}/app-root/data/current/wp-includes/update.php on line 440
Solutions online indicated that I should re-add the function, or re-install Wordpress. Without access to the core files, I downloaded a local repository of the application (but noticed it did not contain any of the plugins or themes I had uploaded via the admin interface).
I extracted a plugin and theme (placing them in the respective directories) then pushed the changes to production in the hopes that it would extract and re-install an updated version of wordpress. I then restarted the app.
The error still persists and I can not validate if the plugin or theme I uploaded were installed. Is there a way to refresh or reinstall a wordpress instance on Openshift?
I'm wondering how I can fix this issue without creating a new gear and migrating my data via the database. Note: Front end is working fine.
Version of Wordpress: 4.1.1
I ended up connecting to the app via SFTP and modified the file the following directly
/var/lib/openshift/{userID}/app-root/data/current/wp-includes/functions.php
and added the following function:
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
/*
* json_encode() has had extra params added over the years.
* $options was added in 5.3, and $depth in 5.5.
* We need to make sure we call it with the correct arguments.
*/
if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
$args = array( $data, $options, $depth );
} elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
$args = array( $data, $options );
} else {
$args = array( $data );
}
$json = call_user_func_array( 'json_encode', $args );
// If json_encode() was successful, no need to do more sanity checking.
// ... unless we're in an old version of PHP, and json_encode() returned
// a string containing 'null'. Then we need to do more sanity checking.
if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) {
return $json;
}
try {
$args[0] = _wp_json_sanity_check( $data, $depth );
} catch ( Exception $e ) {
return false;
}
return call_user_func_array( 'json_encode', $args );
}
Ref: https://wordpress.org/support/topic/fatal-error-call-to-undefined-function-wp_json_encode-in

Change sphinxapi.php and restart on Sphinx

I should change sphinxapi.php , my sphinxapi.php on (usr/local/sphinx/lib/sphinxapi.php) i changed it but what should i do after that to use new functions ?
my php :
<?php
$sphinx = new SphinxClient();
$sphinx->SetServer($this->config->sphinx->host, $this->config->sphinx->port);
$sphinx->SetMatchMode(SPH_MATCH_ALL);
$sphinx->SetLimits(0, 1,1);
..filters...
$sphinx->RemoveFilter($color['id']);
My new function :
function RemoveFilter ( $attribute )
{
assert ( is_string($attribute) );
foreach($this->_filters AS $key => $filter){
if($filter['attr'] == $attribute){
unset($this->_filters[$key]);
break;
}
}
}
Error :
Fatal error: Call to undefined method SphinxClient::RemoveFilter() in
At a guess, you've modified the one that comes with sphinx, but the application itself is using a different 'sphinxapi.php' - maybe a locally installed one.
Or even you have the sphinx extension installed, so its providing the SphinxClient not 'sphinxapi.php`'- if so uninstall the extension.

How to count number of instances in AWS PHP SDK2

Assume composer is installed and you need to setup an ec2 client.
Suppose SDK setup with recommended method using Composer. First call aws_setupthen create an ec2 client object with security credentials. Since composer has been invoked, it will automatically load required libraries.
Then use DescribeInstances to get all running instances.
I packaged the function countInstances so it can be reused. You can call DescribeInstances with
with an array to filter results which is posted at the end.
Setup as follows:
require('/PATH/TO/MY/COMPOSER/vendor/autoload.php');
function aws_setup()
{
$conf_aws = array();
$conf_aws['key'] = 'MYKEY';
$conf_aws['secret'] = 'MYSECRET';
$conf_aws['region'] = 'us-east-1';
return $conf_aws;
}
function countInstances($list)
{
$count = 0;
foreach($list['Reservations'] as $instances)
{
foreach($instances['Instances'] as $instance)
{
$count++;
}
}
return $count;
}
$config = aws_setup();
$ec2Client = \Aws\Ec2\Ec2Client::factory($config);
$list = $ec2Client->DescribeInstances();
echo "Number of running instances: " . countInstances($list);
If you want to filter your results try something like this as a parameter to DescribeInstances:
array('Filters' => array(array('Name' => 'tag-value', 'Values' => array('MY_INSTANCE_TAG'))));
The code executes without error, but I had to adapt it to post it here.
EDIT: Added list of instances to countInstances function. Otherwise it wouldn't be visible.

Empty resultset when using Phalcon\Mvc\Model\Query\Builder

Good day, eveyrone!
I'm trying to fetch data from Oracle database via Phalcon\Mvc\Model\Query\Builder, but resultset allways empty.
// APPLICATION_ROOT/app/models/Package.php
<?php
use Phalcon\MVC\Model;
class Package extends Model
{
public function getSource()
{
return 'RADIO_PACKAGE';
}
}
The controller class:
public function indexAction()
{
$packages = Package::find();
var_dump($packages->toArray()); // null
$query = $this->modelsManager->createBuilder()->from('Package')->getQuery();
var_dump($query->execute()->toArray()); // null
// But the direct access to database returns rows
$PDO = $this->getDI()->get('db')->getInternalHandler();
var_dump($PDO->query('SELECT * FROM RADIO_PACKAGE')->fetchAll()); // returns 23 rows
}
Does anyone know what the problem is?
I tried Phalcon 1.1.0 and 1.2.0.
PDO_OCI driver has been installed from PHP 5.4.16 source.
PHP version is 5.4.11.
Oracle version is "Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit"
Fixed in 1.2.0 branch, discussion about the problem: http://forum.phalconphp.com/discussion/464/empty-resultset-when-using-phalcon-mvc-model-query-builder
Do you have in public/index.php a setup for Loader ?
Something like
$loader = new \Phalcon\Loader();
$loader->registerDirs(
array(
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->pluginsDir
)
)->register();

Categories