PHP Xml-RPC array and struct - php

I am using XML-RPC Lib for PHP to use online signature.
This is the official doc :
$doc = array(
"content" => new xmlrpcval($doc_content, "base64"),
"name" => new xmlrpcval($doc_name, "string")
);
$language = "fr";
$signers = array(new xmlrpcval($signer, "struct"));
$request = array(
"documents" => new xmlrpcval(array(new xmlrpcval($doc, "struct")), "array"),
...
But now I want to put several documents in the request. Here is my code :
$docs = array();
foreach ($documents as $document)
{
// Signature field
$field = array(
'page' => new xmlrpcval($document->page, 'int'),
'x' => new xmlrpcval($document->x, 'int'),
'y' => new xmlrpcval($document->y, 'int'),
'label' => new xmlrpcval($document->nom, 'string'),
);
// Document
$docs []= new xmlrpcval(array(
'content' => new xmlrpcval($document->content, 'base64'),
'name' => new xmlrpcval($document->nom, 'string'),
'signatureFields' => new xmlrpcval($field, 'array'),
),'struct');
}
$request = array(
'documents' => new xmlrpcval($docs, 'array'),
And I catch this error :
Message: Call to a member function serialize() on a non-object
Does someone allready used this library ? Cause I am lost right now..

I have come to realise that even if we have an array still for using the phpxmlrpc library, we need to define the array individually, so if one has to pass an array here is what can be done,
$listids // this was my one dimensional array
$subs_list_array = array();
foreach ($listids as $id) {
$subs_list_array[] = new xmlrpcval($id, "int");
}
$msg = new xmlrpcmsg(
"contact.subscribe", array(
//Set user id
new xmlrpcval($registration_id, "int"),
new xmlrpcval($subs_list_array, "array")// <- Now I am able to use the array
)
);

For recursive encoding of php arrays, you can also use the php_xmlrpc_encode function that will recursively convert arbitrarily deep data structures

Related

Prestashop WebService API - save in database HTML rich text

I am developing a php manager for prestashop via webservice. I have a module created to keep notes about orders.
From the management program I have a form with TinyMCE. But I can't save the text when it has HTML tags
webService class in prestashop module
class sellerNotas extends ObjectModel {
public $id;
public $id_seller;
public $nota;
public static $definition = array(
'table' => 'seller_notas',
'primary' => 'id',
'fields' => array(
'id' => array('type' => self::TYPE_INT),
'id_seller' => array('type' => self::TYPE_INT),
'nota' =>array('type' => self::TYPE_HTML, 'lang' => false, 'validate' => 'isCleanHtml'),
)
);
protected $webserviceParameters = array();
}
MySQL TABLE
I have no problem saving plain text without labels, the problem is when the text has labels.
I have tried htmlentities with no correct results.
create note php function
Please make sure you have used CDATA for that HTML node so it not get break due to any any component
$node = dom_import_simplexml($resources ->nota);
$no = $node -> ownerDocument;
$node -> appendChild($no -> createCDATASection($nota));
$resources ->nota= $nota;
SOLVED WITH htmlentities PHP CODE:
static function nuevaNota($idVendedor, $nota, $tienda) {
try{
$webService = webService::webServiceTienda($tienda);
$opt = [
'resource' => 'seller_notas?schema=blank'
];
$xml = $webService->get($opt);
$resources = $xml->seller_notas->children();
$resources->id_seller = intval($idVendedor);
$resources->nota = htmlentities($nota);
var_dump( $resources->nota);
$opt = [
'resource' => 'seller_notas',
'postXml' => $xml->asXML(),
];
$createdXml = $webService->add($opt);
}
catch (PrestaShopWebserviceException $e){
webService::controlErroresTienda($e, $tienda);
}
}

How to get collection class object from mongodb/driver/manager in PHP

I am using the (current? not sure, php documentation is very opaque to me) method to connect to a MongoDB from PHP:
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}#{$url}", array("ssl" => true), array("context" => $ctx));
From there, if I want to write something I do the following:
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
$filter,
['$set' => $value],
['multi' => false, 'upsert' => $upsert]
);
$results = $manager->executeBulkWrite("$DB.$collection", $bulk);
var_dump($results);
All the documentation on the MongoDB PHP tutorials starts with a $collection object... and the functions thereafter seem much more user-friendly (getInsertedID... insertOne...find...findOne...etc).
For example:
<?php
$collection = (new MongoDB\Client)->test->users;
$insertManyResult = $collection->insertMany([
[
'username' => 'admin',
'email' => 'admin#example.com',
'name' => 'Admin User',
],
[
'username' => 'test',
'email' => 'test#example.com',
'name' => 'Test User',
],
]);
printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
var_dump($insertManyResult->getInsertedIds());
It is not clear to me, how they are actually connecting to the DB... how would I go from the $manager connection to a $collection?
On the MongoDB PHP documentation page, it says 'You can construct collections directly using the driver’s MongoDB\Driver\Manager class'. Unfortunately, a search on the resulting page doesn't include the word 'collection' other than as a side comment in a user contributed note'
Elsewhere on the MongoDB PHP reference pages, I see nowhere that the MongoDB\Manager class is described.
So, how do I get access to the many features in the MongoDB\Collection class?
I was not able to get a collection out of the Manager class, however, I was able to use the bulkWrite class to execute an insert in a secure fashion (I believe). I expect the same pattern will work for reads and updates as well.
Code snippet for those that come here after me:
//echo "Specify the cert...";
$SSL_DIR = ".";
$SSL_FILE = "XXXXXX.pem";
$ctx = stream_context_create(array(
"ssl" => array(
"cafile" => $SSL_DIR . "/" . $SSL_FILE,
))
);
//echo "Done\n";
// echo "Creating manager...";
$manager = new MongoDB\Driver\Manager("mongodb://{$user}:{$pwd}#{$url}", array("ssl" => true), array("context" => $ctx));
// echo "Done!\n";
// echo "Making BSON...";
$bson = MongoDB\BSON\fromJSON($newData);
// echo "Done!\nMaking Value...";
$value = MongoDB\BSON\toPHP($bson);
$value->_id = (string) new MongoDB\BSON\ObjectID;
// echo "Done!\nMaking Bulk...";
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert($value);
// echo "Done!\nExecuting Bulk Write";
$results = $manager->executeBulkWrite("$db.$collection", $bulk);
if($results->getInsertedCount()==1) {
echo $value->_id;
} else {
echo $results->getWriteErrors();
}
// echo "Done!\n";

Facebook Ad API Error

I am getting error while creating Creative using the FB Ads PHP SDK
$parent_id as a parameter of constructor is being deprecated, please try not to use this in new code.
The code was working before the 2.9 and 2.10 update.
The Code I am using to create Creative is:
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'Product Description',
AdCreativeLinkDataFields::LINK => $url_of_website,
AdCreativeLinkDataFields::IMAGE_HASH => $image->hash,
AdCreativeLinkDataFields::DESCRIPTION => 'Link Description',
AdCreativeLinkDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LEARN_MORE,
'value' => array(
'link_title' => 'View Similar Products Now!',
'lead_gen_form_id' => $form_id,
),
),
));
$story = new AdCreativeObjectStorySpec();
$story->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => $page_id,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, $account_id);
$creative->setData(array(
AdCreativeFields::NAME => $nm,
AdCreativeFields::OBJECT_STORY_SPEC => $story,
AdCreativeFields::URL_TAGS => 'product=' . $p_id,
));
$creative->create();
I do not see any parent id in this statement. Please help
$parent_id is deprecated
The issue was reported on facebook github with issue# 314
Response from Facebook Developer
"We are depreciating creation with parent_id. We are seeing multiple endpoints that can create the same type of object. We do not have good ways to decide which one we should use if you are creating new object with parent_id. Moving forward, please instantiate the parent object with the parent_id and call create_XXX function to create the object you want."
Sample Code:
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;
$link_data = new AdCreativeLinkData();
$link_data->setData(array(
AdCreativeLinkDataFields::MESSAGE => 'try it out',
AdCreativeLinkDataFields::LINK => '<URL>',
AdCreativeLinkDataFields::IMAGE_HASH => '<IMAGE_HASH>',
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => <PAGE_ID>,
AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));
$creative = new AdCreative(null, 'act_<AD_ACCOUNT_ID>');
$creative->setData(array(
AdCreativeFields::NAME => 'Sample Creative',
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
$creative->create();
Hope this helps.
Use setParentId($parrent_id).
Sample code:
$product_catalog = new ProductCatalog();
$product_catalog->setParentId($parrent_id);
$product_catalog->setData(
[
ProductCatalogFields::NAME => "Testjon Autojon Catalog",
ProductCatalogFields::VERTICAL => "vehicles",
]
);
$product_catalog->create();
I found even though the accepted answer mentioned in here, which is the use of $parent_id is deprecated, the sample code shared there is still shows the old way of doing it.
In that example, the second argument passed to in AdCreative() is still the $parent_id.
$creative = new AdCreative(null, 'act_<AD_ACCOUNT_ID>');
For clarity mentioned below is the method signature of the constructor of \FacebookAds\Object\AbstractCrudObject which is what \FacebookAds\Object\AdCreative is extended from and, you'd see the deprecation notice there.
/**
* #deprecated deprecate constructor with null and parent_id
* #param string $id Optional (do not set for new objects)
* #param string $parent_id Optional, needed for creating new objects.
* #param Api $api The Api instance this object should use to make calls
*/
public function __construct($id = null, $parent_id = null, Api $api = null) {
parent::__construct();
//...
}
Said that as for the new approach, this is the way it should be done now :)
require __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
$access_token = '<ACCESS_TOKEN>';
$app_secret = '<APP_SECRET>';
$app_id = '<APP_ID>';
$id = '<AD_ACCOUNT_ID>';
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array();
$params = array(
'name' => 'Sample Creative',
'object_story_spec' => ['page_id' => '<pageID>',
'video_data' => ['IMAGE_URL' => '<imageURL>',
'video_id' => '<videoID>',
'call_to_action' => ['type' => 'LIKE_PAGE',
'value' => ['page' => '<pageID>']
]
]
],
);
$adCreative = (new AdAccount($id))->createAdCreative($fields, $params);
echo json_encode($adCreative->exportAllData(), JSON_PRETTY_PRINT);
I found this example here. Please note even though the title of this document is "Create an Ad Video Creative" it actually shows how to create the Ad creative. There are numerous inconsistencies in the Facebook Marketing API reference and this is such a case :)

Storing key value dictionary in Elgg

I am working on a plugin for Elgg that keeps track of device ids that are sent to the application when logging in from your mobile phone. For this, I would like to store these device ids in the database and would like to use ElggObjects for this.
This is what I do now:
function initialize() {
$androidTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'androidTokens',
'limit' => 0
));
$iosTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'iosTokens',
'limit' => 0
));
if ($androidTokens == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'androidTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
if ($iosTokens == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'iosTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
}
So this generates two ElggObjects that hold ids for android and for ios devices, stored in the metadata field tags. This array of tags can however not be retrieved anymore. When I do:
$tokenObject = elgg_get_entities(array(
'type' => 'object',
'subtype' => $os.'Tokens',
'limit' => 0
));
$tokens = $tokenObject->tags
tokens remains empty. Does someone know what I am doing wrong? Am I using the Elgg objects wrong?
I think the reason you're running into issues there is that elgg_get_entities returns an array of entities.
Am I correct in assuming that you'll only ever have one of each token object subtype? (One for iOS and one for Android?)
If so, I would modify your code as follows:
function initialize() {
$androidTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'androidTokens',
'limit' => 1 // only expecting one entity
));
$iosTokens = elgg_get_entities(array(
'type' => 'object',
'subtype' => 'iosTokens',
'limit' => 1 // only expecting one entity
));
if (count($androidTokens) == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'androidTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
if (count($iosTokens) == 0) {
$tokenObject = new ElggObject();
$tokenObject->subtype = 'iosTokens';
$tokenObject->tags = array();
$tokenObject->save();
}
}
Later, when grabbing the entity:
$tokenObject = elgg_get_entities(array(
'type' => 'object',
'subtype' => $os.'Tokens',
'limit' => 1 // only grab one
));
$tokens = $tokenObject[0]->tags; // get tag data for first (and only) entity

Curl Exception 7 PHP and Guzzle with Elasticsearch

I am trying to index documents using the php client for elastic search which uses Guzzle. After compiling my php script I am getting an error that says Internal Server Error, code 500. After doing some research this seems to be an issue with connecting to a server but the strange part is that everything I'm trying to do is set up on the same machine. My instance of Elasticsearch, my documents I'm trying to index, and my php scripts are all saved and running on the same machine. This is my PHP Script:
<?php
require '/home/aharmon/vendor/autoload.php';
$client = new Elasticsearch\Client();
$root = realpath('/home/aharmon/elkdata/for_elk_test_2014_11_24/Agencies');
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
$paths = array($root);
foreach ($iter as $path => $dir) {
if ($dir -> isDir()) {
$paths[] = $path;
}
}
//Create the index and mappings
$mapping['index'] = 'rvuehistoricaldocuments2009-2013'; //mapping code
$mapping['body'] = array (
'mappings' => array (
'documents' => array (
'_source' => array (
'enabled' => true
),
'properties' => array(
'doc_name' => array(
'type' => 'string',
'analyzer' => 'standard'
),
'description' => array(
'type' => 'string'
)
)
)
)
);
//Now index the documents
for ($i = 0; $i <= 10000; $i++) {
$params ['body'] [] = array(
'index' => array(
'_id' => $i
)
);
$params ['body'] [] = array(
'type' => 'documents',
'body' => array(
'foo' => 'bar'//Document body goes here
)
);
//Every 1000 documents stop and send the bulk request.
if($i % 1000) {
$responses = $client->bulk($params);
// erase the old bulk request
$params = array();
// unset the bulk response when you are done to save memory
unset($responses);
}
}
$client ->indices()->create($mapping)
?>
If anyone has seen this before or has an inclination as to what the issue the help would be greatly appreciated. I had a similar issue before when I tried to set up SSH but I got the firewall all configured and got SSH working so I'm not sure why this is happening.
check this link it is ok for me :
http://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_index_operations.html#_put_mappings_api
<?php
// Set the index and type
$params['index'] = 'my_index';
$params['type'] = 'my_type2';
// Adding a new type to an existing index
$myTypeMapping2 = array(
'_source' => array(
'enabled' => true
),
'properties' => array(
'first_name' => array(
'type' => 'string',
'analyzer' => 'standard'
),
'age' => array(
'type' => 'integer'
)
)
);
$params['body']['my_type2'] = $myTypeMapping2;
// Update the index mapping
$client->indices()->putMapping($params);

Categories