my problem is that when i tap rfid to scanner it appears on serial monitor Valet - Not found.
this is a picture when i tap the rfid card and an error appears on the arduino ide monitor serial :
Valet Not Found InSerial Monitor Arduino IDE
that's my code in arduino ide :
#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define SS_PIN D2
#define RST_PIN D1
MFRC522 mfrc522(SS_PIN, RST_PIN);
const char* ssid = "My WiFi";
const char* password = "My Password";
String content;
void setup() {
Serial.begin(115200);
SPI.begin();
mfrc522.PCD_Init();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting..");
}
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Please tag a card or keychain to see the UID !");
Serial.println("");
}
void loop () {
if (WiFi.status() == WL_CONNECTED) {
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
Serial.println();
Serial.print("UID tag :");
content = "";
byte letter;
for (byte i = 0; i <mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : ""));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
content.toUpperCase();
Serial.println();
kirim();
} else {
Serial.println("Error in WiFi connection");
}
}
void kirim()
{
HTTPClient http;
String ValueSend, postData;
ValueSend = String(content);
//Post Data
postData = "uid=" + ValueSend;
http.begin("http://that's my IP:80/web.php/UIDresult"); // :80 is port laravel, UIDresult is the url I created to point to the controller
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST(postData);
String payload = http.getString();
//Serial.println("uid=" + ValueSend);
if (httpCode > 0)
{
Serial.println(payload);
} else
{
Serial.print("Error on sending POST: ");
Serial.println(httpCode);
}
delay(2000);
http.end(); //Close connection
}
That's my code in controller laravel :
<?php
namespace App\Http\Controllers;
use App\Models\UidEntry;
use App\Http\Requests\StoreUidEntryRequest;
use App\Http\Requests\UpdateUidEntryRequest;
use Illuminate\Support\Facades\DB;
class UidEntryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('GetUID/datauid', [
"uidentry" => UidEntry::all()
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('register/index');
}
/**
* Store a newly created resource in storage.
*
* #param \App\Http\Requests\StoreUidEntryRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreUidEntryRequest $request)
{
$uid = $request->get("uid=");
$values = array('uid' => $uid);
DB::table('uid_entries')->insert($values);
// if (null !== $request->get('uid')) {
// $uid = $request->get('uid');
// dd($uid);
// $values = array('uid' => $uid);
// $result = DB::table('uid_entries')->insert($values);
// // return response($result);
// }
//validate form
// $this->validate($request, [
// 'uid' => 'required'
// ]);
// //upload image
// $entry = str($_POST['uid']);
// $image = $request->$entry;
// //create post
// UidEntry::create([
// 'uid' => $image
// ]);
// $validatedData = $request->validate([
// 'uid' => 'required'
// ]);
// UidEntry::create($validatedData);
}
/**
* Display the specified resource.
*
* #param \App\Models\UidEntry $uidEntry
* #return \Illuminate\Http\Response
*/
public function show(UidEntry $uidEntry)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\UidEntry $uidEntry
* #return \Illuminate\Http\Response
*/
public function edit(UidEntry $uidEntry)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \App\Http\Requests\UpdateUidEntryRequest $request
* #param \App\Models\UidEntry $uidEntry
* #return \Illuminate\Http\Response
*/
public function update(UpdateUidEntryRequest $request, UidEntry $uidEntry)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\UidEntry $uidEntry
* #return \Illuminate\Http\Response
*/
public function destroy(UidEntry $uidEntry)
{
//
}
}
That's my Model in laravel :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UidEntry extends Model
{
use HasFactory;
// protected $guarded = ['id'];
protected $fillable = [
'uid'
];
// bisa insert data di database tanpa colum updated_at
public $timestamps = false;
}
sorry if my english is bad.
tas déjà établie un lien api pour ce controller ?
comme ceci :
Route::post('/', [App\Http\Controllers\Controller::class, 'update']);
Related
After Message save broadcasting occurs this issue:
local.ERROR: {"userId":3,"exception":"[object] (Pusher\ApiErrorException(code: 0): at C:\xampp\htdocs\fm\script\vendor\pusher\pusher-php-server\src\Pusher.php:533)
[stacktrace]
#0 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Live\Webcast.php(51): Pusher\Pusher->trigger(Array, 'talk-send-messa...', Array)
nahid\talk\src\Live\Broadcast.php(85): Nahid\Talk\Live\Broadcast->dispatch(Object(Nahid\Talk\Live\Webcast))
#22 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Talk.php(106): Nahid\Talk\Live\Broadcast->transmission(Object(Nahid\Talk\Messages\Message))
#23 C:\xampp\htdocs\fm\script\vendor
nahid\talk\src\Talk.php(268): Nahid\Talk\Talk->makeMessage(2, Object(Nahid\Talk\Messages\Message))
Pages:
Webcast.php
class Webcast implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
/*
* Message Model Instance
*
* #var object
* */
protected $message;
/*
* Broadcast class instance
*
* #var object
* */
protected $broadcast;
/**
* Set message collections to the properties.
*/
public function __construct($message)
{
$this->message = $message;
}
/*
* Execute the job and broadcast to the pusher channels
*
* #param \Nahid\Talk\Live\Broadcast $broadcast
* #return void
*/
public function handle(Broadcast $broadcast)
{
$this->broadcast = $broadcast;
$senderIdKey = $this->broadcast->getConfig('user.ownerKey') ? $this->broadcast->getConfig('user.ownerKey') : 'id';
$toUser = ($this->message['sender'][ $senderIdKey] == $this->message['conversation']['user_one']) ? $this->message['conversation']['user_two'] : $this->message['conversation']['user_one'];
$channelForUser = $this->broadcast->getConfig('broadcast.app_name').'-user-'.$toUser;
$channelForConversation = $this->broadcast->getConfig('broadcast.app_name').'-conversation-'.$this->message['conversation_id'];
// try {
$this->broadcast->pusher->trigger([sha1($channelForUser), sha1($channelForConversation)], 'talk-send-message', $this->message);
// } catch (ApiErrorException $e) {
// throw new BroadcastException(
// sprintf('Pusher error: %s.', $e->getMessage())
// );
// }
}
}
Broadcast.php
class Broadcast
{
use DispatchesJobs;
/*
* Constant for talk config prefix
*
* #const string
* */
const CONFIG_PATH = 'talk';
/*
* Set all configs from talk configurations
*
* #var array
* */
protected $config;
/*
* Pusher instance
*
* #var object
* */
public $pusher;
/**
* Connect pusher and get all credentials from config.
*
* #param \Illuminate\Contracts\Config\Repository $config
*/
public function __construct(Repository $config)
{
$this->config = $config;
$this->pusher = $this->connectPusher();
}
/**
* Make pusher connection.
*
* #param array $options
*
* #return object | bool
*/
protected function connectPusher($options = [])
{
if ($this->getConfig('broadcast.enable')) {
$appId = $this->getConfig('broadcast.pusher.app_id');
$appKey = $this->getConfig('broadcast.pusher.app_key');
$appSecret = $this->getConfig('broadcast.pusher.app_secret');
$appOptions = $this->getConfig('broadcast.pusher.options');
$newOptions = array_merge($appOptions, $options);
$pusher = new Pusher($appKey, $appSecret, $appId, $newOptions);
return $pusher;
}
return false;
}
/**
* Dispatch the job to the queue.
*
* #param \Nahid\Talk\Messages\Message $message
*/
public function transmission(Message $message)
{
if (!$this->pusher) {
return false;
}
$sender = $message->sender->toArray();
$messageArray = $message->toArray();
$messageArray['sender'] = $sender;
$this->dispatch(new Webcast($messageArray));
}
/**
* get specific config from talk configurations.
*
* #param string
*
* #return string|array|int
*/
public function getConfig($name)
{
return $this->config->get(self::CONFIG_PATH.'.'.$name);
}
}
I don't try to install some themes and other extensions on magento 1.9 on my mec.
The error is:
community/HelloWired_Free_Theme_1_4: Unknown SSL protocol error in
connection to connect20.magentocommerce.com:443
Can you help me, please?
Thanks!
Try to use this code in downloader/lib/Mage/HTTP/Client/Curl.php
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Mage
* #package Mage_HTTP
* #copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Class to work with HTTP protocol using curl library
*
* #category Mage
* #package Mage_Connect
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_HTTP_Client_Curl implements Mage_HTTP_IClient
{
/**
* Session Cookie storage, magento_root/var directory used
* #var string
*/
const COOKIE_FILE = 'var/cookie';
/**
* Hostname
* #var string
*/
protected $_host = 'localhost';
/**
* Port
* #var int
*/
protected $_port = 80;
/**
* Stream resource
* #var object
*/
protected $_sock = null;
/**
* Request headers
* #var array
*/
protected $_headers = array();
/**
* Fields for POST method - hash
* #var array
*/
protected $_postFields = array();
/**
* Request cookies
* #var array
*/
protected $_cookies = array();
/**
* Response headers
* #var array
*/
protected $_responseHeaders = array();
/**
* Response body
* #var string
*/
protected $_responseBody = '';
/**
* Response status
* #var int
*/
protected $_responseStatus = 0;
/**
* Request timeout
* #var intunknown_type
*/
protected $_timeout = 300;
/**
* TODO
* #var int
*/
protected $_redirectCount = 0;
/**
* Curl
* #var object
*/
protected $_ch;
/**
* User ovverides options hash
* Are applied before curl_exec
*
* #var array();
*/
protected $_curlUserOptions = array();
/**
* User credentials
*
* #var array();
*/
protected $_auth = array();
/**
* Set request timeout, msec
*
* #param int $value
*/
public function setTimeout($value)
{
$this->_timeout = (int) $value;
}
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
* Removes temporary environment
*/
public function __destruct()
{
if (is_file(self::COOKIE_FILE)) {
#unlink(self::COOKIE_FILE);
}
}
/**
* Set headers from hash
* #param array $headers
*/
public function setHeaders($headers)
{
$this->_headers = $headers;
}
/**
* Add header
*
* #param $name name, ex. "Location"
* #param $value value ex. "http://google.com"
*/
public function addHeader($name, $value)
{
$this->_headers[$name] = $value;
}
/**
* Remove specified header
*
* #param string $name
*/
public function removeHeader($name)
{
unset($this->_headers[$name]);
}
/**
* Authorization: Basic header
* Login credentials support
*
* #param string $login username
* #param string $pass password
*/
public function setCredentials($login, $pass)
{
$this->_auth['login'] = $login;
$this->_auth['password'] = $pass;
//$val= base64_encode( "$login:$pass" );
//$this->addHeader( "Authorization", "Basic $val" );
}
/**
* Add cookie
*
* #param string $name
* #param string $value
*/
public function addCookie($name, $value)
{
$this->_cookies[$name] = $value;
}
/**
* Remove cookie
*
* #param string $name
*/
public function removeCookie($name)
{
unset($this->_cookies[$name]);
}
/**
* Set cookies array
*
* #param array $cookies
*/
public function setCookies($cookies)
{
$this->_cookies = $cookies;
}
/**
* Clear cookies
*/
public function removeCookies()
{
$this->setCookies(array());
}
/**
* Make GET request
*
* #param string $uri uri relative to host, ex. "/index.php"
*/
public function get($uri)
{
$this->makeRequest("GET", $uri);
}
/**
* Make POST request
* #see lib/Mage/HTTP/Mage_HTTP_Client#post($uri, $params)
*/
public function post($uri, $params)
{
$this->makeRequest("POST", $uri, $params);
}
/**
* Get response headers
*
* #return array
*/
public function getHeaders()
{
return $this->_responseHeaders;
}
/**
* Get response body
*
* #return string
*/
public function getBody()
{
return $this->_responseBody;
}
/**
* Get cookies response hash
*
* #return array
*/
public function getCookies()
{
if(empty($this->_responseHeaders['Set-Cookie'])) {
return array();
}
$out = array();
foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row);
$c = count($values);
if(!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if(is_null($val)) {
continue;
}
$out[trim($key)] = trim($val);
}
return $out;
}
/**
* Get cookies array with details
* (domain, expire time etc)
* #return array
*/
public function getCookiesFull()
{
if(empty($this->_responseHeaders['Set-Cookie'])) {
return array();
}
$out = array();
foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row);
$c = count($values);
if(!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if(is_null($val)) {
continue;
}
$out[trim($key)] = array('value'=>trim($val));
array_shift($values);
$c--;
if(!$c) {
continue;
}
for($i = 0; $i<$c; $i++) {
list($subkey, $val) = explode("=", $values[$i]);
$out[trim($key)][trim($subkey)] = trim($val);
}
}
return $out;
}
/**
* Get response status code
* #see lib/Mage/HTTP/Mage_HTTP_Client#getStatus()
*/
public function getStatus()
{
return $this->_responseStatus;
}
/**
* Make request
* #param string $method
* #param string $uri
* #param array $params
* #return null
*/
protected function makeRequest($method, $uri, $params = array())
{
static $isAuthorizationRequired = 0;
$this->_ch = curl_init();
// make request via secured layer
if ($isAuthorizationRequired && strpos($uri, 'https://') !== 0) {
$uri = str_replace('http://', '', $uri);
$uri = 'https://' . $uri;
}
$this->curlOption(CURLOPT_URL, $uri);
$this->curlOption(CURLOPT_SSL_VERIFYPEER, FALSE);
$this->curlOption(CURLOPT_SSL_VERIFYHOST, 2);
// force method to POST if secured
if ($isAuthorizationRequired) {
$method = 'POST';
}
if($method == 'POST') {
$this->curlOption(CURLOPT_POST, 1);
$postFields = is_array($params) ? $params : array();
if ($isAuthorizationRequired) {
$this->curlOption(CURLOPT_COOKIEJAR, self::COOKIE_FILE);
$this->curlOption(CURLOPT_COOKIEFILE, self::COOKIE_FILE);
$postFields = array_merge($postFields, $this->_auth);
}
if (!empty($postFields)) {
$this->curlOption(CURLOPT_POSTFIELDS, $postFields);
}
} elseif($method == "GET") {
$this->curlOption(CURLOPT_HTTPGET, 1);
} else {
$this->curlOption(CURLOPT_CUSTOMREQUEST, $method);
}
if(count($this->_headers)) {
$heads = array();
foreach($this->_headers as $k=>$v) {
$heads[] = $k.': '.$v;
}
$this->curlOption(CURLOPT_HTTPHEADER, $heads);
}
if(count($this->_cookies)) {
$cookies = array();
foreach($this->_cookies as $k=>$v) {
$cookies[] = "$k=$v";
}
$this->curlOption(CURLOPT_COOKIE, implode(";", $cookies));
}
if($this->_timeout) {
$this->curlOption(CURLOPT_TIMEOUT, $this->_timeout);
}
if($this->_port != 80) {
$this->curlOption(CURLOPT_PORT, $this->_port);
}
$this->curlOption(CURLOPT_RETURNTRANSFER, 1);
$this->curlOption(CURLOPT_FOLLOWLOCATION, 1);
$this->curlOption(CURLOPT_HEADERFUNCTION, array($this,'parseHeaders'));
if(count($this->_curlUserOptions)) {
foreach($this->_curlUserOptions as $k=>$v) {
$this->curlOption($k, $v);
}
}
$this->_responseHeaders = array();
$this->_responseBody = curl_exec($this->_ch);
$err = curl_errno($this->_ch);
if($err) {
$this->doError(curl_error($this->_ch));
}
if(!$this->getStatus()) {
return $this->doError("Invalid response headers returned from server.");
}
curl_close($this->_ch);
if (403 == $this->getStatus()) {
if (!$isAuthorizationRequired) {
$isAuthorizationRequired++;
$this->makeRequest($method, $uri, $params);
$isAuthorizationRequired=0;
} else {
return $this->doError(sprintf('Access denied for %s#%s', $_SESSION['auth']['login'], $uri));
}
}
}
/**
* Throw error excpetion
* #param $string
* #throws Exception
*/
public function isAuthorizationRequired()
{
if (isset($_SESSION['auth']['username']) && isset($_SESSION['auth']['password']) && !empty($_SESSION['auth']['username'])) {
return true;
}
return false;
}
/**
* Throw error excpetion
* #param $string
* #throws Exception
*/
public function doError($string)
{
throw new Exception($string);
}
/**
* Parse headers - CURL callback functin
*
* #param resource $ch curl handle, not needed
* #param string $data
* #return int
*/
protected function parseHeaders($ch, $data)
{
if(preg_match('/^HTTP\/[\d\.x]+ (\d+)/', $data, $m)) {
if (isset($m[1])) {
$this->_responseStatus = (int)$m[1];
}
} else {
$name = $value = '';
$out = explode(": ", trim($data), 2);
if(count($out) == 2) {
$name = $out[0];
$value = $out[1];
}
if(strlen($name)) {
if("Set-Cookie" == $name) {
if(!isset($this->_responseHeaders[$name])) {
$this->_responseHeaders[$name] = array();
}
$this->_responseHeaders[$name][] = $value;
} else {
$this->_responseHeaders[$name] = $value;
}
}
}
return strlen($data);
}
/**
* Set curl option directly
*
* #param string $name
* #param string $value
*/
protected function curlOption($name, $value)
{
curl_setopt($this->_ch, $name, $value);
}
/**
* Set curl options array directly
* #param array $array
*/
protected function curlOptions($array)
{
curl_setopt_array($this->_ch, $arr);
}
/**
* Set CURL options ovverides array *
*/
public function setOptions($arr)
{
$this->_curlUserOptions = $arr;
}
/**
* Set curl option
*/
public function setOption($name, $value)
{
$this->_curlUserOptions[$name] = $value;
}
}
Magento Plugin installation Error : Unknown SSL protocol error when trying to install magento plugin from magento connect.
Try to use this code in downloader/lib/Mage/HTTP/Client/Curl.php
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Mage
* #package Mage_HTTP
* #copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Class to work with HTTP protocol using curl library
*
* #category Mage
* #package Mage_Connect
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_HTTP_Client_Curl
implements Mage_HTTP_IClient
{
/**
* Session Cookie storage, magento_root/var directory used
* #var string
*/
const COOKIE_FILE = 'var/cookie';
/**
* Hostname
* #var string
*/
protected $_host = 'localhost';
/**
* Port
* #var int
*/
protected $_port = 80;
/**
* Stream resource
* #var object
*/
protected $_sock = null;
/**
* Request headers
* #var array
*/
protected $_headers = array();
/**
* Fields for POST method - hash
* #var array
*/
protected $_postFields = array();
/**
* Request cookies
* #var array
*/
protected $_cookies = array();
/**
* Response headers
* #var array
*/
protected $_responseHeaders = array();
/**
* Response body
* #var string
*/
protected $_responseBody = '';
/**
* Response status
* #var int
*/
protected $_responseStatus = 0;
/**
* Request timeout
* #var intunknown_type
*/
protected $_timeout = 300;
/**
* TODO
* #var int
*/
protected $_redirectCount = 0;
/**
* Curl
* #var object
*/
protected $_ch;
/**
* User ovverides options hash
* Are applied before curl_exec
*
* #var array();
*/
protected $_curlUserOptions = array();
/**
* User credentials
*
* #var array();
*/
protected $_auth = array();
/**
* Set request timeout, msec
*
* #param int $value
*/
public function setTimeout($value)
{
$this->_timeout = (int) $value;
}
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
* Removes temporary environment
*/
public function __destruct()
{
if (is_file(self::COOKIE_FILE)) {
#unlink(self::COOKIE_FILE);
}
}
/**
* Set headers from hash
* #param array $headers
*/
public function setHeaders($headers)
{
$this->_headers = $headers;
}
/**
* Add header
*
* #param $name name, ex. "Location"
* #param $value value ex. "http://google.com"
*/
public function addHeader($name, $value)
{
$this->_headers[$name] = $value;
}
/**
* Remove specified header
*
* #param string $name
*/
public function removeHeader($name)
{
unset($this->_headers[$name]);
}
/**
* Authorization: Basic header
* Login credentials support
*
* #param string $login username
* #param string $pass password
*/
public function setCredentials($login, $pass)
{
$this->_auth['login'] = $login;
$this->_auth['password'] = $pass;
//$val= base64_encode( "$login:$pass" );
//$this->addHeader( "Authorization", "Basic $val" );
}
/**
* Add cookie
*
* #param string $name
* #param string $value
*/
public function addCookie($name, $value)
{
$this->_cookies[$name] = $value;
}
/**
* Remove cookie
*
* #param string $name
*/
public function removeCookie($name)
{
unset($this->_cookies[$name]);
}
/**
* Set cookies array
*
* #param array $cookies
*/
public function setCookies($cookies)
{
$this->_cookies = $cookies;
}
/**
* Clear cookies
*/
public function removeCookies()
{
$this->setCookies(array());
}
/**
* Make GET request
*
* #param string $uri uri relative to host, ex. "/index.php"
*/
public function get($uri)
{
$this->makeRequest("GET", $uri);
}
/**
* Make POST request
* #see lib/Mage/HTTP/Mage_HTTP_Client#post($uri, $params)
*/
public function post($uri, $params)
{
$this->makeRequest("POST", $uri, $params);
}
/**
* Get response headers
*
* #return array
*/
public function getHeaders()
{
return $this->_responseHeaders;
}
/**
* Get response body
*
* #return string
*/
public function getBody()
{
return $this->_responseBody;
}
/**
* Get cookies response hash
*
* #return array
*/
public function getCookies()
{
if(empty($this->_responseHeaders['Set-Cookie'])) {
return array();
}
$out = array();
foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row);
$c = count($values);
if(!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if(is_null($val)) {
continue;
}
$out[trim($key)] = trim($val);
}
return $out;
}
/**
* Get cookies array with details
* (domain, expire time etc)
* #return array
*/
public function getCookiesFull()
{
if(empty($this->_responseHeaders['Set-Cookie'])) {
return array();
}
$out = array();
foreach( $this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row);
$c = count($values);
if(!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if(is_null($val)) {
continue;
}
$out[trim($key)] = array('value'=>trim($val));
array_shift($values);
$c--;
if(!$c) {
continue;
}
for($i = 0; $i<$c; $i++) {
list($subkey, $val) = explode("=", $values[$i]);
$out[trim($key)][trim($subkey)] = trim($val);
}
}
return $out;
}
/**
* Get response status code
* #see lib/Mage/HTTP/Mage_HTTP_Client#getStatus()
*/
public function getStatus()
{
return $this->_responseStatus;
}
/**
* Make request
* #param string $method
* #param string $uri
* #param array $params
* #return null
*/
protected function makeRequest($method, $uri, $params = array())
{
static $isAuthorizationRequired = 0;
$this->_ch = curl_init();
// make request via secured layer
if ($isAuthorizationRequired && strpos($uri, 'https://') !== 0) {
$uri = str_replace('http://', '', $uri);
$uri = 'https://' . $uri;
}
$this->curlOption(CURLOPT_URL, $uri);
$this->curlOption(CURLOPT_SSL_VERIFYPEER, FALSE);
$this->curlOption(CURLOPT_SSL_VERIFYHOST, 2);
// force method to POST if secured
if ($isAuthorizationRequired) {
$method = 'POST';
}
if($method == 'POST') {
$this->curlOption(CURLOPT_POST, 1);
$postFields = is_array($params) ? $params : array();
if ($isAuthorizationRequired) {
$this->curlOption(CURLOPT_COOKIEJAR, self::COOKIE_FILE);
$this->curlOption(CURLOPT_COOKIEFILE, self::COOKIE_FILE);
$postFields = array_merge($postFields, $this->_auth);
}
if (!empty($postFields)) {
$this->curlOption(CURLOPT_POSTFIELDS, $postFields);
}
} elseif($method == "GET") {
$this->curlOption(CURLOPT_HTTPGET, 1);
} else {
$this->curlOption(CURLOPT_CUSTOMREQUEST, $method);
}
if(count($this->_headers)) {
$heads = array();
foreach($this->_headers as $k=>$v) {
$heads[] = $k.': '.$v;
}
$this->curlOption(CURLOPT_HTTPHEADER, $heads);
}
if(count($this->_cookies)) {
$cookies = array();
foreach($this->_cookies as $k=>$v) {
$cookies[] = "$k=$v";
}
$this->curlOption(CURLOPT_COOKIE, implode(";", $cookies));
}
if($this->_timeout) {
$this->curlOption(CURLOPT_TIMEOUT, $this->_timeout);
}
if($this->_port != 80) {
$this->curlOption(CURLOPT_PORT, $this->_port);
}
$this->curlOption(CURLOPT_RETURNTRANSFER, 1);
$this->curlOption(CURLOPT_FOLLOWLOCATION, 1);
$this->curlOption(CURLOPT_HEADERFUNCTION, array($this,'parseHeaders'));
if(count($this->_curlUserOptions)) {
foreach($this->_curlUserOptions as $k=>$v) {
$this->curlOption($k, $v);
}
}
$this->_responseHeaders = array();
$this->_responseBody = curl_exec($this->_ch);
$err = curl_errno($this->_ch);
if($err) {
$this->doError(curl_error($this->_ch));
}
if(!$this->getStatus()) {
return $this->doError("Invalid response headers returned from server.");
}
curl_close($this->_ch);
if (403 == $this->getStatus()) {
if (!$isAuthorizationRequired) {
$isAuthorizationRequired++;
$this->makeRequest($method, $uri, $params);
$isAuthorizationRequired=0;
} else {
return $this->doError(sprintf('Access denied for %s#%s', $_SESSION['auth']['login'], $uri));
}
}
}
/**
* Throw error excpetion
* #param $string
* #throws Exception
*/
public function isAuthorizationRequired()
{
if (isset($_SESSION['auth']['username']) && isset($_SESSION['auth']['password']) && !empty($_SESSION['auth']['username'])) {
return true;
}
return false;
}
/**
* Throw error excpetion
* #param $string
* #throws Exception
*/
public function doError($string)
{
throw new Exception($string);
}
/**
* Parse headers - CURL callback functin
*
* #param resource $ch curl handle, not needed
* #param string $data
* #return int
*/
protected function parseHeaders($ch, $data)
{
if(preg_match('/^HTTP\/[\d\.x]+ (\d+)/', $data, $m)) {
if (isset($m[1])) {
$this->_responseStatus = (int)$m[1];
}
} else {
$name = $value = '';
$out = explode(": ", trim($data), 2);
if(count($out) == 2) {
$name = $out[0];
$value = $out[1];
}
if(strlen($name)) {
if("Set-Cookie" == $name) {
if(!isset($this->_responseHeaders[$name])) {
$this->_responseHeaders[$name] = array();
}
$this->_responseHeaders[$name][] = $value;
} else {
$this->_responseHeaders[$name] = $value;
}
}
}
return strlen($data);
}
/**
* Set curl option directly
*
* #param string $name
* #param string $value
*/
protected function curlOption($name, $value)
{
curl_setopt($this->_ch, $name, $value);
}
/**
* Set curl options array directly
* #param array $array
*/
protected function curlOptions($array)
{
curl_setopt_array($this->_ch, $arr);
}
/**
* Set CURL options ovverides array *
*/
public function setOptions($arr)
{
$this->_curlUserOptions = $arr;
}
/**
* Set curl option
*/
public function setOption($name, $value)
{
$this->_curlUserOptions[$name] = $value;
}
}
Source
I'm unable to get someone's user ID from their Kunena profile to open a new private message with the recipient name already inserted. The closest I got was the following code, which inserts my own username...
defined('_JEXEC') or die ();
class KunenaPrivateUddeIM extends KunenaPrivate
{
protected $uddeim = null;
protected $params = null;
/**
* #param $params
*/
public function __construct($params)
{
$this->params = $params;
if (!class_exists('uddeIMAPI'))
{
return;
}
$this->uddeim = new uddeIMAPI();
if ($this->uddeim->version() < 1)
{
return;
}
}
/**
* #param $userid
*
* #return string
*/
protected function getURL($userid)
{
static $itemid = false;
if ($itemid === false)
{
$itemid = 0;
if (method_exists($this->uddeim, 'getItemid'))
{
$itemid = $this->uddeim->getItemid();
}
if ($itemid)
{
$itemid = '&Itemid=' . (int) $itemid;
}
else
{
$itemid = '';
}
}
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . (int) $userid . $itemid);
}
/**
* #param $userid
*
* #return mixed
*/
public function getUnreadCount($userid)
{
return $this->uddeim->getInboxUnreadMessages($userid);
}
/**
* #param $text
*
* #return string
*/
public function getInboxLink($text)
{
if (!$text)
{
$text = JText::_('COM_KUNENA_PMS_INBOX');
}
return '' . $text . '';
}
/**
* #return string
*/
public function getInboxURL()
{
$user = JFactory::getUser($userid);
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . ($user ->id));
}
}
Change this line:
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . (JFactory::getUser()->id));
to the following 2 lines:
$user = JFactory::getUser($userid);
return JRoute::_('index.php?option=com_uddeim&task=new&recip=' . ($user ->id));
You can check this post that we have written some time ago (it was written for Joomla 2.5, but it still works, except that you have to remove the &) on how to retrieve non-cached users in Joomla: http://www.itoctopus.com/how-to-retrieve-the-non-cached-user-information-from-joomla
Ok kunena developer has a hotfix on github for the upcomming release update. Here is the commit link https://github.com/Kunena/Kunena-Forum/pull/3547
I need to replace my notifyService, with the event dispatcher of Symphony.
Here is the original service:
<?php
class VmService
{
/**
* #var VmManager|null
*/
protected $vmManager = null;
/**
* #var ProvisionerInterface[]
*/
protected $provisionners = array();
/**
* #var NotifyService|null
*/
protected $notifyService = null;
public function setVmManager(VmManager $vmManager)
{
$this->vmManager = $vmManager;
}
public function getVmManager()
{
return $this->vmManager;
}
/**
* #param $type
* #param ProvisionerInterface $provisionner
*/
public function setProvisionner($type, ProvisionerInterface $provisionner)
{
$this->provisionners[$type] = $provisionner;
}
/**
* #param $type
* #return ProvisionerInterface
*/
public function getProvisionner(Vm $vm)
{
return $this->provisionners[$vm->getType()];
}
/**
* #param NotifyService $notifyService
*/
public function setNotifyService(NotifyService $notifyService)
{
$this->notifyService = $notifyService;
}
/**
* #return NotifyService|null
*/
public function getNotifyService()
{
return $this->notifyService;
}
public function initialise(Vm $vm)
{
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->initialise($vm);
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
}
public function delete(Vm $vm, $force = false)
{
$now = new \DateTime();
$day = $now->format('w');
if ( ($day == 0 || $day == 6) && ! $force) {
throw new \Exception('Cannot delete a VM on weekend unless you force it');
}
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->delete($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
}
private function deleteLogFile(Vm $vm)
{
$filename = VmLogger::getLogFile($vm->getIdVm());
if (file_exists($filename)) {
#unlink("$filename");
}
}
public function prepare(Vm $vm)
{
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
//$provisionner->start($vm, true, 'integ.lafourchette.local');
$provisionner->stop($vm);
}
public function start(Vm $vm, $provisionEnable = true)
{
$vmManager = $this->getVmManager();
$notify = $this->getNotifyService();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(VM::STARTED);
$vmManager->flush($vm);
try {
$provisionner->start($vm, $provisionEnable);
$vm->setStatus(VM::RUNNING);
$vmManager->flush($vm);
$notify->send('ready', $vm);
} catch (UnableToStartException $e) {
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
$notify->send('unable_to_start', $vm);
throw $e;
}
}
public function getStatus(Vm $vm)
{
return $this->getProvisionner($vm)->getStatus($vm);
}
public function stop(Vm $vm)
{
$vmManager = $this->getVmManager();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
$provisionner->stop($vm);
}
public function archived(Vm $vm)
{
$vmManager = $this->getVmManager();
$this->delete($vm);
$vm->setStatus(VM::EXPIRED);
$this->deleteLogFile($vm);
$vmManager->flush($vm);
$this->prepare($vm);
}
}
And here is what I've changed:
<?php
class VmService
{
/**
* #var VmManager|null
*/
protected $vmManager = null;
/**
* #var ProvisionerInterface[]
*/
protected $provisionners = array();
/**
* #var NotifyService|null
*/
protected $notifyService = null;
public function setVmManager(VmManager $vmManager)
{
$this->vmManager = $vmManager;
}
public function getVmManager()
{
return $this->vmManager;
}
/**
* #param $type
* #param ProvisionerInterface $provisionner
*/
public function setProvisionner($type, ProvisionerInterface $provisionner)
{
$this->provisionners[$type] = $provisionner;
}
/**
* #param $type
* #return ProvisionerInterface
*/
public function getProvisionner(Vm $vm)
{
return $this->provisionners[$vm->getType()];
}
/**
* #param NotifyService $notifyService
*/
public function setNotifyService(NotifyService $notifyService)
{
$this->notifyService = $notifyService;
}
/**
* #return NotifyService|null
*/
public function getNotifyService()
{
return $this->notifyService;
}
public function initialise(Vm $vm)
{
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->initialise($vm);
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
}
public function delete(Vm $vm, $force = false)
{
$now = new \DateTime();
$day = $now->format('w');
if ( ($day == 0 || $day == 6) && ! $force) {
throw new \Exception('Cannot delete a VM on weekend unless you force it');
}
$vmManager = $this->getVmManager();
$provisioner = $this->getProvisionner($vm);
$provisioner->delete($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
}
private function deleteLogFile(Vm $vm)
{
$filename = VmLogger::getLogFile($vm->getIdVm());
if (file_exists($filename)) {
#unlink("$filename");
}
}
public function prepare(Vm $vm)
{
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
//$provisionner->start($vm, true, 'integ.lafourchette.local');
$provisionner->stop($vm);
}
public function start(Vm $vm, $provisionEnable = true)
{
$vmManager = $this->getVmManager();
$dispatcher = new EventDispatcher();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(VM::STARTED);
$vmManager->flush($vm);
try {
$provisionner->start($vm, $provisionEnable);
$vm->setStatus(VM::RUNNING);
$vmManager->flush($vm);
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
} catch (UnableToStartException $e) {
$vm->setStatus(VM::STOPPED);
$vmManager->flush($vm);
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
throw $e;
}
}
public function getStatus(Vm $vm)
{
return $this->getProvisionner($vm)->getStatus($vm);
}
public function stop(Vm $vm)
{
$vmManager = $this->getVmManager();
/**
* #var VM $vm
*/
$provisionner = $this->getProvisionner($vm);
$vm->setStatus(Vm::STOPPED);
$vmManager->flush($vm);
$provisionner->stop($vm);
}
public function archived(Vm $vm)
{
$vmManager = $this->getVmManager();
$this->delete($vm);
$vm->setStatus(VM::EXPIRED);
$this->deleteLogFile($vm);
$vmManager->flush($vm);
$this->prepare($vm);
}
}
However as I see with the documentation, I need a listener but I can't figure out how to relate it, and how to make it to work.
You need to refactor your code. As stated in the documentation, in order to dispatch an event, you have to create the event and call the dispatch method on the EventDispatcher instance, so in your code instead of what you are doing currently:
<?php
// this is the start method of your service
// ...
$event = new NotifyEvent($vm);
$dispatcher->addListener('notify.action', $event);
$dispatcher->dispatch('notify.action');
// ...
you have to create the event and dispatch it directly:
<?php
// this is the start method of your service
// ...
$event = new NotifyEvent($vm);
$dispatcher->dispatch('notify.action', $event);
// ...
You also are sending the same event ('notify.action') now but previously you had 2 different events: 'ready' and 'unable_to_start', so you have to create 2 listeners for 2 differents events ('notify.success' and 'notify.unable_to_start' for example).
Now you have 2 more problems:
No listeners are configured for your 'notify.action' event, so you have to add listeners somewhere (you've tried but you've failed, see the documentation for the EventDispatcher component for more details about how to properly configure a listener)
You're creating the dispatcher every time the start method is created, so you have to configure it every time also (configure means add the listeners)
You can tackle both if you refactor a little bit by creating another service based on the Symfony EventDispatcher:
<?php
// somewhere in your config file
// ...
$app['notifyService'] = $app->share(function() use ($app) {
$dispatcher = new Symfony\Component\EventDispatcher\EventDispatcher();
$dispatcher->addListener('notify.success', $callable1);
$dispatcher->addListener('notify.unable_to_start', $callable2);
return $dispatcher;
});
Notice that $callable1 and $callable2 are there to give you an idea, again check the documentation to see how to add listeners properly (you can create a clousure or a method in a class that handles the events, it's completely up to you).
Now you've defined a notifyService based on the Event Dispatcher (another one completely different from the EventDispatcher used by Silex so you have a clean Event Dispatcher for your domain events), you can use it as a notify service on your class. You'd do it like before: using the setNotifyService method and in your code you just need to create the event and call the dispatch method (assuming you've already called the setNotifyService):
<?php
// class VmService
// method start
// when you've to dispatch the success event
$event = new NotifySuccessEvent($vm);
$this->notifyService->dispatch('notify.success', $event);
// if you have to dispatch the notify.unable_to_start event
$event = new NotifyUnableToStartEvent($vm);
$this->notifyService->dispatch('notify.unable_to_start', $event);
I hope that this will put you on the right track.
PS: You'll have to code the 2 event classes by yourself, again, check the docs for details.