CakePHP Multiple emails from one field - cakephp

I'm pretty new to cakephp, I did the sample posts tutorial on the website and I'm now working on my first project.
Its pretty simple. The administrator pastes a list of emails and they become records in the database with a random password.
So, I want to register multiple emails by inputting em 'foo#bar.com; bar#foo.com; com#foo.bar' style in the same textbox. In the database they should become a record/email.
For one email my code is:
echo $this -> Form -> input('email');
echo $this -> Form -> input('code', array('default' => genRandomString()));
I also wan't to validate the adresses as emails later on. So could I use php's explode and then validate em on one way or another?
Greetings
Jeff

Cake itself has a neat method to explode them:
$emails = String::tokenize($emailList, ';');
( http://book.cakephp.org/2.0/en/core-utility-libraries/string.html#string )
yes, you can iterate over them and manually validating them one by one or putting them into an array saveAll() understands and use 'validate'=>'first' or 'only' with it.
( http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html#validating-data-from-the-controller )

Related

Yii2 - mailer - send message to email rows in database

Greetings,
i need to send email to several recipients that are stored in a table named mail which has a field called email.
In my controller i created an action that Query the table mail for the emails.
Later i tried to use the implode() function separated by comma, but obviously it didn't work because of mailer policies.
It generated the wrong format -> "email1#mail.com, email2#mail.com, email3#mail.com".
Tried also a for each loop and the serialize() function without success.
The json_encode() function is close to what i need, separate an array of emails to something like -> "email1#mail.com", "email2#mail.com", "email3#mail.com".
But it appends the field name before the value and it is not accepted by mailer policies.
So far i'm stuck with the following code:
public function actionSucesso()
{
$query = new Query;
$query->select('email')
->from('mail');
$command = $query->createCommand();
$enderecos = $command->queryAll();
$enviar = json_encode($enderecos);
Yii::$app->mailer->compose()
->setFrom('atf#website.com')
->setTo($enviar)
->setSubject('Oferta de jogo no site da ATF.')
->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
->send();
return $this->render('sucesso');
}
I think in order for the mailer to work and send the message the correct format needs to be: ->setTo("mail1#mail.com", "mail2#mail.com", "mail3#mail.com")
Is there a way of solving this problem?
Many thanks in advance.
To get array of email with numeric indexes call queryAll() method with $fetchMode parameter \PDO::FETCH_COLUMN, and then just pass returned array to mailer's setTo() method. Like this
$enderecos = $command->queryAll(\PDO::FETCH_COLUMN);
//$enviar = json_encode($enderecos); <- this line no needed
Yii::$app->mailer->compose()
->setFrom('atf#website.com')
->setTo($enderecos) //you pass an array of email addresses
->setSubject('Oferta de jogo no site da ATF.')
->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
->send();
See queryAll() documentation and list of pdo constant including available fetch modes starting with PDO::FETCH_. Also assuming you are using yii2 default mailer, look for swiftmailer documentation about how to set recipients

Different coding sets in database and website

I have a website with very simple news system (posting, editting, deleting etc). All my html pages are saved in UTF-8 formatting, everything displayes correctly.
I specify using UTF in every header:
For saving news to database, I use simple scripts like (all values come from a html form):
$newsTitel = isset($_POST['title']) ? $_POST['title'] : 'Untitled';
$submitDate = $date = date('Y/m/d');
$content = isset($_POST['newstext']) ? $_POST['newstext'] : 'No content';
include 'includes/dbconnect.php';
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("INSERT INTO news SET date='$submitDate',subject='$newsTitel',news='$content'");
The data get saved to database but in a weird format (coding). There are characters like à ¡ Ä etc which makes the content almost unreadable. Other problem is that when loading this content back to html forms (for editting news) it displays in this weird coding. When I looked into the specification of the database I use, it says that it saves data in UTF-8.
I use phpMyAdmin to access the MYSQL database.
So to sum it up:
Pages: saved in UTF8, all have correct header
Database: interaction with the server: utf8_czech_ci, tables in the same format
What I do not understand at all is this strange bevaior:
1) I save the data into the database using the script above
2) I take a look into phpMyAdmin and see broken encoding
3) I load the data back into my website and display them using this:
<?php
include 'includes/dbconnect.php';
$data = mysql_query("SELECT * FROM news ORDER BY id DESC limit 20") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
echo '<article><h3> '.$info['subject'].'</h3><div id="date">'.$info['date'].'</div>';
echo '<p>'.$info['news']. '</p></article>';
}
?>
The encoding is correct and no weird characters are displayed.
4) I load the exact same data into a html form (for edition purposes) and see the same broken encoding as in the database.
What happened? I really dont get it. I tried fixing this by re-saving everything in utf8, alterign tables and changing their encodings into different utf8 versions etc...
This is example of a data I pass to the database (it is in czech with html tags):
<p>Vařila myšička kašičku</p>
<img src="someImage.jpg">
<p>Další text</p>
Thanks for any help...
The commands for specifying the character set should be:
set names 'utf8';
If you check the result returned from your queries at the moment, what does it say? If I try it in the monitor I get the following:
mysql> set names 'UTF-8';
ERROR 1115 (42000): Unknown character set: 'UTF-8'
Have you tried using set names 'utf8' before connecting for the SELECT as well? The characters you're saying are output make me think you're getting back the correct bytes for UTF-8, but they're being interpreted as ISO-8859-1.
You are not escaping single quotes or some other html chars.
Use mysql_real_escape_string.
$newsTitel = isset($_POST['title']) ? mysql_real_escape_string($_POST['title']) : 'Untitled';

Creating Relation one - to - one Parse User

I state that Parse.com use for my app
Does anyone know what 's the right way to create a list of friends?
The user must be able to create a relationship with another user.
I tried to take a look at AnyPic but I could not follow. seems very complicated for me ... I know there is the possibility of creating a relationship with PFRelation but did not find much nl web
Can you help?
Thank's Rory
If you want to have both sides be able to see the friendship you have two options:
duplicate the relationship, i.e. a PFRelation on each PFUser
us a many-to-many table, i.e. a new Class with two PFUser references, and possibly other information
Given that you might want more information about the relationship (e.g. status=requested/accepted/rejected, etc), I would suggest option two.
Here's a similar question on managing friend requests and friend lists using Parse.
then, I had to make a query where I drew all the posts of my users (Timeline) and their names ... I had a problem (same as what I here to do this' you suggested) or call in a query of the Pointer ...
I solved so
This is the content of the cell
NSString *user = [[object objectForKey:#"Utente"] valueForKey:#"Nome_Cognome"];
cell.FFNomeLabel.frame=CGRectMake(15, -35, 270, 100);
cell.FFNomeLabel.textAlignment = NSTextAlignmentRight;
cell.FFNomeLabel.text = user;
[cell.BiancaView addSubview:cell.FFNomeLabel];
NSString *img = [[object objectForKey:#"Utente"] valueForKey:#"foto"];
cell.FFImmagineUtente.file = (PFFile *)img;
cell.FFImmagineUtente.frame = CGRectMake(10, 10, 70, 70);
[cell.FFImmagineUtente.layer setMasksToBounds:YES];
[cell.FFImmagineUtente.layer setCornerRadius:35.3f];
cell.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
[cell.FFImmagineUtente loadInBackground];
What do you think?
Also how can I save a pointer that is not a Current User?
I saw the documentation parse, but having little experience I was not entirely clear :)

Wordpress selecting wrong DB

I have a Wordpress site that uses two databases -- one section queries one database ("database_A"), and then Wordpress makes its connection to its own database ("database_B").
Everything it working well until I go to call this function:
$pageposts = $wpdb->get_results($querystr, OBJECT);
The Wordpress suddenly selects the wrong database ("database_A") when it was just using ("database_B").
How do I (a) prevent it from selecting ("database_A") or (b) make a call to have it select ("database_B")?
The wpdb class in WP ha a select() method. You should just be able to call it directly.
$wpdb->select('database_B');
You could also instantiate a second object that uses database_b:
$wpdb_b = new wpdb($db_b_user, $db_b_pwd, 'database_B', $db_b_host);
You can create a new $wpdb-var, like this:
<?php
$wpdb2 = new wpdb($user, $dbpassword, $db2, $dbhost);
?>
Now you can easily select items from the other database:
<?php
$pageposts = $wpdb2->get_results($querystr, OBJECT);
?>
I hope it helps you :]
(edit: Are you sure it suddenly changes the database? I mean, is it using database A before it is using database B, that's almost impossible...)

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I'm researching hours and hours, but I could not find any clear, efficient way to make it :/
I have a codeigniter base website in English and I have to add a Polish language now. What is the best way to make my site in 2 language depending visitor selection?
is there any way to create array files for each language and call them in view files depends on Session from lang selection? I don't wanna use database.
Appreciate helps! I'm running out of deadline :/ thanks!!
Have you seen CodeIgniter's Language library?
The Language Class provides functions
to retrieve language files and lines
of text for purposes of internationalization.
In your CodeIgniter system folder you'll
find one called language containing sets
of language files. You can create your
own language files as needed in order
to display error and other messages in
other languages.
Language files are typically stored in
your system/language directory. Alternately
you can create a folder called language
inside your application folder and store
them there. CodeIgniter will look first
in your application/language directory.
If the directory does not exist or the
specified language is not located there
CI will instead look in your global
system/language folder.
In your case...
you need to create a polish_lang.php and english_lang.php inside application/language/polish
then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
then load it in your controller like $this->lang->load('polish_lang', 'polish');
then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.
Repeat the steps for the english language and all other languages you need.
Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:
$this->session->set_userdata('language', ENGLISH);
Then you can grab it anytime like this:
$language = $this->session->userdata('language');
In the controller add following lines when you make the cunstructor
i.e, after
parent::Controller();
add below lines
$this->load->helper('lang_translate');
$this->lang->load('nl_site', 'nl'); // ('filename', 'directory')
create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers
function label($label, $obj)
{
$return = $obj->lang->line($label);
if($return)
echo $return;
else
echo $label;
}
for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under
system\application\languages
create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below
nl_site_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
en_site_lang.php
$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';
you can store multiple files for same language with differently as per the requirement
e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');
nl_admin_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
and finally
to print the label in desired language, access labels as below in view
label('welcome', $this);
OR
label('hello word', $this);
note the space in hello & word you can use it like this way as well :)
whene there is no lable defined in the language file, it will simply print it what you passed to the function label.
I second Randell's answer.
However, one could always integrate a GeoIP such as http://www.maxmind.com/app/php
or http://www.ipinfodb.com/. Then you can save the results with the codeigniter session class.
If you want to use the ipinfodb.com api You can add the ip2locationlite.class.php file to your codeigniter application library folder and then create a model function to do whatever geoip logic you need for your application, such as:
function geolocate()
{
$ipinfodb = new ipinfodb;
$ipinfodb->setKey('API KEY');
//Get errors and locations
$locations = $ipinfodb->getGeoLocation($this->input->ip_address());
$errors = $ipinfodb->getError();
//Set geolocation cookie
if(empty($errors))
{
foreach ($locations as $field => $val):
if($field === 'CountryCode')
{
$place = $val;
}
endforeach;
}
return $place;
}
For easier use CI have updated this so you can just use
$this->load->helper('language');
and to translate text
lang('language line');
and if you want to warp it inside label then use optional parameter
lang('language line', 'element id');
This will output
// becomes <label for="form_item_id">language_key</label>
For good reading
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
I've used Wiredesignz's MY_Language class with great success.
I've just published it on github, as I can't seem to find a trace of it anywhere.
https://github.com/meigwilym/CI_Language
My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.
When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.
You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.
String is totally free so please check it out and tell us what you think.
It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string
Follow this https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n
its simple and clear, also check out the document # http://ellislab.com/codeigniter/user-guide/libraries/language.html
its way simpler than
I am using such code in config.php:
$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
case 'ru':
$config['language'] = 'russian';
setlocale(LC_ALL,'ru_RU.UTF-8');
break;
case 'uk':
$config['language'] = 'ukrainian';
setlocale(LC_ALL,'uk_UA.UTF-8');
break;
case 'foo':
$config['language'] = 'foo';
setlocale(LC_ALL,'foo_FOO.UTF-8');
break;
default:
$config['language'] = 'english';
setlocale(LC_ALL,'en_US.UTF-8');
break;
}
.... and then i'm using usualy internal mechanizm of CI
o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.
So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application
you can make a function like this
function translateTo($language, $word) {
define('defaultLang','english');
if (isset($lang[$language][$word]) == FALSE)
return $lang[$language][$word];
else
return $lang[defaultLang][$word];
}
Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:
1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)
2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array
<?php /*
$lang = array (
'english' => 'English',
'arabic' => 'Arabic', // i add this here
'spanish' => 'Español'
Now save and run the application. It's worked fine.

Resources