I'm currently struggling to add error handling for the following case. An error is raise when a $db database is trying to write into it when it has --read-only access. This causes the following error on WP Engine.
WordPress database error INSERT command denied to user 'readonly'#'xx.xxx.xx.xx' for table 'responses' for query INSERT INTO `responses`
I wan't for this error to not break the application so I'm trying to add error handling. However, when I raise an Exception is not being caught. I know that WP_ERROR are different, so how to I convert an WP_ERROR to an exception?
function drools_request($data, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
This is what I tried so far without success. Here I check for is_wp_error() if this condition is true I throw an exception. However, this did not work. I thought this is how one would go about handling a WP_ERROR, but I wonder if there is another way to handle this type of errors. Here is the full class:
<?php
namespace StatCollector;
function drools_request($data, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function drools_response($response, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("responses", [
"uid" => $uid,
"data" => json_encode($response),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function results_sent($type, $to, $uid, $url = null, $message = null) {
try {
$db = _get_db();
$insertion = $db->insert("messages", [
"uid" => $uid,
"msg_type" => strtolower($type),
"address" => $to,
"url" => $url,
"message" => $message
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function peu_data($staff, $client, $uid) {
try {
if (empty($uid)) {
return;
}
$db = _get_db();
if (! empty($staff)) {
$insertion = $db->insert("peu_staff", [
"uid" => $uid,
"data" => json_encode($staff)
]);
}
if( is_wp_error( $insertion ) ) {
throw new \Exception('Error writing to the database:');
}
if (! empty($client)) {
$insertion = $db->insert("peu_client", [
"uid" => $uid,
"data" => json_encode($client)
]);
}
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e){
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function response_update() {
$uid = $_POST['GUID'];
$url = $_POST['url'];
$programs = $_POST['programs'];
if (empty($uid) || empty($url) || empty($programs)) {
wp_send_json(["status" => "fail","message" => "missing values"]);
return wp_die();
}
try {
$db = _get_db();
$insertion = $db->insert("response_update", [
"uid" => $uid,
"url" => $url,
"program_codes" => $programs
]);
wp_send_json(["status" => "ok"]);
wp_die();
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database.');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
wpdb::insert does not return WP_Error on error. On error it returns boolean false. The error printing is done inside of wpdb::query itself, but you can disable that by setting suppress_errors to true, and then gracefully get the previous error with the last_error property.
$db->suppress_errors(true);
//Note: If you still want to log the errors to your server log
//use $db->hide_errors(); instead.
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( $insertion === false ) {
throw new \Exception('Error writing to the database: ' . $db->last_error);
}
Related
I am trying to send SMS through RingCentral. This is the error I am getting below.
Fatal error: Uncaught Exception: Response has unsuccessful status in /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Http/Client.php:39 Stack trace: #0 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(276): RingCentral\SDK\Http\Client->send(Object(GuzzleHttp\Psr7\Request)) #1 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(363): RingCentral\SDK\Platform\Platform->sendRequest(Object(GuzzleHttp\Psr7\Request), Array) #2 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Platform/Platform.php(183): RingCentral\SDK\Platform\Platform->requestToken('/restapi/oauth/...', Array) #3 /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/includes/ring-central.class.php(26): RingCentral\SDK\Platform\Platform->login(Array, '#Gc090486', '101') #4 /Applicati in /Applications/MAMP/htdocs/Paradise/wp-content/plugins/ring-central/vendor/ringcentral/ringcentral-php/src/Http/Client.php on line 50
<?php
use RingCentral\SDK\SDK;
define("FAILED", 1);
define("LOCKED", 2);
class RingCentralConnection {
private $_sdk;
private $_platform;
function __construct($clientId, $secret) {
}
//https://platform.ringcentral.com/restapi/v1.0/account/159048008/extension/171857008/call-log?dateFrom=2012-08-26
public function sendSMS($from, $to, $text) {
$_credentials = require (getPluginDir().'/includes/credentials.php');
$_sdk = new SDK($_credentials['appKey'], $_credentials['appSecret'], $_credentials['server'], '2FA Demo', '1.0.0');
//print_r($_sdk);
$_platform = $_sdk->platform();
try {
$_platform->login($_credentials['username'], $_credentials['extension'], $_credentials['password']);
// $code = generateRandomCode(6);
// $myNumber = $_credentials['username'];
// try {
// $response = $_platform->post('/account/~/extension/~/sms', array(
// 'from' => array('phoneNumber' => $myNumber),
// 'to' => array(array('phoneNumber' => $to)),
// 'text' => $message
// ));
// $status = $response->json()->messageStatus;
// echo $status;
// if ($status == "SendingFailed" || $status == "DeliveryFailed") {
// //$db->close();
// createResponse(new Response(FAILED, "RC server connection error. Please try again."));
// } else {
// //$timeStamp = time();
// //$query = "UPDATE users SET code= " . $code . ", codeexpiry= " . $timeStamp . " WHERE email='" . $email . "'";
// //$db->query($query);
// //$db->close();
// createResponse(new Response(LOCKED, $message));
// }
// } catch (ApiException $e) {
// //$db->close();
// $this->createResponse(new Response(FAILED, "RC server connection error. Please try again in."));
// }
} catch (ApiException $e) {
//$db->close();
//print_r($e);
$this->createResponse(new Response(FAILED, "RC server connection error. Please try again out."));
}
}
function createResponse($res) {
$response = json_encode($res);
echo $response;
}
function databaseError() {
$res = new Response(UNKNOWN, "Unknown database error. Please try again.");
$response = json_encode($res);
die($response);
}
}
class Response {
function __construct($error, $message) {
$this->error = $error;
$this->message = $message;
}
public $error;
public $message;
}
//credentials
return array(
'username' => '+13128589951',
'extension' => '101', // extension number
'password' => '',
'appKey' => '',
'appSecret' => '',
'server' => 'https://platform.devtest.ringcentral.com'// for production - https://platform.ringcentral.com
);
I am using php and mongodb. I want to use findandmodify. My field is { "_id" : ObjectId("58d37e612d4ffa498b99c2d4"), "userid" : "1234", "active_time" : "hai" }
I want to modify active_time. For example change the value "hai" to "1234"
I am using MongoDB\Driver\Manager.
try {
$mng = new MongoDB\Driver\Manager("mongodb://username:password#localhost:27017/db");
$userid = '1234';
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$command = new MongoDB\Driver\Command($retval);
$cursor = $manager->executeCommand('db.online', $command);
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
It shows the error is
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::findAndModify()
in line
$retval = $mng->findAndModify(
array("userid" => $userid), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
How it possible? please help me?
I got the answer. Change the findAndModify to update. The modified code is shown below.
$bulk->update(
array("userid" => '1234'), // searchQuery
array('$set' => array('active_time' => "kkk")) // UpdateQuery
);
$mng->executeBulkWrite("browser.online", $bulk);
if(!empty($mng)) {
echo "success";
} else {
echo "not";
}
I have a big numbers from Products in Magneto and i must add EAN Numbers to all the Products.
How could i update the new attribute from the CSV file through API.i want to update the EAN numbers from a ssh server through API SOAP.
This is not a full solution for you, but it is definitely a starting point for you. Good Luck
$productData = array(
'additional_attributes' => array(
'single_data' => array(
array(
'key' => 'ean',
'value' => 'value',
),
),
),
);
$productId = '1000000';
$soap = new SoapConnection('1','2','3');
echo $soap->_catalogProductUpdate($productId,$productData);
class SoapConnection
{
protected $soap_client;
protected $session_id;
function __construct($soap_host, $api_user, $api_pass)
{
try{
echo "Connecting to $soap_host\n";
$this->soap_client = new SoapClient( $soap_host, array('trace' =>true,
'connection_timeout' => 30,
'cache_wsdl' => WSDL_CACHE_NONE,
'keep_alive' => false
));
$this->session_id = $this->soap_client->login( $api_user, $api_pass);
echo "Connected with session id ".$this->session_id."\n";
return true;
} catch (SoapFault $e) {
echo "Soap Exception connecting to $soap_host: ". $e->getMessage(). "\n";
var_dump($this->soap_client->__getLastRequest()); var_dump($this->soap_client->__getLastResponse());
return false;
}
}
function _catalogProductUpdate($sku, $args)
{
try
{
return $this->soap_client->catalogProductUpdate($this->session_id, $sku, $args);
} catch (SoapFault $e) {
echo "Soap Exception _catalogProductUpdate: ". $e->getMessage(). "\n";
return false;
}
}
}
EDIT:
here is how to read a csv:
$file = fopen("my file path .csv","r");
while($row = fgetcsv($file))
{
$row[0];//column1
$row[1];//column2 etc etc etc
}
fclose($file);
Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.
I'm having a heck of a time trying to get the status of a uploaded video to YouTube. I've followed the bellow URL to setup a CRON job that would send videos to YouTube, get a response; preferably with the YouTube ID so I can save this in a database. Down side is I can not get this to work.
http://framework.zend.com/manual/1.12/en/zend.gdata.youtube.html
My Code: (Which is basically copy and past from the above URL)
function upload($filename, $options = array()) {
$default = array_merge(
array(
'username' => 'USERNAME',
'password' => 'PASSWORD',
'service' => 'youtube',
'client' => null,
'source' => 'YouTube Component',
'loginToken' => null,
'loginCaptcha' => null,
'authenticationURL' => 'https://www.google.com/accounts/ClientLogin',
'applicationId' => 'YouTube Component',
'clientId' => 'YouTube Component',
'developerKey' => 'DEVELOPERS-KEY',
'content_type' => 'video/quicktime',
'title' => null,
'description' => null,
'category' => null,
'tags' => null,
),
(array)$options
);
extract($default);
$this->controller->Zend->loadClass('Zend_Gdata_YouTube');
$this->controller->Zend->loadClass('Zend_Gdata_ClientLogin');
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username,
$password,
$service,
$client,
$source,
$loginToken,
$loginCaptcha,
$authenticationURL
);
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($filename);
$filesource->setContentType($content_type);
$filesource->setSlug($filename);
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle($title);
$myVideoEntry->setVideoDescription($description);
$myVideoEntry->setVideoCategory($category);
$myVideoEntry->SetVideoTags($tags);
$myVideoEntry->setVideoPrivate();
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
try {
$control = $myVideoEntry->getControl();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
if ($control instanceof Zend_Gdata_App_Extension_Control) {
if ($control->getDraft() != null && $control->getDraft()->getText() == 'yes') {
$state = $myVideoEntry->getVideoState();
if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
print 'Upload status: ' . $state->getName() .' '. $state->getText();
} else {
print 'Not able to retrieve the video status information' .' yet. ' . "Please try again shortly.\n";
}
}
}
}
The above works in every way, minus the fact that I always get "Not able to retrieve the video status information...". What am I doing wrong? I've been staring at this for hours so I imagine its something simple that I've missed.
I wasn't to terribly far off with completing this. The answer was to replace all of the return code with (customized a bit because I need a return value as this is a CakePHP component.):
$state = $newEntry->getVideoState();
if ($state) {
$response['id'] = $newEntry->getVideoId();
} else {
$response['error'] = "Not able to retrieve the video status information yet. " .
"Please try again later.\n";
}
return $response;