Zend_Progressbar + JQuery + uploading a video - php

I would like to show a dynamic progressbar in my applciation while uploading a video (*.flv format). I searched on the Web for more than 2 hours but I can't find any tutorial to guide me through this process.
What I have so far:
script that uploads a video
jQuery library included in the section
But what to do next? Here is the controller action for uploading a video I use:
public function uploadPublicVideoAction()
{
$request = $this->getRequest();
$media = $this->_getTable('Media');
$form = $this->_getForm('UploadPublicVideo',
$this->_helper->url('upload-public-video'));
// if POST data has been submitted
if ($request->isPost()) {
// if the UploadPublicVideo form has been submitted and the submitted data is valid
if (isset($_POST['upload_public_video']) && $form->isValid($_POST)) {
$data = $form->getValues();
$data['user_id'] = $this->view->identity->id;
$ext = end(explode('.', $form->video->getFileName()));
$dbTrans = false;
try {
$db = $this->_getDb();
$dbTrans = $db->beginTransaction();
$data['type'] = 'video';
$data['status'] = 'public';
$paths = $media->add($data, $ext);
if (file_exists($paths[0])) {
unlink($paths[0]);
}
if (file_exists($paths[1])) {
unlink($paths[1]);
}
// add filter for renaming the uploaded photo
$form->video->addFilter('Rename',
array('target' => $paths[0],
'overwrite' => true));
// upload the video
$form->video->receive();
// create a thumbnail
//$this->_helper->FlvThumbnail($path[0], $path[1]);
$db->commit();
$form->reset();
$this->view->success = 'Public video successfully uploaded';
} catch (Exception $e) {
if (true === $dbTrans) {
$db->rollBack();
}
$this->view->error = $e->getMessage();
}
}
}
$this->view->headTitle('Upload Public Video');
$this->view->form = $form;
}
Can anyone show me a simple way to use Zend_Progressbar and jQuery together to achieve a dynamic upload progressbar?

You can do either long (comet) or short polling (ajax) to achieve the desired effect. With the former I would suggest making the request in an iFrame and having your code write out JS which will get executed as they come in, with the latter just do something like:
var pollingId = window.setInterval(poll, 250);
function poll(){
//make an AJAX request, do something with it (like update your progress bar).
if(done){
window.clearInterval(pollingId);
}
}

Related

I get "500 Backend Error" and "400 invalidMetadata" from youtube-api

I use PHP to insert/update the title and description of our video by using youtube-api and I get some problems with it.
1.
When I insert/update title and description of video by using zh-Hant or zh-Hans, I get "500 Backend Error."
However it works when I change zh-Hant and zh-Hans to zh-tw and zh-cn.
500 Backend Error
2.
I get "400 invalidMetadata" when I update a video title by using Italian(it).
I have no idea about this because it's all fine in others languages and it also fine in update video description by using Italian.
400 invalidMetadata
How can I fix these problems?
Here is my code:
public function __construct()
{
$client = new \Google_Client();
$client->setAuthConfig(storage_path('key/youtube_key/client_secret.json'));
$client->setApplicationName("String System");
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl');
$client->setAccessType('offline');
$client->setAccessToken(Cache::get('google_auth_token'));
$this->client = $client;
}
public function youtubeService($stringKey, $stringValue, $language)
{
$this->service = new \Google_Service_YouTube($this->client);
$this->stringKey = $stringKey;
$this->stringValue = $stringValue;
$this->language = $language;
$key = explode('_', $this->stringKey);
if (3 != count($key)) {
return;
}
list($videoName, $videoID, $type) = $key;
$this->videoName= $videoName;
$this->videoID = $videoID;
switch ($type) {
case 'title':
$this->updateTitle();
break;
case 'description':
$this->updateDesc();
break;
}
return;
}
private function updateTitle()
{
// get video list by video ID
$video = $this->service->videos->listVideos(
'snippet,localizations',
['id' => $this->videoID]
);
$videoInfo = $video->items[0];
// set video title of language
if (isset($videoInfo->localizations[$this->language])) {
$videoInfo->localizations[$this->language]->title =
$this->stringValue;
// check default language
if ($this->language === $videoInfo->snippet->defaultLanguage) {
$videoInfo->snippet->title = $this->stringValue;
}
} else {
$videoInfo->localizations[$this->language] = [
'title' => $this->stringValue,
'description' => 'description'
];
}
try {
// update video information
$this->service->videos->update(
'snippet,localizations',
$videoInfo
);
} catch (Exception $e) {
// do nothing and continue
}
return;
}
private function updateDesc()
{
// get video list by video ID
$video = $this->service->videos->listVideos(
'snippet,localizations',
['id' => $this->videoID]
);
$videoInfo = $video->items[0];
// set video description of language
if (isset($videoInfo->localizations[$this->language])) {
$videoInfo->localizations[$this->language]->description =
$this->stringValue;
// check default language
if ($this->language === $videoInfo->snippet->defaultLanguage) {
$videoInfo->snippet->description = $this->stringValue;
}
} else {
$videoInfo->localizations[$this->language] = [
'title' => 'title',
'description' => $this->stringValue
];
}
try {
// update video information
$this->service->videos->update(
'snippet,localizations',
$videoInfo
);
} catch (Exception $e) {
// do nothing and continue
}
return;
}
It seems that the language that you used (zh-Hant & zh-Hans) is not supported as of the moment.
To verify whether a language is supported or not, you may utilize i18nLanguages.list API. Here's a sample request using API explorer.
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.i18nLanguages.list?part=snippet&_h=1&

naming a file after submitting a form in Symfony

I am working on a form which accepts some user input and an image file, the submission part and the data getting entered into the database is working fine but I am stuck at how to name a file once it is uploaded, right now this is what i see as an image name in database C:\wamp2.5\tmp\phpF360.tmp which obviously is not correct.
This is what my controller looks like DefaultController.php
public function createBlogAction(Request $request)
{
$post = new Post();
$form = $this->createForm(new PostCreate(), $post);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$post->upload();
$post->setDate(date_create(date('Y-m-d H:i:s')));
$post->setAuthor('ClickTeck');
$em->persist($post);
$em->flush();
$this->get('session')->getFlashBag()->add(
'notice',
'Success'
);
}
return $this->render('BlogBundle:Default:blog-create.html.twig', array(
'form' => $form->createView()
)
);
}
This is what my upload() looks like inside Entity/Post.php which is uploading the file and moving it into the folder, the file name that I see in a folder is correct however now the one that goes into the database
public function upload()
{
if (null === $this->getImage()) {
return;
}
// I might be wrong, but I feel it is here that i need to name the file
$this->getImage()->move(
$this->getUploadRootDir(),
$this->getImage()->getClientOriginalName()
);
$this->path = $this->getUploadDir();
$this->file = null;
}
I will really appreciate if someone can push me in right direction, I just need to name the file, a name which gets assigned to the image in database and the file should get uploaded with the same name as well.
UPDATE
I managed to get it to work using the following function, not sure if this is the best practice but it did work, i would love to hear from others on this. please do not provide any links, if you can refine what has already been done that would be great.
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->getImage()) {
return;
}
$dirpath = $this->getUploadRootDir();
$image = $this->getImage()->getClientOriginalName();
$ext = $this->getImage()->guessExtension();
$name = substr($image, 0, - strlen($ext));
$i = 1;
while(file_exists($dirpath . '/' . $image)) {
$image = $name . '-' . $i .'.'. $ext;
$i++;
}
$this->getImage()->move($dirpath,$image);
$this->image = $image;
$this->path = $this->getUploadDir();
$this->file = null;
}
This topic from documentation may help you : http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
In addition, you should not put your upload function in the controller but rather use Doctrine events (Lifecycle callbacks) to call your function automatically.
as per suggestion of #theofabry you can check symfony2 documentation How to handle File Uploads with Doctrine, Controller must be thin as much as possible and try to do upload with Doctrine Events.
If you want to continue with your logic you may try following code, I have not tested yet...so please be careful.
// set the path property to the filename where you'ved saved the file
$this->path = $this->file->getClientOriginalName();
instead of
$this->path = $this->getUploadDir();

How to make a fast ajax live search

Hi, im trying to do a ajax live search. It work`s, but i want it to be fast. Currently i`m processing the html by php, but even if i change the processing to js and only get the data from php it only improves my search from 2.1 to 1.8 seconds (this is the request time, but it takes 4/5 seconds for the data to appear)
Heres my code:
$("#searchfield").change(function() {
term = $(this).val();
if (searchReq != false) {
searchReq.abort();
}
searchReq = $.get("/searchModal.php", {
term : term
}).done(function(data) {
$("#liveSearch").html(data);
});
});
EDIT:
php code:
search.php:
$files = filecontroller::search($term);
file controller:
public static function search($term, $by = false, $order = false) {
connection::connect();
$files = ($by && $order && validation::filesOrder($by, $order)) ? file::Search($term, $by, $order) : file::Search($term);
return $files;
}
File model:
public static function Search($term, $by = 'date', $order = 'DESC') {
$session_id = $_SESSION["user_id"];
$term = mysql_real_escape_string($term);
$query = mysql_query("SELECT * FROM files WHERE idUser = '$session_id' AND (name LIKE '%$term%' OR description LIKE '%$term%') ORDER BY $by $order");
$files = self::CreateFromDb($query);
return $files;
}
private static function CreateFromDb($query) {
GLOBAL $imgDir; // just get the img dir from a config file
GLOBAL $userDir; // same
$files = array();
while ($row = mysql_fetch_assoc($query)) {
$file = new File();
$file -> type = $row['type'];
$file -> idFile = $row['idFile'];
$file -> user = $row['idUser'];
$file -> gallery = $row['idGallery'];
$file -> name = htmlspecialchars($row['name']);
$file -> description = htmlspecialchars($row['description']);
$file -> date = $file -> timecheck($row['date']);
$file -> size['kb'] = $row['size'];
$file -> galleryName = Gallery::getName($file -> gallery);
$files[] = $file;
}
return $files;
}
Is there anyway to improve it? Im testing in local.
There are some issues with your code, but nothing obvious.
Some starting points:
The best way to find what's slow is probably to check profiling in PHP.
Another thing is that you're using LIKE "%x%" which will be slow if your user has lots of files (seems unlikely, but who knows). Check the MySQL slow query log.
You're also doing some disk access, but it shouldn't be this slow either - unless something strange is going on inside Gallery::getName or timecheck.
Note that the mysql extension has been deprecated. This has nothing to do with speed though, it's just outdated.
ANSWER
.change has a delay, for real time results its better to use .keyup. I cme up using a timeout to make the request only when user stop typing:
var searchTimeout;
var searchReq;
$("#searchfield").on('keyup', function() {
term = $(this).val();
if (searchTimeout) {
clearTimeout(searchTimeout);
}
if (searchReq) {
searchReq.abort();
}
searchTimeout = setTimeout(function(){
if (term.length > 2) {
searchController(term).then(function(data) {
$("#liveSearch").html(data);
});
}
else {
$("#liveSearch").html("");
}
},500);
});
function searchController(term) {
searchReq = $.ajax({
type : "GET",
url : "/searchModal.php",
data : {
term : term
},
async : true,
context : this,
beforeSend : function() {
},
complete : function() {
}
});
return searchReq;
}
Its still slow compared to facebook, and other big sites. I guess the only way to acess it fast would be with a great server or cached results (i tried to just echo an string without bd requests and its slow too).

How to load an sql dump using symfony

I'm trying to make a user friendly way of testing via lime in symfony 1. I want to load a specific sql dump for each test I write (if required). The problem I face is that I don't know how to make dump loading independent of database type. Currently I'm using the shell exec() command. Here is the code :
public function loadSql()
{
$this->diag("Loading dump...");
if ($this->_sql_is_set)
{
if (file_exists($this->_getSqlPath()))
{
$this->_emptyDataBase();
$options = $this->_connection_manager->connection()->getOptions();
$dsn_parts = $this->_connection_manager->parsePdoDsn($options['dsn']);
exec("mysql -u{$options['username']} -p{$options['password']} {$dsn_parts['dbname']} < {$this->_getSqlPath()}");
return $this;
}
else
{
$this->error("Nothing to load : sql file was not found in ".$this->_getDataDir());
exit;
}
}
else
{
$this->error("Nothing to load : sql dump was not set");
exit;
}
}
$this->_connection_manager is an instance of Doctrine_Manager. Any help will with that?
Try with something like that:
public function loadSqlFiles(sfEvent $event)
{
$task = $event->getSubject();
$taskName = $task->getName();
if ($taskName == 'insert-sql') {
$conn = Doctrine_Manager::connection();
$filesPath = sfConfig::get('sf_data_dir') . '/sql/full-data';
// get all files
$files = sfFinder::type('file')->sort_by_name()->name('*.sql')->in($filesPath);
foreach ($files as $file) {
$task->logSection('custom-sql', sprintf('Inserting custom sql file (%s)', $file));
$res = $conn->getDbh()->exec(file_get_contents($file));
}
}
}

jQuery Fileupload filter display according to mySQL query

Hi i have successfully saved to mySQL database the files uplaoded using jQuery-PHP FileUpload with the answer from this thread as guide. Now my questiion is, is it possible to only just show the images from my database according to the users who uploaded the imgs? since i also save the users along with the filename.? I dont have idea on how to do it, or whant and where to insert the codes, or is it possible.
EDITED:
I have now idea where it initialize the loading of image
protected function get_file_object($file_name) {
if ($this->is_valid_file_object($file_name)) {
$file = new stdClass();
$file->name = $file_name;
$file->size = $this->get_file_size(
$this->get_upload_path($file_name)
);
$file->url = $this->get_download_url($file->name);
foreach($this->options['image_versions'] as $version => $options) {
if (!empty($version)) {
if (is_file($this->get_upload_path($file_name, $version))) {
$file->{$version.'_url'} = $this->get_download_url(
$file->name,
$version
);
}
}
}
$this->set_file_delete_properties($file);
return $file;
}
return null;
}
Now i want to insert this mySql query which filter the images that will only show, but i don't know how.
SELECT desc FROM images WHERE userid=1

Categories