saving a field to upper case in drupal 6? - php

In drupal event creation I have a cck text field called person.How to force the person field to save(in db) in upper case only ?

Check out hook_nodeapi (http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_nodeapi/6)
You should be able to write a function in a module something that looks a little like this:
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == 'presave' && $node->type == 'event') {
$person = strtoupper($node->field_person[0]['value']);
$node->field_person[0]['value'] = $person;
}
}
Where it says event, just replace with your machine-friendly content type name, and where it says field_person, replace this with the machine name for your person field (probably field_person in your case.
If you wanna see if it works then put this in your the code before the end of the if statement (should be your CCK field all in uppercase..probably with a 1 after it, but just ignore that, it's just the die() :-))
die(print_r($person));

for drupal 7 that works :
function mymodule_node_presave($node) {
if ($node->type == ('article') {
$node->title = ucfirst($node->title);
}
}

Related

If last name exists else first name | Wordpress

I'm a completely newbie and trying around in wordpress atm.
I have this function to get first name:
function get_first_name () {
$user_data = get_userdata(get_current_user_id());
return $user_data->first_name;
}
to get the users first name (and display it somewhere afterwards). Now i want to work it like if the user has registered only with his first name it should only get the first name but if he also registered with lastname it should only (!) get last name and ignore the first name.
Can someone help me with this?
A simple ternary statement should do it for you
return $user_data->last_name != '' ? $user_data->last_name : $user_data->first_name;
It is like the longer IF
if ($user_data->last_name != '') {
return $user_data->last_name;
} else {
return $user_data->first_name;
}

Efficient way to make a (PHP) redirection functionality for multiple (128) database values

Currently I am working on a webpage where certain data from a database is being fetched and displayed to the user. This information is about certain project information and the lead partners of those projects. I want to implement a functionality where the user can click on a lead partner (link) and the link will redirect this user to another page (where the database information of all the organisations is on) BUT with a predefined search for only the organisations that are equal to the clicked lead partner link.
I found a solution on how to do this but the problem is that the solution (which i describe further below) isn't that good/efficient for multiple (128) organisations.. So the question is, do you know a better/more efficient solution to achieve this. To answer this question you probably also need some background information:
BACKGROUND INFORMATION
In the outputted database information (which is done in a table) there are several information columns/titles such as:
Project name
Organisations involved
Leader partner
Project website
And so on...
The fetching of the data is being done with a simple query where certain database columns have a specific identifier. For example, the project website columns is obviously a link, so in the query it is being done as follows: $SomeQueryVar = ("SELECT project_website as LINK FROM xxxx WHERE project_website ('$some_website') "); -- Just a short example to clarify things.
For the displaying, the data is being 'catched' like so:
if(count($SomeQueryVar)>0){
for($i=0;$i<count($SomeQueryVar);$i++){
echo "<tr>";
foreach($SomeQueryVar[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
if($key =='LINK' && $value != NULL){
$first = true;
array_filter($b);
foreach($b as $y){
echo ''."Project website".'';
$first = false;
if(!$first) break;
}
} else {
echo $value;
}
echo "</td>";
}
echo "</tr>";
}
}
As you can see in the above code, certain database columns need other displaying as the rest. For example, links must be clickable instead of just being plain text. These 'exceptions' are being catched with the if $key ==, for the data that just needs regular displaying (plain text) there is the last else inserted that just echo's the $value.
MY FOUND SOLUTION
So regarding the question, i found out that i can create redirection links using the ?SomePage on the projects page and using this 'added link value' on the organisations page to compare it. If the link is equal, then do the specific query. But it is probably easier to paste the code here:
The 'CATCHING' part
To catch a specific lead partner is also used an identifier in my query called ORG (which stands for organisation). So here is the code where i catch the organisations table:
if($key =='ORG' && $value != NULL){
$needle = array('Brainport','Development','BRAINPORT',
'brainport','DEVELOPMENT','development');
$needle2 = array('Casa','CASA', 'casa');
if (strpos_arr($value,$needle) !== false) {
echo '<a href="http://portal.e-ucare.eu/database/organisations/?a=brainport" >'.$value.'</a>';
}
if (strpos_arr($value,$needle2) !== false) {
echo '<a href="http://portal.e-ucare.eu/database/organisations/?a=casa" >'.$value.'</a>';
}
}
In the above code i just created it for 2 organisations (brainport and casa). For this solution i used a function called strpos_arr which searches for the needle in the haystack;) So in the code above i set the needles to the names in the database where it has to create a link for. So if for example a company with the word Brainport exists in the database, this 'catcher' will see this and display the organisation and make the name clickable.
The strpos_arr function for the $needle is as follows:
function strpos_arr($value, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($value, $what))!==false) return $pos;
}
return false;
}
In the redirection page the code will also catch certain links to make queries for that link -- so for the brainport link this is http://portal.e-ucare.eu/database/organisations/?a=brainport -- in the second page code this link is catched like so:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'portal.e-ucare.eu/database/organisations/?a=brainport')
{
$link_word = "Brainport";
$tmp = $wpdb->get_results("
SELECT
name_of_company__organization, company_location,
company_website as LINK, organisation_type,
organisation_active_in_, organisation_scope,
organisation_files as DOC
FROM
wp_participants_database
WHERE
name_of_company__organization REGEXP ('$link_word')
ORDER BY
name_of_company__organization ASC
");
}
With this solution i can do what i want, BUT like i said in the beginning, i need this for not just 2 organisations but 128!! This would mean i have to copy the catching code blocks on both pages 128 times!! This is obviously not very efficient..
So is there any more efficient way to achieve this? Sorry if it is a bit unclear but i found it quite hard to easily wright this down;)
Anyway, thank you in advance!
The firts part you can rewrite to
if($key =='ORG' && $value != NULL){
$needles = array(
'brainport'=>array('Brainport','Development','BRAINPORT','brainport','DEVELOPMENT','development'),
'casa'=>array('Casa','CASA', 'casa')
);
foreach($needles AS $nkey => $needle){
if(strpos_arr($value,$needle) !== false) {
echo "<a href='http://portal.e-ucare.eu/database/organisations/?a={$nkey}' >{$value}</a>";
}
}
}
For the second part make an array like
[EDIT]
$link_words = array(
'portal.e-ucare.eu/database/organisations/?a=brainport'=>'Brainport',
'portal.e-ucare.eu/database/organisations/?a=casa'=>'Casa',
);
then you can use
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(!empty($link_words[$host])){
$link_word = $link_words[$host];
$tmp = $wpdb->get_results("
SELECT
name_of_company__organization, company_location, company_website as LINK, organisation_type, organisation_active_in_, organisation_scope, organisation_files as DOC
FROM
wp_participants_database
WHERE
name_of_company__organization REGEXP ('$link_word')
ORDER BY
name_of_company__organization ASC
");
}

Store a user-input date string as datetime

I'm using php, and need to parse a date string formatted as dd/mm/yyyy and store it in MySql.
How can I convert the string to a datetime variable in a MySql table?
Probably the best way would be using this: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Or equivalent PHP functions like:
http://www.php.net/manual/en/function.date-parse-from-format.php (from PHP 5.3)
A generic PHP function would look like
function convertDate($dateString) {
return date('Y-m-d H:i:s',strtotime(str_replace('/','-',$dateString)));
}
or
function convertDate($dateString) {
$a = explode($dateString('/'));
return "{$a[2]}-{$a[1]}-{$a[0]} 00:00:00";
}
First of all you should store a configuration for the required format date, maybe something like this:
Knowing that the ISO_DATE FORMAT is "Y-m-d"
You must save the output configuration somehow, at least the separator.
If you know the separator and you know the format into which the date is entered than you can validate it using checkdate(), and also transform it into the ISO standard by exploding the values by the predefined separator.
I have a validation object that tells me if a field is of a certain type (String,Date,Datetime,Integer,Float) then formats the parameters sent to SQL :
as an example, let's say i get this array from my html form into PHP:
$_POST["DATA"] = array("name"=>"Koko bongo","age"=>12,"graduation_date"=>"12/06/1986");
and we define a validation array, like this:
$validator= array("name"=>"string","age"=>"integer","graduation_date"=>"date");
I have a configuration for each table which makes this automated but you can do it customly inplace by having an evalAndFormatType function that works like this
function evalAndFormatType($value,$type) {
switch strtolower($type) {
case "integer":
$item = is_numeric($value) && !strstr($value,DECIMAL_SEPARATOR) ? intval($item) :false;
break;
case "Date":/*we suppose that somehow we now the order, how you do it it is your decision: configuration array,constants etc*/
$check = explode(DATE_SEPARATOR,$value);
$item = sizeof($check) == 3 && checkdate(intval($check[1]),intval($check[0]),intval($check[2])) ? $check[2]."-".$check[1]."-".$check[0] : false;
break;
default:
throw Exception("Unknown type ".$type);
break;
}
return $item;
}
now, in your code you can say
$_DATA = $_POST["DATA"]; // the previously defined array
$errMsg = array();
foreach($_DATA as $k=>$v) {
$_DATA[$k] = evalAndFormat($v,$validator[$k]);
if($_DATA[$k] === false) {
$errMsg[$k] = "requires type ".$validator[$k];
}
}
if(empty($errMsg)){
$sql= ....WHATEVER USING THE INFO
} else {
return $errMsg;
/*this can be used to show errors nicely near your text boxes by parsing the expected keys or sending it by JSON etc
or
you could create a string out of it by using locale data that you might have which could output something like
Required fields: Graduation date[invalid type],Name,Age ... etc
"/
I hope this answers your question and also explains my "strange" approach on it.
}

Making of a shell

I'm working on a project where the admin panel is just a shell that do some actions depending on what string you input.
By shell i mean an input box where you type for example
delete user 1
and the user with id 1 is deleted.
I have planned this for about 4 months and i have written all the commands that the app could manage.
I have some problem to make this system. I was thinking about this solution:
$c = explode(' ', $input);
if ($c[0] == 'delete' and $c[1] == 'user' and count($c) === 3)
{
$c[2] = $id;
delete_user_by_id($id);
}
But i think it is not that well designed and i'm sure that it could be improved.
I noticed that exists regular expression and that they could be better than this but i can't really figure out how to use them in the previous example.
Any idea?
{Notice that a part of the string is variable (delete user VARIABLE)}
Instead of a bunch of if statements, you should create a class for each command, which takes the information as an argument and does something. You just need to load the class when it's called.
$command = 'delete user 1';
$parsed = explode($command, ' ', 2);
load_class($parsed[0]); // hypothetical loader
if (class_exists($parsed[0])) {
$class = new $parsed[0]();
$class->execute($parsed[1]);
} else {
die('Sorry, invalid command');
}
I think exploding on spaces is cleaner than using a regex.
You might be able to clean up the code a bit with a switch statement, and trimming the input before you explode it:
$c explode(' ', trim($input));
switch(strtolower($c)) {
case 'delete' :
delete_user_by_id($c[2]);
break;
case 'update' :
update_user_by_id($c[2]);
break;
...
default :
echo 'Invalid command: '.$c;
}

Need better structure of my code

this is my front controller
$pages = array("matches", "boards", "search", "articles", "interviews", "userlist", "teams", "servers", "awards", "gallery", "qids");
if (!$_SERVER['QUERY_STRING']) include('home_en.php');
elseif (isset($_GET['matchid'])) include('matchid.php');
elseif (isset($_GET['boardid'])) include('boardid.php');
elseif (isset($_GET['articleid'])) include('articleid.php');
elseif (isset($_GET['interviewid'])) include('interviewid.php');
elseif (isset($_GET['userid'])) include('profi.php');
elseif (isset($_GET['teamid'])) include('teamid.php');
elseif (isset($_GET['serverid'])) include('serverid.php');
elseif (isset($_GET['awardid'])) include('awardid.php');
elseif (isset($_GET['galleryid'])) include('galleryid.php');
elseif (isset($_GET['threadid'])) include('threadid.php');
elseif (isset($_GET['blogid'])) include('blogid.php');
..
elseif (in_array($_GET['content'], $pages)) include($_GET['content']);
else echo "File not found =(";
could i somehow add the identifiers to the array too? but i want the pages as index.php?matchid=9438 and for regular pages: index.php?content=matches
would really aprricate some ideas
thanks!
My Suggestion, From My Comment is this:
In order to check what type of id it is, you should use two $_GET parameters. One is the type (match, award, server, etc), one is the ID. That way you don't have to check for 500 different $_GET parameters, just the value of 2. Much more standardized.
Second, you want to make all of it under 1 file for the ID showing.
In the spirit of writing less code, not more, it would be relatively easy to change the SQL statement to grab the record based on if $_GET['type'] was match, award, team, etc. This is of course given that they will probably look the same. If they don't, instead of writing new code to grab each type, instead write code to display it differently
All Variables in this code much be validated/sanatized beforehand.
// First Get the Type
$type = $_GET['type'];
// Then the ID
$id = $_GET['id'];
// SANITIZE YOUR DATA. Replace this with your sanitization.
die("SANITIZE YOUR DATA HERE");
// Get Data Here
$sql = "SELECT * FROM table WHERE type=".$type." AND id=".$id;
$data = mysql_query($sql);
// Next, Include a template based on the data.
// Global the variable so it can be used in the file
Global $data;
include($type."-template.php");
I agree with Tom -- you should look into using a framework such as Zend, Cake, Symfony, Kohana, CodeIgniter, ez-Components, or Seagull. The advantage of using a framework is that they have already solved a lot of issues for you, including:
1) How to structure your code
2) How to interpret pretty urls (i.e. /x/1/y/2 instead of ?x=1&y=2)
3) Where to put certain types of code (html, php, configs, etc)
4) How to fix something you can't figure out (because these frameworks have communities)
and much much more...
That being said, maybe you don't want all the overhead of using a framework (it does require you to learn a lot). In that case, I recommend Rasmus Lerdorf's "No Framework PHP Framework". Rasmus is the creator of PHP, so you know he knows his stuff.
Lastly, to answer your actual question, here's how I would do it:
could i somehow add the identifiers to the array too?
i want the pages as index.php?matchid=9438
and for regular pages: index.php?content=matches
Sure, but yes, as Chacha102 said, you will need 2 parameters: $area (page) and $id.
Example: index.php?area=articles&id=2345
Then you can re-organize & simplify your 'front controller' this way:
/index.php
/areas/articles.php
/areas/boards.php
etc.
Instead of naming the templates articleid.php, just call it articles.php -- this way your area name also tells you which template to use.
$valid_areas = array("matches", "boards", "search", "articles",
"interviews", "userlist", "teams", "servers",
"awards", "gallery", "qids");
$area = strtolower(trim($_REQUEST['area'])); //if you are not posting any forms, use $_GET instead
$id = (int)$_REQUEST['id']; //if you are not posting any forms, use $_GET instead
if(!$id)
{
include('home_en.php');
}
if(!in_array($area), $valid_areas))
{
echo 'Sorry, the area you have requested does not exist: '.$area;
exit();
}
else
{
$template = '/templates/'.$area.'.php';
if(!file_exists($template))
{
echo 'Sorry, the file you have requested does not exist: '.$area.' '.$id);
}
else
{
include($template);
}
}
It might help to go ahead and use a framework such as Zend:
http://framework.zend.com/
You could do this:
<?php
$controllerDefault = 'home';
function sanitize($str)
{
return str_replace(array('.', '/', '\\'), '', $str);
}
//Prevent of Remote File Inclusion
$controller = sanitize($_GET['controller']);
$id = intval($_GET['id']);
if (empty($controller))
{
$controller = $controllerDefault;
}
if (!empty($id))
{
$controller .= 'id';
}
$controllerFile = $controller . '.php';
if (!file_exists($controllerFile)
|| $controller == 'index') //for not recursive index.php include :)
{
exit('Controller "'.$controllerFile.'" not exists');
}
include($controllerFile);
?>
Using this code you can use your application like:
http://yoursite.com/index.php //include('home.php')
http://yoursite.com/index.php?id=285230 //include('homeid.php')
http://yoursite.com/index.php?controller=matches //include('matches.php')
http://yoursite.com/index.php?controller=matches&id=28410 //include('matchesid.php')
http://yoursite.com/index.php?controller=notexists //ERROR! Controller "notexists" not exists
http://yoursite.com/index.php?controller=../../etc/passwd //ERROR! Controller "etcpasswd" not exists
I hope you like it
PD: the code is not tested, but I hope you catch my idea

Categories