Related
I'm using the data from telegrams received Webhook but I am faced with this error
Webhook tested properly set.
In your opinion, what is the problem?
This is my code:
Route :
Route::post('setwebhook','BotController#setWebhook');
Route::post('updates','BotController#updates');
BotController :
public function setWebhook()
{
$res = Telegram::setWebhook([
'url' => 'https://example.com/telegram-sdk/public/updates'
]);
return $res;
}
public function updates()
{
$update = Telegram::getWebhookUpdates();
$chat_id = $update->getMessage()->getChat()->getId();
$text = $update->getMessage()->getText();
$name = $update->getMessage()->getChat()->getFirstName();
if ($text == '/start') {
Telegram::sendMessage([
'chat_id' => $chat_id,
'text' => 'Hello World'
]);
}
}
I am trying to add Google Recaptcha to my custom SilverStripe form.
I have generated Google public and private keys but I do not know where to put them to show a captcha on my website.
Here is my current code:
ContactPage
class ContactPage extends Page
{
private static $db = array(
'TelCustomerSupport' => 'Varchar',
'TelProjectSupport' => 'Varchar',
'OfficeName' => 'Text',
'OfficeStreetAddress' => 'Text',
'OfficeAddressLocality' => 'Text',
'OfficePostalCode' => 'Varchar',
'OfficeMapLink' => 'Text',
'OfficeLatitude' => 'Text',
'OfficeLongitude' => 'Text',
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
// Add extra fields
$fields->addFieldToTab("Root.Main", new TextField('TelCustomerSupport', 'Phone - Customer, Trade & Retail Support'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('TelProjectSupport', 'Phone - Project Support'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeName'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeStreetAddress'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeAddressLocality'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficePostalCode'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeMapLink'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeLatitude'), "Content");
$fields->addFieldToTab("Root.Main", new TextField('OfficeLongitude'), "Content");
return $fields;
}
}
class ContactPage_Controller extends NetSuitePage_Controller
{
private static $allowed_actions = array('ContactForm');
// Generate the form
public function ContactForm()
{
// Create fields
$fields = new FieldList(
TextField::create("FirstName")->setTitle(_t('Contact.FIRSTNAME')),
TextField::create("LastName")->setTitle(_t('Contact.LASTNAME')),
EmailField::create("Email")->setTitle(_t('Contact.EMAILADDRESS')),
TextField::create("Phone")->setTitle(_t('Contact.PHONENUMBER')),
DropdownField::create('Iam', _t('Contact.IAMA'), $this->translateNetsuiteConfigArray('Contact', 'Iam')),
TextField::create("SendSubject")->setTitle(_t('Contact.SUBJECT')),
HoneyPotField::create("Subject2")->setTitle('Subject2'),
TextareaField::create("Message")->setTitle(_t('Contact.MESSAGE'))->setColumns(30)->setRows(10)
new RecaptchaField('MyCaptcha')
);
// Create actions
$submitbutton = new FormAction('doContactForm', _t('Contact.SEND'));
$submitbutton->addExtraClass('btn btn-black');
$actions = new FieldList(
$submitbutton
);
$validator = ZenValidator::create();
$validator->addRequiredFields(array('FirstName', 'LastName', 'Email', 'Phone', 'Iam', 'SendSubject', 'Message'));
$validator->setConstraint('FirstName', Constraint_length::create('max', 32));
$validator->setConstraint('LastName', Constraint_length::create('max', 32));
$validator->setConstraint('Phone', Constraint_length::create('min', 7));
$validator->setConstraint('Email', Constraint_type::create('email'));
$validator->setConstraint('Phone', Constraint_type::create('digits'));
$form = new Form($this, 'ContactForm', $fields, $actions, $validator);
$form->addExtraClass('contact-form');
$form->setFormMethod('POST', true);
return $form;
}
// Deal with form submission
public function doContactForm($data, $form)
{
$submission = new ContactFormSubmission();
$form->saveInto($submission);
$submission->write();
$data['path'] = print_r($this->refererTracker->retrieveAll(), true);
$email = new Email();
$email->setTemplate('ContactFormEmail');
$email->populateTemplate($data);
$email->setTo($this->getNetsuiteConfig('Contact', 'Emails'));
$email->setFrom("no-reply#warmup.co.uk");
$email->setSubject('[warmup.co.uk] New contact from the website');
$email->populateTemplate($data);
$email->send();
$post = $this->getNetsuiteConfig('Contact');
$post->firstname = $data['FirstName'];
$post->lastname = $data['LastName'];
$post->email = $data['Email'];
$post->phone = $data['Phone'];
$post->custentity116 = $data['Iam'];
$post->custentitysubject_contact_us = $data['SendSubject'];
$post->custentitymessage_contact_us = $data['Message'];
// Check for success
if ($this->queueNetSuitePost($post)) {
return $this->redirect(Director::get_current_page()->Link()."?success=1");
}
// Redirect back with form data and error message
Session::set('FormInfo.' . $form->FormName() . '.data', $data);
Session::set('FormInfo.'.$form->FormName().'.errors', array());
$form->sessionMessage("Netsuite error", 'bad');
return $this->redirectBack();
}
// Returns true if form submitted successfully
public function Success()
{
return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
}
public function getCurrentSubsite()
{
$subsite = Subsite::currentSubsite();
if($subsite) {
return $subsite->Title;
}
return $subsite;
}
}
ContactFormSubmission
class ContactFormSubmission extends DataObject {
private static $db = array(
'FirstName' => 'Text',
'LastName' => 'Text',
'Email' => 'Text',
'Phone' => 'Text',
'Iam' => 'Text',
'Subject' => 'Text',
'Message' => 'Text'
);
}
How do I correctly add Google Recaptcha to my form?
We can add Google Nocaptcha to our form using the SilverStripe Nocaptcha module.
The easiest way to install this module is through composer with the following command:
composer require undefinedoffset/silverstripe-nocaptcha
After installing the module be sure to call dev/build?flush=all.
Next we must set the spam protector to NocaptchaProtector through our site config.yml file, as well as set the Nocaptcha keys.
mysite/_config/config.yml
# ...
FormSpamProtectionExtension:
default_spam_protector: NocaptchaProtector
NocaptchaField:
site_key: "YOUR_SITE_KEY"
secret_key: "YOUR_SECRET_KEY"
The keys are retrieved through Google when setting up a new Nocaptcha account.
Make sure to call ?flush=all after adding these settings.
We are now ready to enable spam protection on our form. To do this we simply call $form->enableSpamProtection() in our form function:
public function ContactForm()
{
// Create fields
$fields = FieldList::create(
// ...
);
// Create actions
$actions = FieldList::create(
// ...
);
$validator = ZenValidator::create();
$form = Form::create($this, 'ContactForm', $fields, $actions, $validator);
$form->enableSpamProtection();
return $form;
}
Google Nocaptcha should now be enabled on our form.
Add
new LiteralField('recaptcha_bubble', '<div id="recaptcha_bubble" class="field"></div>')
in your forms field list
Then add the google javascript with
Requirements::javascript("https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=en-GB");
After that add the function to your javascript
var recaptchaCallback = function () {
var elementExists = document.getElementById('recaptcha_bubble');
if (null != elementExists) {
grecaptcha.render('recaptcha_bubble', {
'sitekey' : 'the site key here'
});
}};
When the form will be submitted with the variable 'g-recaptcha-response'
function getPostUrlContents($url, $fields){
$result = null;
$ch = curl_init();
$timeout = 30;
$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($fields_string, '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
public function checkGoogle_recaptcha_Response($code) {
$result = $this->getPostUrlContents(
'https://www.google.com/recaptcha/api/siteverify',
array(
'secret' => urlencode('secret key here'),
'response' => urlencode($code)
)
);
if (!$result) return false;
$gResult = json_decode($result, true);
if ($gResult['success']) {
return true;
}
return false;
}
public function yourForm(SS_HTTPRequest $request) {
$vars = $request->postVars();
if (!$this->checkGoogle_recaptcha_Response($vars['g-recaptcha-response'])) {
// throw error
} else {
//not a robot, do something with request
}
}
Tell me where I was wrong, everything is tried
my view file:
echo FileInput::widget([
'model' => $model,
'attribute' => 'files[]',
'options' => ['multiple' => true]
]);
Also i added
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
enctype option to form element
Model:
i add two variables as property:
public $files; // files instance
public $serialize; // set string which store the files
in rules
serialize as string, and files:
[['files'], 'file', 'skipOnEmpty' => true, 'extensions' => 'gif, jpg, png, pdf, doc, docx', 'maxFiles' => 10],
and controller action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$oldFiles = $model->serialize;
$files = UploadedFile::getInstance($model, 'files');
if($files === false){
$model->serialize = $oldFiles;
} else {
$serialize = [];
if($model->validate()){
foreach($files as $file){
$ext = end((explode(".", $file)));
$filename = Yii::$app->security->generateRandomString().".{$ext}";
$serialize[] = $filename;
$file->saveAs(Yii::$app->basePath . '/web/image/' . $filename);
}
} else {
}
//print_r($model->getErrors()); die();
$model->serialize = serialize($serialize);
}
$model->save();
return $this->redirect(['view', 'id' => $model->news_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
So, $files is empty, why?
also i get a "4" code error in $_FILES array
It should be getInstances for multiple files.
$files = UploadedFile::getInstances($model, 'files');
I am trying to use the Bing Translation API, but I am confused.
There seems to be much possibilities (old and new ones) but I don't understand what I have to do.
Can someone please help me?
I want to send a HTTP Request like http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=<AppId>&to=de&text=World and get the translation. Where to get the AppId?
What I have done so far:
Signed in for the free API useage (https://datamarket.azure.com/dataset/bing/microsofttranslator)
Created an App: https://datamarket.azure.com/developer/applications
Now I have the Client_ID and Client_Secret and also I have a account key (visible here https://datamarket.azure.com/account)
What to do now?
Thanks a lot or any help!
AppID is deprecated. How you need perform following steps:
Register you clientID, clientSecter in https://datamarket.azure.com
Then you code must getting access token for login BingTranslator API
Read more details instrustions on http://msdn.microsoft.com/en-us/library/dd576287.aspx
NB Microsoft Translator has been replaced by Bing Translate, which does not appear to have a readily-available API.
Follow the links on http://api.microsofttranslator.com. The API takes an access token in the appid parameter. See the section "Obtaining an access token" in the documentation to learn how to get that token.
Feel free to use this instructions (if you're using php):
Define your keys
$apis['azure']['id'] = 123456789
$apis['azure']['key'] = 'abcde123456';
Classes and functions
class AccessTokenAuthentication {
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
try {
$ch = curl_init();
$paramArr = array (
'grant_type' => $grantType,
'scope' => $scopeUrl,
'client_id' => $clientID,
'client_secret' => $clientSecret
);
$paramArr = http_build_query($paramArr);
curl_setopt($ch, CURLOPT_URL, $authUrl);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
if($curlErrno){
$curlError = curl_error($ch);
throw new Exception($curlError);
}
curl_close($ch);
$objResponse = json_decode($strResponse);
if($objResponse->error){
throw new Exception($objResponse->error_description);
}
return $objResponse->access_token;
} catch (Exception $e) {
echo "Exception-".$e->getMessage();
}
}
}
class HTTPTranslator {
function curlRequest($url, $authHeader, $postData=''){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
if($postData) {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$curlResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
curl_close($ch);
return $curlResponse;
}
function xmlLanguageCodes($languageCodes) {
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if(sizeof($languageCodes) > 0){
foreach($languageCodes as $codes) {
$requestXml .= "<string>$codes</string>";
}
} else {
throw new Exception('$languageCodes array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $requestXml;
}
function xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr) {
$requestXml = "<TranslateArrayRequest>".
"<AppId/>".
"<From>$fromLanguage</From>".
"<Options>" .
"<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>" .
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"</Options>" .
"<Texts>";
foreach ($inputStrArr as $inputStr) {
$requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">$inputStr</string>";
}
$requestXml .= "</Texts>".
"<To>$toLanguage</To>" .
"</TranslateArrayRequest>";
return $requestXml;
}
}
function get_language_names($locale="en") {
global $list, $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
foreach($list['translate'] as $k=>$iso) {
$languageCodes[] = $k;
}
$url = "http://api.microsofttranslator.com/V2/Http.svc/GetLanguageNames?locale=$locale";
$translatorObj = new HTTPTranslator();
$requestXml = $translatorObj->xmlLanguageCodes($languageCodes);
$curlResponse =$translatorObj->curlRequest($url, $authHeader, $requestXml);
$xmlObj = simplexml_load_string($curlResponse);
$i=0;
foreach($xmlObj->string as $language) {
$result[$languageCodes[$i]] = (string)$language;
$i++;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
function get_translate($array, $from, $to, $html=false) {
global $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
$fromLanguage = $from;
$toLanguage = $to;
$inputStrArr = array_values($array);
if($html) {
$contentType = 'text/html';
foreach($inputStrArr as $k=>$item) {
$inputStrArr[$k] = htmlentities($inputStrArr[$k]);
}
} else {
$contentType = 'text/plain';
}
$translatorObj = new HTTPTranslator();
$requestXml = $translatorObj->xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr);
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader, $requestXml);
$xmlObj = simplexml_load_string($curlResponse);
foreach($xmlObj->TranslateArrayResponse as $translatedArrObj){
$result[] = (string)$translatedArrObj->TranslatedText;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
function get_translate_single($input, $from, $to, $html=false) {
global $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
$fromLanguage = $from;
$toLanguage = $to;
if($html) {
$contentType = 'text/html';
$input = htmlentities($input);
} else {
$contentType = 'text/plain';
}
# params
$params = "text=".urlencode($input)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?".$params;
# object
$translatorObj = new HTTPTranslator();
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
# interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val){
$result = $val;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
The calls
echo get_translate_single('horse', 'en', 'es'); //this will print 'caballo'
or
echo get_translate(array('horse', 'house'), 'en', 'es'); //this will print array('caballo', 'casa')
That's it, have fun and remember to follow the terms of service.
I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.