Okay, here's a fun one.
I need to figure out what source a user is referencing when entering a copy and pasted Vimeo URL into an input box. For those that are unfamiliar, Vimeo currently has 4 different sources that are accessible through their simple API:
Videos belonging to a user
Valid URL structure: http://vimeo.com/user3825208 or https://vimeo.com/davekiss
Videos belonging to a group
Valid URL structure: http://vimeo.com/groups/eos550d or https://vimeo.com/groups/162
Videos belonging to a channel
Valid URL structure: http://vimeo.com/channels/hd or https://vimeo.com/channels/201
Videos belonging to an album
Valid URL structure: http://vimeo.com/album/1919683 or https://vimeo.com/album/mycustomname
So basically, I want to be able to run the URL into a function which will tell me what source the URL belongs to.
I've been using this for videos belonging to a user, but now I need to expand to all sources.
sscanf(parse_url($url, PHP_URL_PATH), '/%d', $video_id);
Maybe I should do this four times? preg_match('???', $url);
Thanks for your help!
You don't need regular expressions:
function discoverVimeo($url)
{
if ((($url = parse_url($url)) !== false) && (preg_match('~vimeo[.]com$~', $url['host']) > 0))
{
$url = array_filter(explode('/', $url['path']), 'strlen');
if (in_array($url[0], array('album', 'channels', 'groups')) !== true)
{
array_unshift($url, 'users');
}
return array('type' => rtrim(array_shift($url), 's'), 'id' => array_shift($url));
}
return false;
}
The following will return an array, with an index id and another index type, that will be one of:
user
album
channel
group
i would preg_match() the following regex patterns (in this order):
$channel_regex = '%vimeo\.com/channels/([a-zA-Z0-9]+)%/i';
$group_regex = '%vimeo\.com/groups/([a-zA-Z0-9]+)%/i';
$album_regex = '%vimeo\.com/album/([a-zA-Z0-9]+)%/i';
$user_regex = '%vimeo\.com/([a-zA-Z0-9]+)%/i';
this will regex match for:
vimeo.com/channels/...grab_this_data...
vimeo.com/groups/...grab_this_data...
vimeo.com/albums/...grab_this_data...
and if all of those preg_matches fail, (therefore a user URL), it will grab whatever is in the url:
vimeo.com/...grab_this_data...
good luck.
Related
I'm trying to retrieve the number of parking lots from a .txt file, its working on the static site iframe but I want to make a shortcode and place it on wordpress theme function file.
For some reason it's not reading the data...
function GenerateLOT($atts = array()) {
// Default Parameters
extract(shortcode_atts(array(
'id' => 'id'
), $atts));
// Create Default Park / Help
if ($id == '') {
$id = 'PARK IDs: bahnhofgarage;';
}
// Create Park Bahnhofgarage
if ($id == 'bahnhofgarage') {
$completeBahnhof = "//xxx.de/bahnhof.txt";
if(file_exists($completeBahnhof )) {
$fp=file($completeBahnhof );
$Garage = $fp[0];
$valmpl=explode(" ",$Garage);
$Bahnhof_Platz = $valmpl[0];
$Bahnhof_Tendenz = $valmpl[1];
}
$id = $Bahnhof_Platz;
}
return $id;
}
add_shortcode('parking', 'GenerateLOT');
[parking id='bahnhofgarage']
PS: The .txt is working properly retrieving like this: 000 - //bahnhof 27.12.15 12:46:59
For some reason its only displaying the $park == '' text and not the parking lots according shortcode param.
I've used this tutorial: sitepoint.com/wordpress-shortcodes-tutorial/
EDIT: There are 6 parking lots.
EDIT2: Changed park to id on all instances
The problem is that you can't meaningfully use file_exists on remote path. See SO answer to "file_exists() returns false even if file exist (remote URL)" question for details.
You should probably just call file() on that path. It will return FALSE if it encounter an error.
if ($id == 'bahnhofgarage') {
$completeBahnhof = "//xxx.de/bahnhof.txt";
$fp=file($completeBahnhof );
if ($fp !== false) {
$Garage = $fp[0];
// rest of code
On a side note, shortcode_atts() is used to provide default values for shortcode attributes, while you seem to be using it as some sort of mapping between shortcode attributes and internal variable names.
Accessing file on remote server inside shortcode is asking for trouble. Just think what will happen if this server is overloaded, slow to respond or not available anymore. You should really access that file asynchronously. If it is located on your server, access it through file-system path.
I am building some user profiles and want to add social links to the profiles so users can link to their, let's say Steam, YouTube, Google+ profiles.
So i can't find any way of validating against specific url's in laravel. I want a user, if he set a link in steam text field to validate if given url is really url to steampowered.com, or if not to throw an error that url is not valid.
I have read the documentation on validation and i read that there is a URL validation, but as i have read it's only validating agains the input if it's formated as an url. so basically user can post any url and it will be validated.
Is there a filter or some additional condition to URL validation for a specific url. So the input field will be valid only if user insert like: http://steamcommunity.com in the field.
How can someone achieve that, or i must write old php regex expression?
You should definetely write your own custom Validator and use a regexp to verify that:
\Validator::extend('checkUrl', function($attribute, $value, $parameters)
{
$url = $parameters[0];
//Your pattern, not pretending to be super precise, so it's up to you
$pattern = '/^((http|https)\:\/\/)?(www\.)?'.$url.'\..+$/'
if( preg_match( $pattern,$value)
{
return true;
}
return false;
});
And to use it provide it as a rule to your validator
$rules = [
your_field => 'checkUrl:http://steamcommunity.com'
];
Such a thing is not built in. You can write a custom validation rule and then use regex as you said.
Validator::extend('steam_url', function($attribute, $value, $parameters)
{
$pattern = "#^https?://([a-z0-9-]+\.)*steamcommunity\.com(/.*)?$#";
return !! preg_match($pattern, $value);
});
Usage: 'url' => 'steam_url
Or something more generic:
Validator::extend('domain', function($attribute, $value, $parameters)
{
$domain = $parameters[0];
$pattern = "#^https?://([a-z0-9-]+\.)*".preg_quote($domain)."(/.*)?$#";
return !! preg_match($pattern, $value);
});
Usage: 'url' => 'domain:steamcommunity.com'
Both of your answers are correct guys, however i never liked using regex and i remembered what i did on some site i was making last year to match the website url, and to match it to the point where is no possible for user to input wrong url, and this will also match both http and https. So my final solution is to use parse_url method, very simple and thanks to your examples of validator parameters i can also use it on multiple different domains.
Here's my final code.
Validator::extend('checkUrl', function($attribute, $value, $parameters) {
$url = parse_url($value, PHP_URL_HOST);
return $url == $parameters[0];
EDIT: there is even simpler solution instead of using if method and returning false or true, you can just use return method with option you want to validate.
return $url == $parameters[0];
This would be resolved as
if($url == $parameters[0]) {
return true
} else {
return false
}
A little more than a month ago I did a post involving the extraction the values of from a URL.
https://stackoverflow.com/questions/21231390/extracting-the-values-from-a-xml-url
It was a good answer and helped me a lot, but is there a way to generalize the code for any parameter given? The testing parameters won't be part of a formula, and this plugin I'm developing is supposed to be handled by Moodle teachers. They won't have access to my code to manually alter the parameters themselves. Here is the link.
By changing the rs parameter, I change the course. p(even/odd) and tp(semestral/anual/trimestral courses) parameters are about semesters and year is the year.
This is what I currently have.
function buildURL($year, $period, $typeperiod,$course)
{
return 'https://clip.unl.pt/sprs?lg=pt&year='.$year.'&uo=97747&srv=rsu&p='.$period.'&tp='.$typeperiod.'&md=3&rs='.$course.'&it=1030123459';
}
function doRequest_with_FileGetContents($url)
{
return download_file_content($url);
}
function processXML($xmlContent)
{
$xmlObj= new SimpleXMLElement($xmlContent);
$result=array();
foreach($xmlObj->unidade_curricular->inscritos->aluno as $aluno)
{
$result[]= $aluno->identificador;
}
return $result;
}
Testing parameters:
$year='2014';
$period='1';
$typeperiod='s';
$course='8145';
$url=buildURL($year,$period,$typeperiod,$course);
$content_b = doRequest_with_FileGetContents($url);
$dataClip = processXML($content_b);
I've tried to associate the id number of the course (course / course edit Settings/course id number) to the parameter rs, by typing:
$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
$idnumber = $course->idnumber;
and replace it in $url=buildURL($year,$period,$typeperiod,$idnumber); but the XML doesn't even process. Is this even possible to pull it off without a formal interface?
I know *wp_remote_get* is a WordPress function, and that I should be posting this in wordpress.stackexchange, however, I am almost certain my issue lies more on the general PHP side.
The problem: I need to retrieve all Vimeo videos found within an album, yet I am only getting 20.
The approach:
$vmg_feed_url = 'http://vimeo.com/api/v2/';
$vmg_user = '2212323';
if($vmg_type == 'user'){ /** just an input variable checking whether the function should search for user or for album. in our case, it searches for album **/
$vmg_type_url = '';
} else {
$vmg_type_url = $vmg_type . '/';
}
$vmg_videos_url = $vmg_feed_url . $vmg_type_url . $vmg_user . '/videos.xml';
$videos_result = wp_remote_get($vmg_videos_url);
$vmg_videos = simplexml_load_string($videos_result['body']);
The resulting XML is http://vimeo.com/api/v2/album/2212323/videos.xml - and as you can see, I am only retrieving 20 videos.
The question: Am I missing something? Is there a function/variable that sets a limit to the amount of videos I can retrieve? I know that wp_remote_get gives me these attributes (from the WordPress Codex):
$url
(string) (required) Universal Resource Locator (URL).
- Default: None
$args
(array) (optional)
- Default: method: GET, timeout: 5, redirection: 5, httpversion: 1.0, blocking: true, headers: array(), body: null, cookies: array()
Any help is truly appreciated. Please let me know if I forgot about any details!
Yor problem is not in wordpress or PHP. It is API limits:
http://developer.vimeo.com/apis/simple
Simple API responses include up to 20 items per page.
You can get more by adding ?page parameter in next requests.
i have url like this :
http://quickstart.local/public/category1/product2
and in url (category1/product2) numbers are id , categorys and products fetched from database attention to the id
id is unique
i need to the sensitive url like zend framework url. for example :http://stackoverflow.com/questions/621380/seo-url-structure
how i can convert that url to the new url like this
is there any way?!!
You'll need to store a unique value in your database with a field name such as 'url' or something similar. Every time you generate a new product you will have to create this unique url and store it with the product information. A common way to do this is to take the name of the product and make it url friendly:
public function generateUrl($name)
{
$alias = str_replace(' ', '-', strtolower(trim($name)));
return preg_replace('/[^A-Za-z0-9-]/', '', $alias);
}
Calling this method:
$url = $this->generateUrl("My amazing product!");
echo $url;
will output:
my-amazing-product
You'll need to check that the output from this function does not already exist in the database as you will use this value to query on instead of the id.
If you apply this logic to the categories as well, you can have easily readable and descriptive urls like the one below. You may need to tweak your routing before this works correctly though.
http://quickstart.local/public/awesome-stuff/my-amazing-product
You could use ZF's Zend_Controller_Router_Route. For example, to make similar url to those used by SO, one could define a custom route in an application.ini as follows (assuming you have controller and action called questions and show respectively):
resources.router.routes.questions.route = '/questions/:id/:title'
resources.router.routes.questions.type = "Zend_Controller_Router_Route"
resources.router.routes.questions.defaults.module = default
resources.router.routes.questions.defaults.controller = questions
resources.router.routes.questions.defaults.action = show
resources.router.routes.questions.defaults.id =
resources.router.routes.questions.defaults.title =
resources.router.routes.questions.reqs.id = "\d+"
Having such a route, in your views you could generate an url as follows:
<?php echo $this->url(array('id'=>621380,'title' => 'seo url structure'),'questions');
// results in: /myapp/public/questions/621380/seo+url+structure
//OR if you really want to have dashes in your title:
<?php echo $this->url(array('id'=>621380,'title' => preg_replace('/\s+/','-','seo url structure'),'questions');
// results in: /myapp/public/questions/621380/seo-url-structure
Note that /myapp/public/ is in the url generated because I don't have virtual hosts setup on my localhost nor any modifications of .htaccess made. Also note that you don't need to have unique :title, because your real id is in :id variable.
As a side note, if you wanted to make it slightly more user friendly, it would be better to have your url as /question/621380/see-url-structure rather than /questions/621380/see-url-structure. This is because under this url you would have only one question, not many questions. This could be simply done by changing the route to the following resources.router.routes.questions.route = '/question/:id/:title'.
EDIT:
And what to do with categories and products that you have in your question? So, I would define a custom route, but this time using Zend_Controller_Router_Route_Regex:
resources.router.routes.questions.route = '/questions/(\d+)-(d+)/(\w*)'
resources.router.routes.questions.type = "Zend_Controller_Router_Route_Regex"
resources.router.routes.questions.defaults.module = default
resources.router.routes.questions.defaults.controller = questions
resources.router.routes.questions.defaults.action = show
resources.router.routes.questions.map.1 = category
resources.router.routes.questions.map.2 = product
resources.router.routes.questions.map.3 = title
resources.router.routes.questions.reverse = "questions/%d-%d/%s"
The url for this route would be then generated:
<?php echo $this->url(array('category' => 6213,'product' => 80,'title' => preg_replace('/\s+/', '-', 'seo url structure')),'questions' ); ?>
// results in: /myapp/public/questions/6213-80/seo-url-structure
Hope this will help or at least point you in the right direction.