PHP change language of current site - php

I am working on changing language without leaving current site for PHP. Here is the code I have come up so far, it works ok great only on home page, deeper i go the more links it displays.
function print_languages()
{
global $sipnati, $phrase;
$sql = $sipnati->db->query("
SELECT " . (MYSQL_QUERYCACHE ? "SQL_CACHE " : "") . "languageid, languagecode, title, canselect
FROM " . DB_PREFIX . "language
", 0, null, __FILE__, __LINE__);
$html = '';
while ($res = $sipnati->db->fetch_array($sql, DB_ASSOC))
{
$params = $_GET;
$params['lang'] = $res['languagecode'];
$qs = '?';
foreach($params as $k=>$v)
{
$qs .= $k.'='.urlencode($v).'&';
$html .= '<a class="flagi" href="' . substr($_SERVER['PHP_SELF'].$qs, 0, -1) . '"><img src="images/default/flag-' . $v . '.png" /></a>';
}
}
unset($res);
return $html;
}
Please help me out.

Before developing a multilanguage website, take attention to these elements:
For referencing your website, ONE page link must have ONE and ONLY ONE language.
e.g http://mydomain.com/mypage.php => Content in English OR another language but not both, even by autodetecting user language. Use http://fr.mydomain.com/mypage.php, http://mydomain.it/mypage.php or http://mydomain.com/en_US/mypage.php.
If you don't consider this help, you will kill your own SEO, making it blooding on the floor.
You can autodetect the user language with $_SERVER['HTTP_ACCEPT_LANGUAGE'].
e.g HTTP_ACCEPT_LANGUAGE => fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Seperate data by language (one version by language and only one version for each language on your website, avoid french contents on an english website).
You can use multiple tables (not recommended), multiple database (convenient but unsustainable), multiple rows (convenient but unsustainable) or one row with language reference (conceptually the best solution but it implies a lot of queries.)
For your question... (Yes i have an answer for you :D)
Do you save the selected language in a Session or a Cookie ?
I think we are missing a lot of informations:
Where you are saving the selected language.
"deeper i go the more links it displays." What are you meaning ?
What are you doing with $params = $_GET; $params['lang'] = $res['languagecode']; ...
What is the rest of your language system ?

Related

How to use Quick-books online Minor-version >= 4

I have done integration with Quick-Books online using quick-books sdk from this link: https://github.com/consolibyte/quickbooks-php.
Everything works perfectly except one issue.
The issue is, when I retrieve Items from quick-books, it returns "Non Inventory" items as "service".
I have read different topics which state that I will have to shift to minor version 4 to resolve the issue.
But I can't find a way of how I can make my current SDK to use minor version 4 or above.
Any help will be appreciated.
For those who have similar issue, I have found a workaround and sharing it for others to benefit if they want:
open the file quickbook_sdk\QuickBooks\IPP\Service.php
Find the following function protected function _query($Context, $realmID, $query)
Replace the following code
$return = $IPP->IDS($Context, $realmID, null, QuickBooks_IPP_IDS::OPTYPE_QUERY, urlencode($query));
With
$query = urlencode($query);
$query .= "&minorversion=4";
$return = $IPP->IDS($Context, $realmID, null, QuickBooks_IPP_IDS::OPTYPE_QUERY, $query);
Note: I was querying Items, so this workaround may only be beneficial in case of getting data through query.
UPDATE:
if you want to add / update items to QuickBooks online with item type NonInventory, You need to modify the following code in your quickbook_sdk/QuickBooks/IPP.php file.
Find function named function _IDS_v3 and inside that function find the following condition
if ($optype == QuickBooks_IPP_IDS::OPTYPE_ADD or $optype == QuickBooks_IPP_IDS::OPTYPE_MOD)
{
$post = true;
$url = $this->baseURL() . '/company/' . $realm . '/' . strtolower($resource);
$xml = $xml_or_query;
}
Replace it with
if ($optype == QuickBooks_IPP_IDS::OPTYPE_ADD or $optype == QuickBooks_IPP_IDS::OPTYPE_MOD)
{
$post = true;
$url = $this->baseURL() . '/company/' . $realm . '/' . strtolower($resource);
$xml = $xml_or_query;
$url .= "?minorversion=4"; // this is the only addition
}
For those who use the official php sdk from Intuit, in the root folder you'll find the file sdk.config. Edit <minorVersion>3</minorVersion>.
If you go to the official PHP SDK:
https://github.com/intuit/QuickBooks-V3-PHP-SDK
You will see that you can use:
$dataService->setMinorVersion("4");
to set the minor version you want to use before making the HTTP call.

Parsing closed brackets in URL and http_build_query with it inserts number in closed bracket

may not have explained this properly but here we go.
I have a URL that looks like http://www.test.co.uk/?page=2&area[]=thing&area[]=thing2
Multiple "area"s can be added or removed from the URL via links on the site. on each addition of n "area" I wanted to remove the "page" part of the URL. so it can be reset to page1. I used parse_url to take that bit out.
Then I built an http query so it could generate the URL properly without "page"
this resulted in "area%5B0%5D=" "area%5B1%5D=" instead of "area[]="
When I use urldecode, now it shows "area[0]=" and "area[1]="
I need it to be "[]" because when using a link to remove an area, it checks for the "[]=" - when it's [0] it doesn't recognise it. How do I keep it as "[]="?
See code below.
$currentURL = currentURL();
$parts = parse_url($currentURL);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
urldecode($currenturlfinal);
$currentURL = "?" . urldecode($currenturlfinal);
This is what I've done so far - it fixes the visual part in the URL - however I don't think I've solved anything as I've realised that what represents 'area' and 'thing' is not recognised as $key or $val as a result of what I think is parsing or reencoding the url in accordance with the code below. So I still can't remove 'areas' using the links
$currentURL_with_QS2 = currentURL();
$parts = parse_url($currentURL_with_QS2);
parse_str($parts['query'], $query);
unset($query['page']);
$currenturlfinal = http_build_query($query);
$currenturlfinal = preg_replace('/%5B[0-9]+%5D/simU', '[]', $currenturlfinal);
urldecode($currenturlfinal);
$currentURL_with_QS = "?" . $currenturlfinal;
$numQueries = count(explode('&', $_SERVER['QUERY_STRING']));
$get = $_GET;
if (activeCat($val)) { // if this category is already set
$searchString = $key . '[]= ' . $val; // we build the query string to remove
I'm using Wordpress as well may I add - maybe there's a way to reset the pagination through Wordpress. of course even then - when I go to page 2 on any page it still changes the "[]" to "5b0%5d" etc....
EDIT: this is all part of a function that refers to $key (the area/category) and $val (name of area or category) which is echoed in the link itself
EDIT2: It works now!
I don't know why but I had to use the original code and make the adjustments I did before again and now it works exactly how I want it to! Yet I couldn't see any visible differences in both codes afterwards. Strange...
As far as I know, there is no built-in way to do this.
You could try with:
$currenturlfinal = http_build_query($query);
Where $query is querystring part w/o area parameters and then:
foreach ($areas as $area) {
$currenturlfinal .= '&area[]='.$area;
}
UPD:
you could try with:
$query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
just place it right after http_build_query call.

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
");
}

Downloading a file, but sending a POST to initiate it

I have a button on a page with an onClick I dynamically set via Jquery.
That button starts the download of a file.
I'm using mod_rewrite to turn http://somesite.com/blah1/blah2/blah3/blah4 into index.php&q=$1
Then I access q, split on / and I get any user requested path as an array.
Works great except I can't send an encoded path as one of my variables:
<?php
$html = '<button onClick="window.location = \'' . SITE_URL . 'downloadLog/' . urlencode($some_path) . ">Click me</button>';
Looked into AllowEncodedSlashes On for Apache.
Tried it.. Always end up with either %2Fvar%2Fadm%2Fmessages even after urldecode() or rawurldecode(), or apache attempting to go somewhere that doesn't exist even with my mod_rewrite on / converting these to q=.
So.. the new idea is I'll just create a form onClick and submit that. POST will have no problem with my urlencoded path as a parameter.
Since this is destined to go in an onClick, and my onClick= uses double quotes (this is part of another huge piece of code I can't easily change right now) I'm having trouble getting the escaping correct I think. Broke down and didn't use quotes around my id/name as a last resort, still no dice.
So here is what I came up with. This does not error in firebug, but I don't see a POST happening either.
function get_inline_post($a) {
$output .= 'this_form = $(\'<form submit=' . SITE_URL . $a['submit'] . ' ></form>\').html(\'\')';
unset($a['submit']);
foreach ( $a as $key => $value ) {
$output .= '.append(\'<input id=' . $key . ' name=' . $key . ' type=hidden>\')';
}
$output .= ';';
foreach ($a as $key => $value ) {
$output .= '$(\'#' . $key . '\').val(\'' . rawurlencode($value) . '\');';
}
$output .= 'this_form.submit();';
return $output;
}
Which given the right variables ends up building this to go in my onClick:
<button class="ui-corner-all"
onClick="
this_form = $('<form submit=/downloadHostLog/messages></form>').html('').append('<input id=link_hcmdb_id name=link_hcmdb_id type=hidden >').append('<input id=added_path name=added_path type=hidden >');
$('#link_hcmdb_id').val('046345D4771C4D3FBD2EF33CBE038028');$('#added_path').val('var%2Fadm');this_form.submit();
"
title="Kill me now" type="button">
<span class="ui-icon ui-icon-copy"></span>
</button>
Remember,I'm trying to initiate a download here so answers with .post() are useless. Thank you.
Edit:
I'm open to using the original idea of just urlencoding it in the window.location script, but I've wasted all day on it already. Actually made a table and tried every variation of:
single urlencoding, double urlencoding encoding,Different levels of encoding going in versus coming out.
rawurlencode vs urlencode,
AllowEncodedSlashes On/Off
At this point I'm guessing that my combination of using mod_rewrite, splitting on / to generate the original query path as an array, and AllowEncodedSlashes just may not work together.
I'm also eliminating the fact that the buttons are sent to the user via ajax, and this button actually ends up in a jqgrid.
This is part of the reason I want to simply inline the onClick on generation instead of doing
$().click(function(){blah});
for every single result row as every row has 5 different parameters other than what I show here that are unique to every row for security purposes... so I end up calling the bind 50-500 times anyway which was painfully slow.
What I was doing previously was just generating a uid for each row, storing that in a session variable, and dereferencing it back when the user visited /downloadLog/UID. That worked as well, but I like to keep my session information under 4k for performance reasons and doing this took it to 16k easily.
Simply replacing / with | before encoding and changing it back after worked but I refused to resort to building in a bug like that.
EDIT: #dqhendricks My current mod_rewrite statement:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)? index.php?q=$1 [L,QSA]
The corresponding php that processes that:
foreach ( preg_split('/\//',$_GET['q']) as $key => $value)
{
$g[$key] = urldecode($value);
}
Given the above I tried AllowEncodedSlashes On and Off. Neither one allowed /blah/blah/%2F%var%2Fadmin/blah to be even directed into index.php. Got 404.
Don't quote me on this, but I believe frameworks like Zend just redirect everything to index.php (no GET request variables), then gets the request data from something like $_SERVER['ORIG_PATH_INFO']*. This gives you the request data prior to decoding the url. You can then split the request string, and decode each variable yourself.
*Unsure exactly, but something like this. Would have to look into Zend Framework's routing class to be sure.
EDIT
Dug up the code that gets the request uri from zend framework. Part of the Zend_Controller_Request_Http class, but you get the idea.
public function setRequestUri($requestUri = null)
{
if ($requestUri === null) {
if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
$requestUri = $_SERVER['HTTP_X_REWRITE_URL'];
} elseif (
// IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
isset($_SERVER['IIS_WasUrlRewritten'])
&& $_SERVER['IIS_WasUrlRewritten'] == '1'
&& isset($_SERVER['UNENCODED_URL'])
&& $_SERVER['UNENCODED_URL'] != ''
) {
$requestUri = $_SERVER['UNENCODED_URL'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$requestUri = $_SERVER['REQUEST_URI'];
// Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
$schemeAndHttpHost = $this->getScheme() . '://' . $this->getHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost));
}
} elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
$requestUri = $_SERVER['ORIG_PATH_INFO'];
if (!empty($_SERVER['QUERY_STRING'])) {
$requestUri .= '?' . $_SERVER['QUERY_STRING'];
}
} else {
return $this;
}
} elseif (!is_string($requestUri)) {
return $this;
} else {
// Set GET items, if available
if (false !== ($pos = strpos($requestUri, '?'))) {
// Get key => value pairs and set $_GET
$query = substr($requestUri, $pos + 1);
parse_str($query, $vars);
$this->setQuery($vars);
}
}
$this->_requestUri = $requestUri;
return $this;
}

Persistent HTTP GET variables in PHP

Let's say I have some code like this
if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz.
I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.
Here's one way....
//get passed params
//(you might do some sanitizing at this point)
$params=$_GET;
//morph the params with new values
$params['bar']='xyz';
//build new query string
$query='';
$sep='?';
foreach($params as $name=>$value)
{
$query.=$sep.$name.'='.urlencode($value);
$sep='&';
}
If you are updating the query string you need ot make sure you don't do something like
$qs="a=1&b=2";
$href="$qs&b=4";
$href contains "a=1&b=2&b=4"
What you really want to do is overwrite the current key if you need to .
You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bugged)
function getUpdateQS($key,$value)
{
foreach ($_GET as $k => $v)
{
if ($k != $key)
{
$qs .= "$k=".urlencode($v)."&"
}
else
{
$qs .= "$key=".urlencode($value)."&";
}
}
return $qs
}
View report
Just set the link that changes bar to xyz to also have foo=abc if foo is already set.
$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';
?>
Click Me
You would have to render out the links with the proper URL querystring to make that happen. This is a design decision that you would need to make on your end depending on how your system is setup.
I have some sites that have this issue, and what I do is setup a querystring global variable that sets the current page data the top of the page request.
Then when I am rendering the page, if I need to make use of the current query string I do something like:
echo '<a href="myurl.php' . querystring . '&bar=foo';
It's not the cleanest, but it all depends on how your system works.
Save some code and use the built-in http_build_query. I use this wrapper in one of my projects:
function to_query_string($array) {
if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here
else $query = http_build_query($array);
return '?'.$query;
}
Also, though it isn't often used, you can have $_GET on the left-hand side of an assignment:
$_GET['overriden_or_new'] = 'new_value';
echo 'Yeah!';
Other than that, just do what Paul Dixon said.

Categories