drupal add video Video Embed - drupal

I will Try to add Video Embed to drupal-7 programmatically
with thumb.
This is what I've tried:
$url='https://www.youtube.com/watch?v=8Zq3KCBed5Q';
$file_path = drupal_realpath($url);
$file->uid = 1;
$file->filename = 'dsdss';
$file->uri = $url;
$file->filemime = file_get_mimetype($file_path);
$file->type = 'video';
$file->status = 1;
$file_exists = file_save($file);
$node->field_videoyou[$node->language]['0'] = (array) $file_exists;
How I can do this?

As far as I know, drupal_realpath is converting local drupal path to absolute path and you are passing to it absolute path. Also, you didn't show us where you create that $file object. What is that?
If you check file_save() docs:
https://api.drupal.org/api/drupal/includes!file.inc/function/file_save/7
...you'll see that $file should be "a file object returned by file_load()."
So, I think that you are using drupal_realpath wrong, don't see that you are using file_load() for creating $file object and I don't see that you are copy-ing file to your server.
My suggestion is not to mess with files anyway, but just take player embed code and use it. You can have some text field to your content type where admin can insert video embed code and just shoot that value out on front-end.
Moreever...it will probably happen that embed code is pretty similar for different videos and that only difference is just some video id value so you don't even have to store whole embed code, but just that video id and you can keep rest of embed code in some template file, as static, where you will just insert video id.

Related

How to upload image in wordpress?

I am new in wordpress, I am currently creating a plugin which is get the message and image and store it in database. I learn wpdb class to store data to database, But i still can't know how to move and upload file and store in also in folder and media library. Please help me i tried codes which i get at wordpress.org but still cant upload image to media library. If you cant tell me please reference to learn admin-ajax.
Get an array containing the current upload directory’s path and url.
wp_upload_dir( string $time = null, bool $create_dir = true, bool $refresh_cache = false )
You can find more on https://developer.wordpress.org/reference/functions/wp_upload_dir/

import a google static map directly in fpdf

I wanted to place a google static map in a pdffile generated by using the fpdf extension.
and used code to make a tempfile first. Using this code. However I run into an error ('can't open image file').
// define the mapurl
$fullURL = 'http://maps.googleapis.com/maps/api/staticmap?center=Amsterdam&z=14&size=100x100&sensor=false';
// create a tempfile
$tempF = tmpfile();
fwrite($tempF, file_get_contents($fullURL));
//Rewind to the start of file
rewind($tempF);
// place the image in the pdf.
if (!empty($tempF)) {
$this->Image($tempF,$start_x, $this->GetY(),0,100);
}
fclose($tempF); // remove the tempfile
Note: OP's own answer extracted from the question.
Then I found out it can be done much easier... I don't need to use a tempfile. If I put the url in the image variable and give a format the thing works in two lines.. I don't use the height and width parameters in fpdf because they stretch the image into a unreadable form.
$fullURL = "http://maps.googleapis.com/maps/api/staticmap?center=". \
$row-Google_coor."&zoom=10&size=2200x200\
&markers=color:blue%7Clabel:D%7C".$row->Google_coor;
$this->Image($fullURL,$start_x, $this->GetY(),0,0,"PNG");
Saddly when using this function sometimes the program returns an error. The image could not be found. But when I put the url string in the browser the image shows up fine. Hopefully this is also a minor fallback.
Lets see if I find a solution on the google apis site https://developers.google.com/maps/documentation/staticmaps/?csw=1
For what it is worth I had this problem as well, I found that my server had an outgoing connections manager, this would automatically block the request, I had to add the ip, once this was done it worked fine.
I had a problem similiar to the OP's. I was getting an error when using FPDF and trying to get the static map image from Google Maps and into my PDF. I was getting "FPDF error: Missing or incorrect image file". What I did is to register in the Google Developer Console and get an API Key, just like they say in the documentation
Hope this helps.
You can download the image and use it with fpdf
$url ="https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=".$googleApiKey;
$img = __DIR__.'/img/map.png';
file_put_contents($img, file_get_contents($url));
$pdf->Image($img,null,null,170);
Hope that this will be helpful

Scraping product information for comic book website

I'm making a comic book website built upon a WordPress platform for an old friend for his business. I would like to be able to have a script that goes to various publisher sites and pulls in the data. I'm new to programming and I've read of many different alternatives and just don't know where to begin. Firstly, would this be legal to pull this content from these websites? Secondly, here's an example for what I would like to do.
Page displays what's coming out for the month. Copy all links from
that page within the appropriate div that leads to the comic book
details. Save each hyperlink as $comiclink or whatever. The script will
execute each hyperlink at a time.
Go to the hyperlink for $comiclink and scrape content out of the page based
upon what's in certain DIV's on that page. Example:
Copy & save comic title within a defined div into $title
Copy & save previous and future title hyperlinks within a defined div into $othertitles
Note: $othertitles will loop off and start the same process itself from 1.
Save & download all images within a defined div to $images
Copy & save all content within a defined div to $content. $content is then broken down
and pulled apart based upon the content that is within it. Example:
In stores: $date
format: $format
UPC: $upc
Price: $price
The Story: $story
Copy & save defined div hyperlink and save into $seriesinfo
Copy & save defined div $relatedinfo and then break it down.
images within $relatedinfo to $relatedimages
content within $relatedinfo to $relatedcontent
links within $relatedinfo to $relatedlink. $relatedlink will loop off and restart this process itself from 1.
Now that everything is broken apart and saved into it's own little pieces. I want WordPress to automatically create a post and then start assigning all this info into the post. Working something like this.
Check for existing post with same $title if does not exist place $title in title for post and page-name. If it exists abort script and move on to the next.
Remove numbers and alpha characters from $title and check for existence of category if it does not exist; create it and assign to post. If it exists assigns category to the post.
Check for existing category with value $format if exists assign to post, if not create & assign category to post.
upload images that were downloaded from $image into this post.
Check for images that contain the word "cover" and assign as featured image.
Also how this whole thing executes also. I don't want this running 24/7 - just once a week I would like this to execute by itself and automatically go to the websites in question and scrape the content and create the pages.
I'm not asking you guys to write out the whole darn thing for me; though I definitely won't object to it! Just help point me in the right directions to get this going. Over the past day I've read probably 30+ articles on pulling content and there's so many options from what I can tell that I just don't know where to begin or how to get the ball moving in the right direction with this.
Updated Code
Notes: So I've managed to successfully copy the content and paths for each block and instead of downloading the images just echoing them from their present location. Next up is actually automating the process to create a post in wordpress to dump the data into.
function scraping_comic()
{
// create HTML DOM
$html = file_get_html('http://page-on-site-to-scrape.com');
// get block to scrape
foreach($html->find('li.browse_result') as $article)
{
// get title from block
$item['title'] = trim($article->find('h4', 0)->find('span',0)->plaintext);
// get title url from block
$item['title_url'] = trim($article->find('h4', 0)->find('a.grid-hidden',0)->href);
// get image from block
$item['image_url'] = trim($article->find('img.main_thumb',0)->src);
// get details from block
$item['details'] = trim($article->find('p.browse_result_description_release', 0)->plaintext);
// get sale info from block
$item['on_sale'] = trim($article->find('.browse_comics_release_dates', 0)->plaintext);
$ret[] = $item;
}
// clean up memory
$html->clear();
unset($html);
return $ret;
}
// ===== The Code ====
$ret = scraping_comic();
if ( ! empty($ret))
{
// place main url for instance when hyperlinks and image srcs don't use the full path.
$scrape = 'http://site-to-scrape.com';
foreach($ret as $v)
{
echo '<p>'.$v['title'].'</p>';
echo '<p><img src="'.$v['image_url'].'"></p>';
echo '<p>'.$v['details'].'</p>';
echo '<p> '.$v['on_sale'].'</p>';
}
}
else { echo 'Could not scrape page!'; }
?>
Typically, no this wouldn't be legal. Companies that share their data these days will implement an API you can call and use in your application (subject to their Terms of Use and Copyright Policy). They don't like you making automated requests that bog down their server and kill their bandwidth.
That being said, often times product information is available from other sources such as Amazon which does have an API.
This project you are describing has a lot of work to be done essentially customizing the WordPress CMS and would be less than trivial for someone without any programming experience. You might want to consider hiring a freelancer at oDesk or one of the many other freelance job boards.

Re-processing attached images in drupal 7

I'm trying to import nodes from my forum to drupal 7. Not in bulk, but one by one so that news posts can be created and referenced back to the forum. The kicker is that I'm wanting to bring image attachments across as well...
So far, using the code example here http://drupal.org/node/889058#comment-3709802 things mostly work: Nodes are created, but the images don't go through any validation or processing.
I'd like the attached images to be validated against the rules defined in the content type. in particular the style associated with my image field which resizes them to 600x600.
So, instead of simply creating the nodes programatically with my own form, i decided to modify a "new" node using hook_node_prepare and using the existing form to create new content (based on passed in url args). This works really well and a create form is presented pre-filled with all my data. including the image! very cute.
I expected that i could then hit preview or save and all the validation and resizing would happen to my image, but instead i get the error:
"The file used in the Image field may not be referenced."
The reason for this is that my file doesn't have an entry in the file_usage table.. *le sigh*
so, how do i get to all the nice validation and processing which happens when i manually choose a file to upload? like resizing, an entry in the file_usage table.
The ajax upload function does it, but i can't find the code which is called to do this anywhere in the api.
What file upload / validation functions does Drupal call which i'm not doing?
Anybody have any experience with the file/image api for Drupal 7 who can help me out?
For getting the usage entry (in essence, checking out a file to a specific module so that it doesn't get deleted while its in use) look up the Drupal function 'file_usage_add()'
For validating incoming images, I got this example from user.module (if you're comfortable with PHP, you can always look at the core to see how something is done the 'Drupal way'):
function user_validate_picture(&$form, &$form_state) {
// If required, validate the uploaded picture.
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);
// Save the file as a temporary file.
$file = file_save_upload('picture_upload', $validators);
if ($file === FALSE) {
form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
}
elseif ($file !== NULL) {
$form_state['values']['picture_upload'] = $file;
}
}
That function is added to the $form['#validate'] array like so:
$form['#validate'][] = 'user_validate_picture'

Saving nodes with a filefield

I'm in the progress of creating a bulk upload function for a Drupal site. Using flash I'm able to upload the files to a specific url that then handles the files. What I want to do, is not just to upload the files, but create a node of a specific type with the file saved to a filefield that has been setup with CCK. Since these are audio files, it's important that filefield handles the files, so addition meta data can be provided with the getid3 module.
Now I've looked through some of the code as I wasn't able to find an API documentation, but it's not clear at all how I should handle this. Ideally I could just pass the file to a function and just use the data returned when saving the node, but I haven't been able to find that function.
If any one has experience with this I would apreciate some pointers on how to approach this matter.
I had to do something similar some weeks ago and ended up adapting some functionality from the Remote File module, especially the remote_file_cck_attach_file() function. It uses the field_file_save_file() function from the filefield module, which might be the function you're looking for.
In my case, the files are fetched from several remote locations and stored temporarily using file_save_data(). Attaching them to a CCK filefield happens on hook_nodeapi() presave, using the following:
public static function attachAsCCKField(&$node, $filepath, $fieldname, $index=0) {
// Grab the filefield definition
$field = content_fields($fieldname, $node->type);
$validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
$fieldFileDirectory = filefield_widget_file_path($field);
// This path does not necessarily exist already, so make sure it is available
self::verifyPath($fieldFileDirectory);
$file = field_file_save_file($filepath, $validators, $fieldFileDirectory);
// Is the CCK field array already available in the node object?
if (!is_array($node->$fieldname)) {
// No, add a stub
$node->$fieldname=array();
}
$node->{$fieldname}[$index] = $file;
}
$filepath is the path to the file that should be attached, $fieldname is the internal name of the filefield instance to use within the node and $index would be the 0 based index of the attached file in case of multiple field entries.
The function ended up within a utility class, hence the class syntax for the verifyPath() call. The call just ensures that the target directory is available:
public static function verifyPath($path) {
if (!file_check_directory($path, FILE_CREATE_DIRECTORY)) {
throw new RuntimeException('The path "' . $path . '" is not valid (not creatable, not writeable?).');
}
}
That did it for me - everything else happens on node saving automatically.
I have not used the getid3 module yet, so I have no idea if it would play along with this way of doing it. Also, I had no need to add additional information/attributes to the filefield, so maybe you'd have to put some more information into the field array than just the file returned by field_file_save_file(). Anyways, hope this helps and good luck.
I have done something whith imagefield which worked, I think the structure has to be right otherwise it won't work. It took a lot of trial and error. This is is what I populated the imagefield with.
$image['data'] =array(
'title' => $media_reference_attributes->getNamedItem("source")->value,
'description' => $description,
'alt' => "",);
$image['width'] = $width;
$image['height'] = $height;
$image['mimetype'] = $mime_type
$image['uid'] = 1;
$image['status'] = 1;
$image['fid'] = $fid;
$image['filesize'] = $file->filesize;
$image['nid'] = $id;
$image['filename'] = $url;
$image['timestamp'] = $file->timestamp;
$image['filepath'] = $file_path;
Hope this is of some help.
You might want to look at Image FUpload if you need a look at integrating the flash upload.
To push the files on to another server while still handling them through Drupal sounds a little like the CDN space, maybe look at the behavior in the CDN or CDN2 projects?
If you find a clear solution please come back and post it!

Resources