Youtube api get latest upload thumbnail - api

I am looking to returning the video-thumbnail of the latest uploaded video from my channel, and display it on my website.
Anyone know how I can do a minimal connection trough api and get only the thumbnail?
Thanks!
-Tom
REVISED!!
Using Cakephp, this is how I did it (thanks dave for suggestions using zend);
controller:
App::import('Xml');
$channel = 'Blanktv';
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads?v=2&max-results=1&orderby=published';
$parsed_xml =& new XML($url);
$parsed_xml = Set::reverse($parsed_xml);
//debug($parsed_xml);
$this->set('parsed_xml',$parsed_xml);
View;
$i=0;
foreach ($parsed_xml as $entry)
{
echo '<a href="/videokanalen" target="_self">
<img width="220px" src="'.$entry['Entry']['Group']['Thumbnail'][1]['url'] .'">
</a>';
}
Now the only thing remaining is to cache the feed call someway.. Any suggestions???
-Tom

here is a quick dirty way of doing it without really touching the api at all.
I'm not suggesting it's best practice or anything and I'm sure there are smarter ways but it definitely works with the current Youtube feed service.
My solution is PHP using the Zend_Feed_Reader component from Zend Framework, if you need a hand setting this up if you're not familiar with it let me know.
Essentially you can download version 1.11 from Zend.com here and then make sure the framework files are accessible on your PHP include path.
If you are already using Zend Framework in an MVC pattern you can do this in your chosen controller action:
$channel = 'Blanktv'; //change this to your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
$this->view->feed = $feed;
Then you can do this in your view:
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($this->feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
otherwise you can do:
<?php
$channel = 'Blanktv'; //change this to your channel
$url = 'https://gdata.youtube.com/feeds/api/users/'.$channel.'/uploads';
$feed = Zend_Feed_Reader::import($url);
?>
<h1>Latest Video</h1>
<div>
<?php
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
echo '<h3>' . $entry->getTitle() . '</h3>';
echo '<p>Uploaded on: '. $entry->getDateCreated() .'</p>';
echo '<a href="http://www.youtube.com/watch?v=' . $videoId .'" target="_blank">
<img src="http://img.youtube.com/vi/' . $videoId .'/hqdefault.jpg">
</a>';
$i++;
if($i==1) break;
}
?>
</div>
With the latter method you'll likely need to use a php require statement for the Zend_Feed_Reader files etc....
Hope this helps, like I say let me know if you need a hand.
All the best,
Dave
UPDATE: In response to your comments about caching
Hi Tom, here is another quick and dirty solution which doesn't use cache but may be very quick to implement.
The reason I didn't go with a caching component is because I figured a simple db solution would suffice under the circumstances. I also thought having to pull the feed to compare whether it was new or not wouldn't be the most economical for you.
You could automate this process to be run automatically at specified times but if you don't want to automate the process and don't mind clicking a link to update the video manually you could trigger it that way.
My solution is again based on ZF but since you were ok hacking it into something useful with cakephp you should have no problem doing the same here.
First set up a new table (assuming a MySQL db):
CREATE TABLE `yourdbname`.`latestvid` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique identifier',
`videoId` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video id',
`videoTitle` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video title',
`uploadDate` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'Video upload date'
) ENGINE = INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `yourdbname`.`latestvid` (`id`, `videoId`, `videoTitle`, `uploadDate`) VALUES (NULL, '--', '--', '--');
This will create a table for your latest video info for use in your template however the default values I've set up will not work with your template for obvious reasons.
You could then do something similar to this:
public function updateAction()
{
$this->_helper->viewRenderer->setNoRender(); // disable view
$this->_helper->layout()->disableLayout(); // disable layout
$user = 'Blanktv'; // insert your channel name
$url = 'https://gdata.youtube.com/feeds/api/users/'.$user.'/uploads';
$feed = Zend_Feed_Reader::import($url);
if(!$feed)
{
die("couldn't access the feed"); // Note: the Zend component will display an error if the feed is not available so this wouldn't really be necessary for ZF
}
else
{
$i=0;
foreach ($feed as $entry)
{
$urlChop = explode ('http://gdata.youtube.com/feeds/api/videos/',$entry->getId());
$videoId = end($urlChop);
$videoTitle = $entry->getTitle();
$uploadDate = $entry->getDateCreated();
// use your preferred method to update the db record where the id = 1
$i++;
if($i==1) break;
}
}
}
Maybe have a go and let me know how you get on?
You'd just need to tweak the template so you'd get the variables from the database instead of Youtube with the exception of the thumbnail.
I suppose you could always take that approach further and actually store images etc since the thumbnail is still being pulled from Youtube and may slow things down.
You could set up a script to copy the thumbnail to your own server and store the path in the db or use a standard thumbnail if you are running a series of videos for which you require standard branding - anyway hope it helps.
:-D
Dave

Related

Insert SQL statement error

Hi Im trying to insert data into a database using an insert statement. So basically, the user inputs data into a form and then once the submit button is clicked its meant to get the property_id of the table Property.
My code is this:
<?php
$id = intval($_GET['id']);
$query = mysql_query('SELECT * FROM review WHERE property_id="'.$id.'"');
if(isset($_POST['submit']))
{
$review = mysqli_real_escape_string($mysqli, $_POST['review']);
if(mysqli_query($mysqli, "INSERT INTO review(review) VALUES ('$review')"))
{
?>
<script>alert('Successfully Updated ');</script>
<?php
}
else
{
?>
<script>alert('Error...');</script>
<?php
}
}
?>
At the top of the page is my other code which is as followed:
<?php
include_once '../db/dbconnect.php';
$id = intval($_GET['id']);
$sql = 'SELECT* FROM property WHERE property_id="'.$id.'"';
$result = mysqli_query($mysqli, $sql);
$row=mysqli_fetch_array($result);
?>
The code above basically displays all the data for that individual property. Any help would be great.
There are several errors in your code:
$id = intval($_GET['id']);
$query = mysql_query('SELECT * FROM review WHERE property_id="'.$id.'"');
The mysql_* functions are deprecated in PHP 5, and totally removed in PHP 7. Don't use them!
Moreover, it's not possible to use mysql_* and mysqli_* functions together.
Yet another error: you are executing a SELECT query, but you never fetch the results!
Note: you don't need to concatenate $id. It makes the code harder to read with plenty of useless single and double quotes, and increases the likeliness of a typo. Just enclose the variables in a double-quoted string.
You are casting $id to an int value. If the field property_id is an integer, there is no need to put single quotes around $id in the query.
Updated snippet:
$id = intval($_GET['id']);
$query = mysqli_query($mysqli, "SELECT * FROM review WHERE property_id=$id") or die(mysqli_error($mysqli));
while($r = $query->fetch_assoc()) {
// do something here with the current record $r
}
Your code:
if(mysqli_query($mysqli, "INSERT INTO review(review) VALUES ('$review')"))
[...]
<script>alert('Error...');</script>
When developing, you should display (or write to a log file) the MySQL error message from each failing query. It will make debugging much easier:
<script>alert('Error: <?= mysqli_error($mysqli) ?>');</script>

Joomla 3.0 not echoing usertype

I made the following code to get some user variables in a flash app:
<?php
$user =& JFactory::getUser();
echo $user->get('username') ;
echo $user->get('id') ;
echo $user->get('name') ;
echo $user->get('usertype') ;
?>
Everything but usertype works, for some reason. Usertype is vital to be able to monetize my app. I followed this as a reference, so it seems alright:
http://docs.joomla.org/Accessing_the_current_user_object
Whats wrong here?
Right, I've had a look around and I can't actually find a decent solution that simply provides you with the name of the group that the user belongs to. Everything else gives you an array or the ID, so I have written a simple function that will get you exactly what you want:
function getUserGroup($userId){
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('title')
->from('#__user_usergroup_map AS map')
->where('map.user_id = '.(int) $userId)
->leftJoin('#__usergroups AS a ON a.id = map.group_id');
$db->setQuery($query);
$result = $db->loadResult();
return $result;
}
echo getUserGroup($user->id);
Hope this helps

Edit woocommerce Login register page

I am using woocommerce for an eCommerce website. I want to add one more field in Login Regiser page. On this page there are three fields in registration (Email, Password and Re-enter password) and I want to add one more field for phone number.
Can anybody help me ? Thanks in Advance
http://wordpress.org/plugins/woocommerce/
If anyone else is curious on how to add additional fields to the login/register/any other account forms. You can achieve this quite easily since WooCommerce has added those to their templates folder. All you have to do is copy-paste the form you need to modify from plugins>woocommerce>templates>myaccount and drop it into your own theme. After which, you can add your extra fields and add any other functionality to make them work using http://docs.woothemes.com/document/hooks/
Hope this is of help to anyone who's been stuck on this.
I Use the "Register Plus Redux" plugin and use the "billing_phone" Database key to map to the correct field in the the User database. You can also have the user add other Information such as "'billing_address_1" and any others.
Best Regards
Marc
Old post, but this answer deals with the question as asked and provides a direct answer form the WordPress Codex
I have modified the code from the pages linked to act inline with the zipcode example that appears on the validation page. Each page within the codes used different examples, I just made them all the same.
Add the custom field
Plugin API/Action Reference/register form
The 'register_form' action hook is used to customize the built-in WordPress registration form.
Use in conjunction with 'registration_errors' (for validation) and 'register_post' (save extra data) when customizing registration.
WordPress MS Note: For Wordpress MS (Multi-Site), use the 'signup_header' action to redirect users away from the signup. (emphasis mine, took me a while to realise this)
Example
This example demonstrates how to add a new field to the registration form. Keep in mind that this won't be saved automatically. You will still need to set up validation rules and manually handle saving of the additional form fields.
add_action( 'register_form', 'myplugin_add_registration_fields' );
function myplugin_add_registration_fields() {
//Get and set any values already sent
$zipcode = ( isset( $_POST['zipcode'] ) ) ? $_POST['zipcode'] : '';
?>
<p>
<label for="user_extra"><?php _e( 'Extra Field', 'myplugin_textdomain' ) ?><br />
<input type="text" name="user_extra" id="user_extra" class="input" value="<?php echo esc_attr( stripslashes( $zipcode ) ); ?>" size="25" /></label>
</p>
<?php
}
link: https://codex.wordpress.org/Plugin_API/Action_Reference/login_form
Validation
You need to validate the user input (obviously) and should run that throughregistration_errors filter hook. Be mindful, the $errors variable may already be populated by other errors from the registration process. As in the examples, you would add your error to errors already contained therein.
Returning an Error
function myplugin_check_fields( $errors, $sanitized_user_login, $user_email ) {
$errors->add( 'demo_error', __( '<strong>ERROR</strong>: This is a demo error.', 'my_textdomain' ) );
return $errors;
}
add_filter( 'registration_errors', 'myplugin_check_fields', 10, 3 );
Validating a Custom Field
(this next section deals specifically with validation of the custom field)
Assuming you wanted to validate a postal code field that you have already created using the register_form hook, you might validate the field like so:
function myplugin_check_fields( $errors, $sanitized_user_login, $user_email ) {
if ( ! preg_match('/[0-9]{5}/', $_POST['zipcode'] ) ) {
$errors->add( 'zipcode_error', __( '<strong>ERROR</strong>: Invalid Zip.', 'my_textdomain' ) );
}
return $errors;
}
add_filter( 'registration_errors', 'myplugin_check_fields', 10, 3 );
link: https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors
finally, don't forget to save the custom field's data!
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
if ( isset( $_POST['zipcode'] ) )
update_user_meta($user_id, 'zipcode', $_POST['zipcode']);
}
link: https://codex.wordpress.org/Plugin_API/Action_Reference/user_register
A complete example
At the end of all this I ended up coming across a tutorial to do exactly this. In this example they are adding a First Name field:
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
$first_name = ( ! empty( $_POST['first_name'] ) ) ? sanitize_text_field( $_POST['first_name'] ) : '';
?>
<p>
<label for="first_name"><?php _e( 'First Name', 'mydomain' ) ?><br />
<input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( $first_name ); ?>" size="25" /></label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) {
$errors->add( 'first_name_error', sprintf('<strong>%s</strong>: %s',__( 'ERROR', 'mydomain' ),__( 'You must include a first name.', 'mydomain' ) ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['first_name'] ) ) {
update_user_meta( $user_id, 'first_name', sanitize_text_field( $_POST['first_name'] ) );
}
}
https://codex.wordpress.org/Customizing_the_Registration_Form

Extbase - get created sql from query

i want to get some database tables from my typo3 extensions.
The Extension is based on extbase.
The query always returns nothing but the data exists
I've tried this:
$query = $this->createQuery();
$query->statement('SELECT * FROM `my_table`
WHERE field = ? ORDER BY date DESC LIMIT 1',
array($condition));
$results = $query->execute();
and this:
$query = $this->createQuery();
$query->matching($query->equals('field', $condition));
$query->setOrderings(array('date' => Tx_Extbase_Persistence_QueryInterface::ORDER_DESCENDING));
$query->setLimit(1);
$results = $query->execute();
both returns null as result.
Is it possible to get the sql that the class creates to look where the bug is?
I've looked in some extbase persistent classes but didn't find a clue
EDIT:
For those who are interested.. i found a "solution".
If you create the query with the statement() method, you can print the query with this function
echo $query->getStatement()->getStatement();
It doesn't replace the placeholder.
But you can get the Variables with this method
var_dump($query->getStatement()->getBoundVariables());
Thats the best Solution that i found, without editing the extbase extenstions
In TYPO3 6.2 you can use Extbase DebuggerUtility to debug the query.
Add this code before $query->execute():
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbQueryParser');
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($queryParser->parseQuery($query));
For TYPO3 8.7+ use this code instead:
$queryParser = \TYPO3\CMS\Core\Utility\GeneralUtilityGeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser::class);
$doctrineQueryBuilder = $queryParser->convertQueryToDoctrineQueryBuilder($query);
$doctrineQueryBuilderSQL = $doctrineQueryBuilder->getSQL();
$doctrineQueryBuilderParameters = $doctrineQueryBuilder->getParameters();
Check this snippet, although it's not very comfortable in use it helps a lot:
in general you need this code at the end of the buildQuery(array $sql) method (*) - right before return $statement;
if (in_array("your_table_name", $sql['tables'])) {
var_dump($statement);
print_r($statement);
}
(*) Class file:
TYPO3 ver.: 4.x: typo3/sysext/extbase/Classes/Persistence/Storage/Typo3DbBackend.php
TYPO3 ver.: 6.x: typo3/sysext/extbase/Classes/Persistence/Generic/Storage/Typo3DbBackend.php
In 6.2.x ...
You can try within \TYPO3\CMS\Core\Database\DatabaseConnection::exec_SELECTquery method, just add the condition after fetching the $query, like (trim is important!):
public function exec_SELECTquery($select_fields, $from_table, $where_clause, $groupBy = '', $orderBy = '', $limit = '') {
$query = $this->SELECTquery($select_fields, $from_table, $where_clause, $groupBy, $orderBy, $limit);
if (trim($from_table) == 'fe_users') {
DebuggerUtility::var_dump($query);
}
// rest of method
An easy way without changing any Typo3 core code and not mentioned in any forum so far is using the php "serialize()" method:
$result = $query->execute();
echo (serialize($result));
In the result object you find the SQL query ("statement;" ...)
Improvement to biesiors answer:
As Extbase replaces some placeholders after calling buildQuery(), you might prefer to place the debug output into getObjectDataByQuery(), just after $this->replacePlaceholders($sql, $parameters, $tableName);
if (strpos($sql, "your_table_name.")) {
debug($sql, 'my debug output');
};
Also, better use debug() instead of var_dump().
[File: typo3\sysext\extbase\Classes\Persistence\Generic\Storage\Typo3DbBackend.php. Line 339 in version 6.1]:
$query = $this->createQuery();
$query->getQuerySettings()->setReturnRawQueryResult(TRUE);
$getHotelInfo = 'SELECT * FROM `my_table` WHERE field = ? ORDER BY date DESC LIMIT 1';
return $query->statement($getHotelInfo)->execute();
For executing query you have to write 'setReturnQueryResult' on your repository
I just extended the above snippet, with a $_GET condition.
for debugging, just append "?dbg_table=tx_some_of_my_tables" to your address, and you're ready to go ;-)
if (in_array($_GET['dbg_table'], $sql['tables'])) {
echo('<div style="background: #ebebeb; border: 1px solid #999; margin-bottom: 20px; padding: 10px;"><pre style="white-space: normal">'.$statement.'</pre></div>');
}
A cleaner way to debug your statements when using TYPO3 6.1 is to use the query parser of Typo3DbBackend.
$parser = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Storage\\Typo3DbBackend');
$params = array();
$queryParts = $parser->parseQuery($query, $params);
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('query', 'my_extension', 1, array('query' => $queryParts, 'params' => $params));
The parser returns an array containing the different parts of the generated SQL statement.
With TYPO3 6.2 the parseQuery method was moved to Typo3DbQueryParser and lost its second parameter.
i suggest set this in typo3conf/LocalConfiguration.php file under 'SYS' array
'SYS' => array(
......
'displayErrors' => 1,
'sqlDebug' => 1
.......
)
and then write wrong field name in query intentionally and then execute code.
this will show last query execute with error.

Yii: How to work with translate Yii::t() and hyperlinks

I have many lines similar to this in my code:
echo Yii::t('forms','Would you like to create a new item?');
where I want to hyperlink just around "create a new item", as an example.
Here are some alternatives that I've thought about:
Split the URL into 2 translated strings, surrounded by a hyperlink:
echo Yii::t('forms','Would you like to').' '.Yii::t('forms','create a new item').'?';
Use placeholders, as described in the Yii documentation ( http://www.yiiframework.com/doc/guide/1.1/en/topics.i18n Although hyperlinks aren't given as an explicit example):
echo Yii::t('forms','Would you like to {url}create a new item',array('{url}'=>"<a href='/new_item'>")).'</a>?';
There's probably an easier way to do this, but I've been unable to discover the preferred method...what's the best way to build translated strings that include URLs?
I suggest to you this solution:
echo Yii::t(
'forms',
'Would you like to {link:create}create a new item{/link}?',
array(
'{link:create}'=>'<a href="/new_item">',
'{/link}'=>'</a>',
)
);
The benefit is if you want put id, class, onclick and more anything in a tag you can do it. and so the translate string in clear.
Note that create in {link:create} is just a ideal string that pointer to hyperlink string.
Another advanced sample:
echo Yii::t(
'forms',
'Would you like to {link:create}create a new item{/link}? And you can {link:delete}delete the item{/link}.',
array(
'{link:create}'=>'<a href="/new_item" class="button">',
'{link:delete}'=>'<a href="#" id="item-21" onclick="delete(21);">',
'{/link}'=>'</a>',
)
);
The link may have different placement (beginning, middle or end) and label in the translated string depending on a target language. Therefore, you should use placeholder only for url:
echo Yii::t(
'forms',
'Would you like to create a new item?',
array('{url}' => '/new_item')
);
Use following if you have a dynamic uri:
echo Yii::t(
'forms',
'Would you like to create a new item?',
array(':url'=>'/new_item')
);
Or:
echo Yii::t(
'forms',
'Would you like to create a new item?',
);
Or if you want to pass other dynamic attributes other than the url, use the following:
echo Yii::t(
'forms',
'Would you like to <a :linkAttr>create a new item?</a>',
array('linkAttr'=>'href="/new_item" id="link-id" class="link-class"')
);
I think this is a better solution:
echo Yii::t(
'forms',
'Would you like to {action}?'
[
'action' => Html::a(
Yii::t('forms', 'create a new item'),
['controller/action']
)
]
);
Benefits of this solution
You can use helpers to generate your link
You can modify your html code without modifing the translations
Whoever will be doing translations doesn't need to know anything about html and they can't mess the html code.