extend larasap/fb post method - laravel

I'm trying to extend the functionality of a method from this package:
https://github.com/toolkito/laravel-social-auto-posting
Because the usage from mine controller is so simple, and others package makes a big mess even for basic operation like the one I need to achieve!
Goal: -posting text over a fb page with some tags of users that have allready puted a like to the same page.
So I Start from this call:
SendTo::Facebook(
‘link’,
[
‘link’ => ‘https://github.com/toolkito/laravel-social-auto-posting',
‘message’ => ‘Laravel social auto posting’
]
);
If I simply cut the link part, the message part can be my text of the post, and all works easy.
If I try to add user's tag on the 'message' part with the notation:
#[userId]
thats not works and the tag part is cutted and only the text is showed:
If I send 'text'=>'some text #[mineuserid] more text''
only
'some text more text'
is showed on the wall.
So I move to copy and extend the methods.
If I well understand from fb documentation I can tags user with the field tags but needs to be specified even the field places (in that case if I well understand my page's id)
So I start to explore into package, and trying to mods over sends link of the package:
public static function Facebook($type, $data)
{
switch ($type) {
case 'link':
$message = isset($data['message']) ? $data['message'] : '';
$result = FacebookApi::sendLink($data['link'], $data['message']);
break;
case 'postolo':
$message = isset($data['message']) ? $data['message'] :'';
$tags =isset($data['tags']) ? $data['tags'] : '';
$places =isset($data['places']) ? $data['places'] : '';
$result = FacebookApi::sendPostolo( $message, $tags,$places);
break;
Mine part is "postolo"
Then I found sendLink:
public static function sendLink($link, $message = '')
{
self::initialize();
$data = compact('link', 'message');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
If I foolishly copy this and adapts it to my needs is something like:
public static function sendPostolo($link, $message = '',$tags='',$places='')
{
self::initialize();
$data = compact( 'tags','message','places');
try {
$response = self::$fb->post('/me/feed', $data, self::$page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
throw new \Exception('Graph returned an error: '.$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
throw new \Exception('Facebook SDK returned an error: '.$e->getMessage());
}
$graphNode = $response->getGraphNode();
return $graphNode['id'];
}
But at the end the method $fb->post() not works as espect to me, and just publishs the first data of my array $data = compact( 'tags','message','places'); so in that case 'tags' and not as tags but predictably as plain text...
this is post() on fb package:
public function post($endpoint, array $params = [], $accessToken = null, $eTag = null, $graphVersion = null)
{
return $this->sendRequest(
'POST',
$endpoint,
$params,
$accessToken,
$eTag,
$graphVersion
);
}

Related

How to insert into couchDB in laravel

How to insert the records to couchDB in laravel. i have done the retrieval part but now I want to do insert, update and delete .
My retrieval code is below.
class couchdbcontroller extends Controller
{
public function getdata()
{
$content =null;
try {
$client = new Client();
$apiRequest = $client->request('GET','http://localhost:5984/user/_design/userdesign/_view/user-view?limit=20&reduce=false');
$code = $apiRequest->getBody()->getContents();
} catch (RequestException $re) {
//For handling exception
return $re->error;
}
return $code;
//return response()->json($code);
}
}
Inserting code below:
public function guzzle_insert_doc()
{
$client = new Client();
$res = $client->request('PUT', 'http://localhost:5984/login/new_doc',[
'uname' => 'admin',
'password' => 'admin123',
]);
//return $res;
}
Error: Client error: PUT http://localhost:5984/login/new_doc resulted in a 400 Bad Request response:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
From my google search, you could do something like this :
<?php
$client = new Client();
$doc = ['title'=>'This is a new doc'];
$res = $client->request('PUT', 'http://localhost:5984/db/new_doc',['json' => $doc]);
I assume you're using Guzzle (If I am wrong, tell us what your are using)
I didn't test my code since I don't have time to setup a laravel project with Guzzle. See documentation for further help.

Access information from session in website with two different sessions

My website has two restrict areas, in the public website and admin area. I've tried to follow some instructions to make multiple sessions throughout the website, but I'm facing some problems about accessing and retrieving their information.
Below are the login methods from both pages. First from the administration area:
public function login()
{
if ($this->Admin_model->find_credentials()) {
$data['user_email'] = $this->input->post('email');
$this->session->set_userdata('auto', $data);
redirect('/admin/dashboard', 'refresh');
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/admin/entrar');
}
}
And then, the admin area in the public website:
public function login()
{
if ($this->Usuarios_model->find_credentials()) {
$email = $this->input->post('email');
if ($this->Usuarios_model->is_active($email)) {
$data = array();
$data['nome'] = $this->Usuarios_model->find_col_by_email('nome_razao_social', $email);
$data['email'] = $email;
$data['tipo_usuario'] = $this->Usuarios_model->find_col_by_email('tipo_usuario', $email);
$data['id_usuario'] = $this->Usuarios_model->find_col_by_email('id', $email);
$this->session->set_userdata('auto', $data);
$this->session->set_flashdata('message', 'Bem-vindo!');
redirect('/usuario/painel');
} else {
$this->session->set_flashdata('message', 'Por favor, ative o seu cadastro');
redirect('/');
}
} else {
$this->session->set_flashdata('message', 'Desculpe, credenciais inválidas');
redirect('/');
}
}
For each new session, I am settling a name for it. Now, every point I call the session value, I must specify the name of which session I want, but I am having an error message after I try to log-in:
Message: Array to string conversion
This error points at line 161 of my model, which has the following code:
public function find_details($email = null, $id = null, $id_carro = null)
{
$this->db
->select(
'usuario.*,' .
'estado.nome_estado AS uf,' .
'cidade.nome_cidade AS cidade'
)
->join('cidade', 'cidade.id = usuario.id_cidade')
->join('estado', 'estado.id = usuario.id_estado');
if ($email) {$this->db->where('usuario.email', $email);} // 161
...
}
What do I need to do to make multiple sessions work correctly?
Alright. The solution for me was a different way to echo the value of a certain session:
$this->session->userdata('foo')['bar'].
Where foo is the session name, specified when creating a new session. In my case, a good example can be $this->session->userdata('auto')['email'];

How to change existing tag information in Magento

I am trying to update the popularity count of Magento's Tag module by interacting with this core function in Mage_Tag_Model_API
public function update($tagId, $data, $store)
{
$data = $this->_prepareDataForUpdate($data);
$storeId = $this->_getStoreId($store);
/** #var $tag Mage_Tag_Model_Tag */
$tag = Mage::getModel('tag/tag')->setStoreId($storeId)->setAddBasePopularity()->load($tagId);
if (!$tag->getId()) {
$this->_fault('tag_not_exists');
}
// store should be set for 'base_popularity' to be saved in Mage_Tag_Model_Resource_Tag::_afterSave()
$tag->setStore($storeId);
if (isset($data['base_popularity'])) {
$tag->setBasePopularity($data['base_popularity']);
}
if (isset($data['name'])) {
$tag->setName(trim($data['name']));
}
if (isset($data['status'])) {
// validate tag status
if (!in_array($data['status'], array(
$tag->getApprovedStatus(), $tag->getPendingStatus(), $tag->getDisabledStatus()))) {
$this->_fault('invalid_data');
}
$tag->setStatus($data['status']);
}
try {
$tag->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('save_error', $e->getMessage());
}
return true;
}
In my controller I have this :
public function clickAction()
{
$tagString = $this->getRequest()->getParam('tag');
$tagByName = Mage::getModel('tag/tag')->loadByName($tagString);
$tagId = $tagByName->getTagId();
$basePopularity = ['base_popularity' => '13']; // hard coding while testing
Mage::getModel('tag/api')->update($tagId, $basePopularity, 1);
}
If I put a log statement in this part of the update function :
try {
// log stuff
$tag->save();
}
I can see it makes it to that try but there is no change in the data. What did I screw up? Any other ideas on how I can update the popularity of a tag through a controller? Using this same method and adding 'name' => 'blah' to that $data array parameter works fine..
I also found in Mage_Tag_Model_Indexer_Summary.php this method defined in the PHPdoc * #method Mage_Tag_Model_Indexer_Summary setPopularity(int $value) Maybe that is what I need... can someone provide an example showing how I could use that magic setter?
Try adding Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); at the start of your clickAction function. base_popularity can only be updated from admin store.

Why I am getting error message when using Yii CActiveForm::validate() with array

I have a problem related to CActiveForm::validate(). I have a form and and sending data to database using Ajax, my form contains a multiple selectable drop-down list. In data saving section of controller produced the following error initially
mb_strlen() expects parameter 1 to be string, array given (.../framework/validators/CStringValidator.php:84)
and after updating framework to newer version, that error gone, and got the below validation message instead.
Category Ids is invalid.
If the form is fully filled(I mean all the rules in the model satisfied), it will not produce any such bug or error message.
controller action
public function actionCompany() {
$model = new Company;
if (isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$category_ids = "";
if (is_array($_POST['Company']['category_ids']))
$category_ids = implode(',', $_POST['Company']['category_ids']);
$model->category_ids = $category_ids;
if ($model->validate()) {
/*$temp = Company::model()->findByPK($model->id);
if ($temp !== null) {
$model = $temp;
}*/
$model->save();
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate($model);
if ($error != '[]')
echo $error;
}
}
}
Model rules
public function rules()
{
return array(
array('...., category_ids,...', 'required'),
array('..., category_ids, ...', 'length', 'max'=>255),
....
.....
array('...., category_ids,...', 'safe', 'on'=>'search'),
);
}
What is actually I'm missing?
By default, CActiveForm::validate($model) loads the model attributes from $_POST and overrides current attribute values, thus destroying your transformed values. Pass false as the third argument to avoid this.

Form validation with custom callback function

I created a "callback" function to check if the username exists in the DB.
I have multiple rules for the "username" field, but the only thing that work is my callback function. It refuses to check against the other rules. I tried leaving the field empty, and the "required" rule never kicked in.
Controller:
account.php
function register() {
$this->load->library('validation');
$fields['username'] = "trim|required|callback_username_check";
etc ...
etc ...
$this->validation->set_rules($fields);
if ($this->validation->run()) {
$records = array();
$records['username'] = $this->validation->username;
etc ...
etc ...
$data = $this->account_model->registerNewAccount($records);
}
$this->load->view('register_view');
}
function username_check($username) {
$m = new Mongo();
$collection = $m->selectDB( DBNAME )->selectCollection( TABLE );
$data = $collection->count(array("username" => $username) );
if($data == 1) {
$this->validation->set_message('username_check', '%s is already taken!');
return false;
} else {
return true;
}
}
Try using the new form_validation class here:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html
I believe there was a bug about it.

Resources