accents at image names - php

In my php + javascript project i have to show images and some of then have accents,
like ~ ç and ^.
My site are not showing these images.
I know that there is a function to treat this, but i forgot.
Somebody can help me?
thank's

Try running the image URLs through rawurlencode().

/* (C)Scripterlative.com
* Strips grave, acute, circumflex umlaut and tilde from vowels and Ñ.
*
* Include this script block, then within the tag of each text element to be controlled, insert:
*
* onblur='this.value=stripVowelAccent(this.value)'
*
* GratuityWare
* ~~~~~~~~~~~~
* You obtained this script probably out of desperation, so if you wish to express your gratitude for our efforts,
* please visit: www.scripterlative.com
*
*/
function stripVowelAccent(str)
{
var rExps=[
{re:/[\xC0-\xC6]/g, ch:'A'},
{re:/[\xE0-\xE6]/g, ch:'a'},
{re:/[\xC8-\xCB]/g, ch:'E'},
{re:/[\xE8-\xEB]/g, ch:'e'},
{re:/[\xCC-\xCF]/g, ch:'I'},
{re:/[\xEC-\xEF]/g, ch:'i'},
{re:/[\xD2-\xD6]/g, ch:'O'},
{re:/[\xF2-\xF6]/g, ch:'o'},
{re:/[\xD9-\xDC]/g, ch:'U'},
{re:/[\xF9-\xFC]/g, ch:'u'},
{re:/[\xD1]/g, ch:'N'},
{re:/[\xF1]/g, ch:'n'} ];
for(var i=0, len=rExps.length; i<len; i++)
str=str.replace(rExps[i].re, rExps[i].ch);
return str;
}

Related

MSSQL + PHP - Error to insert oriental char

I'm having a problem to insert a oriental character with bind variables in SQL Server.
i'm using MSSQL commands and PHP.
My PHP code is like this:
$sql = "
CREATE TABLE table_test
( id int
,nvarchar_latin nvarchar(255) collate sql_latin1_general_cp1_ci_as
);";
$stmt = mssql_query($sql);
$conn = mssql_connect("server","user","pass");
mssql_select_db('test')
$stmt = mssql_init('test..sp_chinese', $conn);
$id = 1;
$nvarchar_latin = '重建議';
mssql_bind($stmt, '#id' , $id , SQLINT1);
mssql_bind($stmt, #nvarchar_latin, $nvarchar_latin, SQLVARCHAR);
mssql_execute($stmt);
My procedure is like this:
ALTER PROCEDURE sp_chinese
#id int
,#nvarchar_latin nvarchar (255)
AS
BEGIN
INSERT INTO char_chines (id, nvarchar_latin)
VALUES (#id, #nvarchar_latin);
END
this work if I change the oriental characters for normal one.
if I run directly this insert, it work's fine:
INSERT INTO table_test (id, nvarchar_latin)
VALUES (1, '重建議');
So, cleary the problem is when I send the variable from PHP to SQL Server.
Anyone have a clue how to make this works? some casting or something?
Thanks!
A solution that uses just the PHP (or even JavaScript) is to convert the character to its HEX value and store that. I don't know if you want to go this route but and I don't have time to show you the code but here is the full theory:
A non-English character is detected, like so: 重
Convert to HEX value (Look here for starters. But a search for Javascript will help you find better ways to do this even in PHP): 14af
NOTE: That is not what 重 really is in HEX
Store in a way that you can convert back to its original value. For example how can you tell what this is: 0d3114af is it 0d - 31 - 14 - af OR is it 0d31 - 14af. You can use deliminators like | or a . but one way is to provide padding of 00 in front. An English character would be only 2 characters long like 31 or af non-English will be 4 like 14af. Knowing this you can just split every 4 characters and convert to their values.
Downside is you will need to change your Database to accommodate these changes.
[ UPDATE ] -----
Here is some JavaScript code to send you off in the right direction. This is completely possible to replicate in PHP. This does not search for characters though, its part of an encryption program so all it cares about is turning everything into HEX. English characters will be padded with 00 (This is my own code hence no link to source):
function toHex(data) {
var result = '';
// Loop through entire string of data character by character
for(var i=0;i<data.length;i++) {
// Convert UTF-16 Character to HEX, if it is a 2 chracter HEX add 00 padding in front
result += (data.charCodeAt(i) + 0x10000).toString(16).slice(1);
}
// Display the result for testing purposes
document.getElementById('two').value = result;
}
function fromHex(data) {
var result = '', block = '', pattern = /(00)/; // Pattern is the padding
for(var i=0;i<data.length;i = i+4) {
// Split into separate HEX blocks
block = data.substring(i,i+4);
// Remove 00 from a HEX block that was only 2 characters long
if(pattern.test(block)){
block = block.substring(2,4);
}
// HEX to UTF-16 Character
result += String.fromCharCode(parseInt(block,16));
}
// Display the result for testing purposes
document.getElementById('two').value = result;
}

Remove Text In Front of IP

I'm trying to make a Skype resolver and I have an API for it already, now all my code is working and everything, but instead of just displaying their IP it displays some html code in front of it, for example: <h1><b>0.0.0.0</b></h1>, how would I remove the random text from the text box, also this resolver is made in Visual Basic! Here is the code I use to resolve if that helps:
Try
DownloadResponse = GetResponse.DownloadString("http://SKYPEAPIHERE.com/&name=" & TextBox7.Text)
FormatResponse = DownloadResponse.Split(New Char() {ControlChars.Lf}, StringSplitOptions.RemoveEmptyEntries)
TextBox8.Text = FormatResponse(0)
Dim sText() As String
sText = Split(TextBox8.Text, ":")
If sText(0) = "168.63.55.14" Then
TextBox8.Text = "IP Not Found"
ListBox1.Items.Add("SKYPE RESOLVER: IP Not Found")
Else
TextBox8.Text = sText(-2)
ListBox1.Items.Add("SKYPE RESOLVER: Resolved " + TextBox7.Text + " - " + TextBox8.Text)
End If
Catch ex As Exception
End Try
If anyone can help me with this, it would be greatly appreciated!
How about using a regex to match the IPv4 format?
Imports System.Text.RegularExpressions
Dim regex As Regex = New Regex("^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$")
Dim match As Match = regex.Match("<h1><b>0.0.0.0</b></h1>")
If match.Success Then
sText=match.Value
End If
Above is untested but hopefully points you in the right direction.
http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

How to find the nearest cities using web services? [duplicate]

Do you know some utility or a web site where I can give US city,state and radial distance in miles as input and it would return me all the cities within that radius?
Thanks!
Here is how I do it.
You can obtain a list of city, st, zip codes and their latitudes and longitudes.
(I can't recall off the top of my head where we got ours)
edit: http://geonames.usgs.gov/domestic/download_data.htm
like someone mentioned above would probably work.
Then you can write a method to calculate the min and max latitude and longitudes based on a radius, and query for all cities between those min and max. Then loop through and calculate the distance and remove any that are not in the radius
double latitude1 = Double.parseDouble(zipCodes.getLatitude().toString());
double longitude1 = Double.parseDouble(zipCodes.getLongitude().toString());
//Upper reaches of possible boundaries
double upperLatBound = latitude1 + Double.parseDouble(distance)/40.0;
double lowerLatBound = latitude1 - Double.parseDouble(distance)/40.0;
double upperLongBound = longitude1 + Double.parseDouble(distance)/40.0;
double lowerLongBound = longitude1 - Double.parseDouble(distance)/40.0;
//pull back possible matches
SimpleCriteria zipCriteria = new SimpleCriteria();
zipCriteria.isBetween(ZipCodesPeer.LONGITUDE, lowerLongBound, upperLongBound);
zipCriteria.isBetween(ZipCodesPeer.LATITUDE, lowerLatBound, upperLatBound);
List zipList = ZipCodesPeer.doSelect(zipCriteria);
ArrayList acceptList = new ArrayList();
if(zipList != null)
{
for(int i = 0; i < zipList.size(); i++)
{
ZipCodes tempZip = (ZipCodes)zipList.get(i);
double tempLat = new Double(tempZip.getLatitude().toString()).doubleValue();
double tempLon = new Double(tempZip.getLongitude().toString()).doubleValue();
double d = 3963.0 * Math.acos(Math.sin(latitude1 * Math.PI/180) * Math.sin(tempLat * Math.PI/180) + Math.cos(latitude1 * Math.PI/180) * Math.cos(tempLat * Math.PI/180) * Math.cos(tempLon*Math.PI/180 -longitude1 * Math.PI/180));
if(d < Double.parseDouble(distance))
{
acceptList.add(((ZipCodes)zipList.get(i)).getZipCd());
}
}
}
There's an excerpt of my code, hopefully you can see what's happening. I start out with one ZipCodes( a table in my DB), then I pull back possible matches, and finally I weed out those who are not in the radius.
Oracle, PostGIS, mysql with GIS extensions, sqlite with GIS extensions all support this kind of queries.
If you don't have the dataset look at:
http://www.geonames.org/
Take a look at this web service advertised on xmethods.net. It requires a subscription to actually use, but claims to do what you need.
The advertised method in question's description:
GetPlacesWithin Returns a list of geo
places within a specified distance
from a given place. Parameters: place
- place name (65 char max), state - 2 letter state code (not required for
zip codes), distance - distance in
miles, placeTypeToFind - type of place
to look for: ZipCode or City
(including any villages, towns, etc).
http://xmethods.net/ve2/ViewListing.po?key=uuid:5428B3DD-C7C6-E1A8-87D6-461729AF02C0
You can obtain a pretty good database of geolocated cities/placenames from http://geonames.usgs.gov - find an appropriate database dump, import it into your DB, and performing the kind of query your need is pretty straightforward, particularly if your DBMS supports some kind of spatial queries (e.g. like Oracle Spatial, MySQL Spatial Extensions, PostGIS or SQLServer 2008)
See also: how to do location based search
I do not have a website, but we have implemented this both in Oracle as a database function and in SAS as a statistics macro. It only requires a database with all cities and their lat and long.
Maybe this can help. The project is configured in kilometers though. You can modify these in CityDAO.java
public List<City> findCityInRange(GeoPoint geoPoint, double distance) {
List<City> cities = new ArrayList<City>();
QueryBuilder queryBuilder = geoDistanceQuery("geoPoint")
.point(geoPoint.getLat(), geoPoint.getLon())
//.distance(distance, DistanceUnit.KILOMETERS) original
.distance(distance, DistanceUnit.MILES)
.optimizeBbox("memory")
.geoDistance(GeoDistance.ARC);
SearchRequestBuilder builder = esClient.getClient()
.prepareSearch(INDEX)
.setTypes("city")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setScroll(new TimeValue(60000))
.setSize(100).setExplain(true)
.setPostFilter(queryBuilder)
.addSort(SortBuilders.geoDistanceSort("geoPoint")
.order(SortOrder.ASC)
.point(geoPoint.getLat(), geoPoint.getLon())
//.unit(DistanceUnit.KILOMETERS)); Original
.unit(DistanceUnit.MILES));
SearchResponse response = builder
.execute()
.actionGet();
SearchHit[] hits = response.getHits().getHits();
scroll:
while (true) {
for (SearchHit hit : hits) {
Map<String, Object> result = hit.getSource();
cities.add(mapper.convertValue(result, City.class));
}
response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
if (response.getHits().getHits().length == 0) {
break scroll;
}
}
return cities;
}
The "LocationFinder\src\main\resources\json\cities.json" file contains all cities from Belgium. You can delete or create entries if you want too. As long as you don't change the names and/or structure, no code changes are required.
Make sure to read the README https://github.com/GlennVanSchil/LocationFinder

mysql password() in js

I would like to generate the mysql-password hash from js.
I know the method with php functions,
$p = "example";
echo("$p<br>");
$p2= sha1($p,true);
echo("$p2<br>"); //ĂI')s~űvŠ-Ëo?
$result = sha1($p2);
echo("$result<br>"); //*57237bb49761f29ab9724ba084e811d70c12393d - this is the same as password("example") in mysql
and I'm trying to do this in javascript.
here is located the sha1 function:
http://pajhome.org.uk/crypt/md5/sha1.html
this is the hex2bin function I use to give the same result as sha1("",true);
function hex2bin(hex)
{
var bytes = [], str;
for(var i=0; i< hex.length-1; i+=2)
bytes.push(parseInt(hex.substr(i, 2), 16));
return String.fromCharCode.apply(String, bytes);
}
but at the last step it does not work. What can be the problem?
var p = "example";
console.log(p);
var p2 = hex2bin(hex_sha1(p));
console.log(p); //ÃI')s~ûv©-Ëo? - SEEMS OK
var result = hex_sha1(p2);
console.log(result); //9a5355dce26b1adfa0bdbe9f2b2a6e5ae58e5c9d WRONG
Use http://code.google.com/p/crypto-js/#SHA-1 with 2 encodings.
Here is an example:
var password = "TestPassword";
var result = ("*"+CryptoJS.SHA1(CryptoJS.SHA1(password))).toUpperCase();
console.log("result : " + result);
Result will be *0F437A73F4E4014091B7360F60CF81271FB73180. If you check it with mysql password() it will be the same:
mysql> select password("TestPassword") as result;
+-------------------------------------------+
| result |
+-------------------------------------------+
| *0F437A73F4E4014091B7360F60CF81271FB73180 |
+-------------------------------------------+
SOLUTION 2017
Download file 2.5.3-crypto-sha1.js
https://code.google.com/archive/p/crypto-js/downloads
var key = '*' + Crypto.SHA1(Crypto.util.hexToBytes(Crypto.SHA1('test'))).toUpperCase();
key = *94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
Test in MySQL
SELECT PASSWORD('test') /* function */
UNION
SELECT '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29' /* Key generated by javascript */
UNION
select CONCAT('*', UPPER(SHA1(UNHEX(SHA1('test'))))); /* Logic for Password() function */
So, in the example above, you are invoking: hex_sha1(hex2bin(hex_sha1(string))). Are you sure that is correct? Why would you need hex_sha1 twice?
Few month ago, I needed SHA1 in my JS and found this: http://phpjs.org/functions/sha1:512
... and it worked pretty ok ;)
The solution (partly):
Well, as you suggested, the main problem was charset encoding. It seems that MySQL does not encode any data prior to hashing it. This does not represent problem when dealing it with hex data, however, MySQL's UNHEX(hex2bin in JS) returns some unreadable chars and if we encode the result using UTF8 that's where all breaks apart.
When I edited JS's SHA1 not to encode data to UTF8 at line (I only commented the line):
str = this.utf8_encode(str);
everything seemed ok. However, as soon as I supplied some UTF8 chars to input (such as Central European chars čćžšđ) it started failing again.
So, bottom line, if you disable UTF8 in JSs SHA1 function and do not supply UTF8 chars on input it works fine.
I'm sure there is a solution to this such as JS function that will decode UTF8 input so, JS could hash it properly.

Merge FDF and PDF without PDFTK

Is there a way to merge FDF file and a PDF File to create a flat format of all the data and form into 1 pdf without using PDFTK?
Any light shed upon this would be greatly appreciated.
No.. There's no other way easy way to flatten, but it's awesome. Why would you need anything else?
PDFTK is actually mostly Java (literally hundreds of Java files). You could think about wrapping your own project around it. The functionality that you're looking for is here (java/com/lowagie/text/pdf/AcroFields.java:931):
/** Sets the fields by XFDF merging.
* #param xfdf the XFDF form
* #throws IOException on error
* #throws DocumentException on error
*/
public boolean setFields(XfdfReader xfdf) throws IOException, DocumentException {
boolean ret_val_b= false; // ssteward
xfdf.getFields();
for (Iterator i = fields.keySet().iterator(); i.hasNext();) {
String f = (String)i.next();
String v = xfdf.getFieldValue(f);
String rv = xfdf.getFieldRichValue(f); // ssteward
if (rv != null)
ret_val_b= true;
if (v != null)
setField(f, v, v, rv); // ssteward
}
return ret_val_b; // ssteward
}

Categories