Need Help Merging Template Chatbox with php - javascript

I've recently purchased a template from themeforest and it has a perfect chat template that i need to merge with php/ajax? Im trying to make it so rather than just showing on the chatbox until i refresh, it will send to php file and upload to database, same for refreshing chats, so if anyone sends a message it comes up as well.
<?php
if (isset($_GET['chatMessage'])){
session_start();
require_once("functions.php");
$ChatMessage = htmlspecialchars($_GET['chatMessage']);
if (($ChatMessage != "") && (strlen($ChatMessage) < 255)){
$statement = $MySQL->prepare("INSERT INTO `chatbox` VALUES (NULL, ?, ?, ?)");
$statement->bind_param("isi", $_SESSION['memberID'], $ChatMessage, time());
$statement->execute();
}
}
?>
This above is the sendchat.php
This below is the getchat.php that has previously worked on my old website:
$statement = $MySQL->query("SELECT * FROM `chatbox` ORDER BY `ID` DESC LIMIT 20");
while ($Chat = $statement->fetch_assoc()){
$MemberID = $Chat['MemberID'];
$ChatMessage = $Chat['ChatMessage'];
$Time = time_ago($Chat['TimeStamp']);
$ChatClass = $MemberID == $_SESSION['memberID'] ? 'chatui-talk-msg' : 'chatui-talk-msg chatui-talk-msg-highlight themed-border';
echo "
<li class=\"chatui-talk-msg\">
<img src=\"img/placeholders/avatars/avatar6.jpg\" alt=\"Avatar\" class=\"img-circle chatui-talk-msg-avatar\"> $ChatMessage
</li>";
}
?>
This was also the javascript used on my old website that worked as well:
function startChatBox() {
setInterval(function() {
refreshShouts();
}, 1500);
}
function sendShout() {
var chatRequest = new XMLHttpRequest();
var shoutMessage = document.getElementById('chatui-message').value;
chatRequest.onreadystatechange = function() {
if (chatRequest.readyState == 4 && chatRequest.status == 200) {}
}, chatRequest.open("GET", "sendChat.php?chatMessage=" + encodeURIComponent(shoutMessage), true);
chatRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
chatRequest.send();
document.getElementById('chatui-message').value = "";
refreshShouts();
}
function refreshShouts() {
$("#chatBox").load("inc/getChat.php");
}
I Realise there is alot of code here but i am very confused as to what i could do to achieve my goal here. The code below is the javascript used on the template to print chats to the screen until you refresh:
/*
* Document : readyChat.js
* Author : pixelcave
* Description: Custom javascript code used in Chat page
*/
var ReadyChat = function() {
var chatHeight = 600; // Default chat container height in large screens
var chatHeightSmall = 300; // Default chat components (talk & people) height in small screens
/* Cache some often used variables */
var chatCon = $('.chatui-container');
var chatTalk = $('.chatui-talk');
var chatTalkScroll = $('.chatui-talk-scroll');
var chatPeople = $('.chatui-people');
var chatPeopleScroll = $('.chatui-people-scroll');
var chatInput = $('.chatui-input');
var chatMsg = '';
/* Updates chat UI components height */
var updateChatHeight = function(){
var windowW = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
if (windowW < 768) { // On small screens
chatCon
.css('height', (chatHeightSmall * 2) + chatInput.outerHeight());
chatTalk
.add(chatTalkScroll)
.add(chatTalkScroll.parent())
.add(chatPeople)
.add(chatPeopleScroll)
.add(chatPeopleScroll.parent())
.css('height', chatHeightSmall);
}
else if (windowW > 767) { // On large screens
chatCon
.css('height', chatHeight);
chatTalk
.add(chatTalkScroll)
.add(chatTalkScroll.parent())
.css('height', chatHeight - chatInput.outerHeight());
chatPeople
.add(chatPeopleScroll)
.add(chatPeopleScroll.parent())
.css('height', chatHeight);
}
};
return {
init: function() {
// Initialize default chat height
updateChatHeight();
// Update chat UI components height on window resize
$(window).resize(function(){ updateChatHeight(); });
// Initialize scrolling on chat talk + people
chatTalkScroll
.slimScroll({
height: chatTalk.outerHeight(),
color: '#000',
size: '3px',
position: 'right',
touchScrollStep: 100
});
chatPeopleScroll
.slimScroll({
height: chatPeople.outerHeight(),
color: '#fff',
size: '3px',
position: 'right',
touchScrollStep: 100
});
// When the chat message form is submitted
chatInput
.find('form')
.submit(function(e){
// Get text from message input
chatMsg = chatInput.find('#chatui-message').val();
// If the user typed a message
if (chatMsg) {
// Add it to the message list
chatTalk
.find('ul')
.append('<li class="chatui-talk-msg chatui-talk-msg-highlight themed-border animation-expandUp">'
+ '<img src="img/placeholders/avatars/avatar2.jpg" alt="Avatar" class="img-circle chatui-talk-msg-avatar">'
+ $('<div />').text(chatMsg).html()
+ '</li>');
// Scroll the message list to the bottom
chatTalkScroll
.animate({ scrollTop: chatTalkScroll[0].scrollHeight },150);
// Reset the message input
chatInput
.find('#chatui-message')
.val('');
}
// Don't submit the message form
e.preventDefault();
});
}
};
}();
If anyone is able to help me, it would be greatly appreciated. Thank you

Related

Uploading an image to my website causes a 500 error

I tried to upload an image in my site and I had made this piece of code that worked very well but now it's going as I planned I tried to modify the url
url: 'ajax/uploadifive.php' in url: './ajax/uploadifive.php' even in url: 'https://www.nanaje.com/ajax/uploadifive.php' but nothing works I don't know why
Here is the Ajax jQuery code
<script type="text/javascript">
$(document).ready(function(){
var _URL = window.URL || window.webkitURL
var bar = $('.bar')
var percent = $('.percent')
var progress_bar_id = '#progress-wrp' //ID of an element for response output
var url = $('#url').val() // Url of the page gallery of image
var ajaxCall
$('#file').change(function () {
var file = $(this)[0].files[0]
img = new Image()
var imgwidth = 0
var imgheight = 0
var minwidth = 640 // Minimum width required W: 640
var minheight = 320 // Minimum length required H: 320
img.src = _URL.createObjectURL(file)
img.onload = function() {
imgwidth = this.width // Original Image Width
imgheight = this.height // Original Length Of The Image
if (imgwidth >= minwidth && imgheight >= minheight) {
var formData = new FormData()
formData.append('fileToUpload', $('#file')[0].files[0])
ajaxCall = $.ajax({
url: 'ajax/uploadifive.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
beforeSend: function () {
$('.progress-bar').show()
$(progress_bar_id + " .load_file").html('<img src="assets/img/ajax-loader.gif" style="width: 15px; height: 15px;"/>')
$(progress_bar_id + " .cancel").html('Cancel')
},
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr()
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0
var position = event.loaded || event.position
var total = event.total
var total_file = Math.round((total / 1024) /1024)
var total_file_kb = Math.round(total / 1024)
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100)
}
//update progressbar
$(progress_bar_id +" .progress-bar").attr("value", percent)
$(progress_bar_id + " .status").text(percent +"%")
$(progress_bar_id + " .status_from").text("from")
if(total_file != 0) {
$(progress_bar_id + " .status_total").text(total_file+'Mb')
} else {
$(progress_bar_id + " .status_total").text(total_file_kb+'Kb')
}
}, true)
}
return xhr
},
success: function (response) {
if(response.status == 1) {
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").hide()
window.location = url
} else {
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").text('Failed')
swal({
text: response.returnText,
icon: "info",
})
return false
}
}
})
} else {
swal({
text: "Dezole, imaj sa a twò piti oswa twò gwo kalite, tanpri eseye ankò ak yon lòt imaj ki gen pi bon kalite. Nou sijere ke ou soumèt vèsyon orijinal la, kote ou fe li ak pwòp telefon ou, ki pat janm te redwi oswa chanje.",
icon: "info",
})
return false
}
}
img.onerror = function() {
$("#response").text("fichier a pa bon " + file.type)
}
})
$(document).on('click','.cancel', function() {
ajaxCall.abort()
$(progress_bar_id + " .load_file").hide()
$(progress_bar_id + " .cancel").text('Failed')
})
})
</script>
and here is the php code
<?php
session_start();
require_once '../class/Database.php';
require_once '../includes/functions.php';
require_once '../includes/constants.php';
require_once '../src/interventionImage/autoload.php';
use Intervention\Image\ImageManager;
// We create the instance so that we can use the image
$manager = new ImageManager();
/*
UploadiFive
Copyright (c) 2012 applications réactives, Ronnie Garcia
*/
$returnText = "";
$uploadOk = 1;
// Set the download directory
// We define the user's Id
$id = $_SESSION['user_id'];
$dir_img = '../photos/m/'.$id.'/i';
$uploadDir = "$dir_img/oi"; // Place of destination of the original image
// $uploadDirProfile = "$dir_img/oip"; // Place of destination of the original image
$uploadDirImgHomeProfile = "$dir_img/ihp"; // Place of destination of the img_home_profile
$uploadDirAvatar = "$dir_img/ai"; // Place of destination of the avatar image
$uploadDirImgProfileExtra = "$dir_img/ipe"; // Place of destination of the avatar image
$uploadDirImgGallery = "$dir_img/ig"; // Place of destination of the avatar image
$uploadDirImgMessage = "$dir_img/im"; // Place of destination of the avatar image
$uploadDirStandardProfile = "$dir_img/sp"; // Place of destination of the avatar image
// Let's test the fioxtension
$nomFichier = pathinfo($_FILES['fileToUpload']['name']); //nom complet de l'image avec son extension
$nameFile = $nomFichier['basename']; //nom complet de l'image avec son extension
$extension_file = $nomFichier['extension']; // L'extension de l'image
$field = 'nfo';
$value = $nameFile;
$table = 'pictures';
if(is_already_in_use($field, $value, $table)) {
$returnText = "You have already put this image on the site.";
$uploadOk = 0;
} else {
// Define allowed file extensions
$fileTypes = ['jpg', 'jpeg']; // Allowed file extensions
$verifyToken = md5(uniqid(rand(), true));
$targetPath = $uploadDir; // Place or store the image on the site server
// $targetPathProfile = $uploadDirProfile; // Place or store the image on the site server
$targetPathImgHomeProfile = $uploadDirImgHomeProfile; // Place or store the image on the site server
$targetPathAvatar = $uploadDirAvatar; // Place or store the image on the site server
$targetPathImgProfileExtra = $uploadDirImgProfileExtra; // Place or store the image on the site server
$targetPathImgGallery = $uploadDirImgGallery; // Place or store the image on the site server
$targetPathImgMessage = $uploadDirImgMessage; // Place or store the image on the site server
$targetPathStandardProfile = $uploadDirStandardProfile; // Place or store the image on the site server
$randomFileName = $verifyToken.'.'.$extension_file;
if (!empty($_FILES) && $verifyToken) {
$tempFile = $_FILES['fileToUpload']['tmp_name'];
$targetFile = rtrim($targetPath,'/') . '/' . $randomFileName; // The place where the image will be stored
if(!file_exists($targetPath)) {
mkdir("$dir_img/oi", 0755, true);
}
if (in_array(strtolower($extension_file), $fileTypes)) {
// We take the current image...
$tempFileOriginal = $manager->make($tempFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400 300X300
$tempFileOriginal->orientate()->text('nanaje.com', 720, 1000, function($font) {
$font->file('../assets/img/Texturina-Italic-VariableFont_opsz,wght.ttf');
$font->size(48);
$font->color('#be0210');
})->interlace(true)->save($targetFile, 60);
// $tempFileOriginal->orientate()->insert($img_logo, 'bottom-right', -10, -100)->interlace(true)->save($targetFile, 60);
// save the file, ie the original image
if ($tempFileOriginal) {
$filename = $targetFile;
list($width, $height, $type, $attr) = getimagesize($filename);
if ($width < 640 && $height < 320) {
unlink($filename);
$returnText = "Sorry, this image is too small or of too low a quality, please try again with another image of better quality. We suggest that you submit the original version of your recent photo that has never been reduced or altered.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
$returnText;
} else {
/**
* Create the targetPathProfile for your profile for modal box
*/
// We save the modal box resize image in the file
$thumbnailPathProfile = rtrim($targetPathProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathProfile)) {
mkdir("$targetPathProfile", 0755, true);
}
$width = 900; // Maximum width
$height = 900; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// We check which height or width we should keep...
($img->height() > $img->width()) ? $width = null : $height = null;
$img->orientate()->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
})->interlace(true)->save($thumbnailPathProfile, 60); //900x900
/** END */
/**
* Create the img_home_profile
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgHomeProfile = rtrim($targetPathImgHomeProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgHomeProfile)) {
mkdir("$targetPathImgHomeProfile", 0755, true);
}
$width = 218; // Maximum width
$height = 218; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height)->interlace(true)->save($thumbnailPathImgHomeProfile, 60); /90089008
$img->orientate()->resize($width, $height)->interlace(true)->save($thumbnailPathImgHomeProfile, 60); //218x218
/** END */
/**
* Create the Avatar Profile
*/
// We save the AVATAR resize image in the file
$thumbnailPathAvatar = rtrim($targetPathAvatar,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathAvatar)) {
mkdir("$targetPathAvatar", 0755, true);
}
$width = 500; // Maximum width
$height = 500; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// We check which height or width we should keep...
($img->height() > $img->width()) ? $width = null : $height = null;
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height, function ($constraint) {
$img->orientate()->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
})->interlace(true)->save($thumbnailPathAvatar, 60); //500x500
/** END */
/**
* Create the Avatar Profile Extra
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgProfileExtra = rtrim($targetPathImgProfileExtra,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgProfileExtra)) {
mkdir("$targetPathImgProfileExtra", 0755, true);
}
$width = 80; // Maximum width
$height = 80; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgProfileExtra, 60); //80x80
/** END */
/**
* Create the Avatar Profile Gallery
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgGallery = rtrim($targetPathImgGallery,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgGallery)) {
mkdir("$targetPathImgGallery", 0755, true);
}
$width = 190; // Maximum width
$height = 190; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
// $img->orientate()->insert($img_logo, 'bottom-right', -10, -100)->resize($width, $height)->interlace(true)->save($thumbnailPathImgGallery, 60); //80x80
$img->orientate()->resize($width, $height)->interlace(true)->save($thumbnailPathImgGallery, 60); //80x80
/** END */
/**
* Create the Avatar Profile Message
*/
// We save the AVATAR resize image in the file
$thumbnailPathImgMessage = rtrim($targetPathImgMessage,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathImgMessage)) {
mkdir("$targetPathImgMessage", 0755, true);
}
$width = 32; // Maximum width
$height = 32; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// $img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgMessage, 60); //32x32
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathImgMessage, 60); //32x32
/** END */
/**
* Create the img_home_profile standard_home
*/
// We save the AVATAR resize image in the file
$thumbnailPathStandardProfile = rtrim($targetPathStandardProfile,'/') . '/' . $randomFileName; // The place where the image will be stored
// We check if this path exists, if not, we create it
if (!file_exists($thumbnailPathStandardProfile)) {
mkdir("$targetPathStandardProfile", 0755, true);
}
$width = 320; // Maximum width
$height = 240; // Maximum height
// We take the current image...
$img = $manager->make($targetFile);
// Img Logo
// $img_logo = $manager->make(WEBSITE_NAME_URL.'/assets/img/Logopit_1571868283797.png')->resize(700, 400); // 700X400
$img->orientate()->fit($width, $height)->interlace(true)->save($thumbnailPathStandardProfile, 60); //32x32
/** END */
unlink($filename);
$q = $db->prepare("INSERT INTO pictures(io, nfo, ihp, ai, ipe, ig, im, sp, rules, picture_added, ip, user_id)
VALUES(:io, :nfo, :ihp, :ai, :ipe, :ig, :im, :sp, :rules, now(), :ip, :user_id)");
$q->execute([
'io' => $thumbnailPathProfile,
'nfo' => $nameFile,
'ihp' => $thumbnailPathImgHomeProfile,
'ai' => $thumbnailPathAvatar,
'ipe' => $thumbnailPathImgProfileExtra,
'ig' => $thumbnailPathImgGallery,
'im' => $thumbnailPathImgMessage,
'sp' => $thumbnailPathStandardProfile,
'rules' => '1',
'ip' => $_SERVER['REMOTE_ADDR'],
'user_id' => $id
]);
$picture_user_id = $db->lastInsertId();
if ($picture_user_id) {
$q = $db->prepare("SELECT id FROM pictures WHERE user_id = ? AND active_profile = ?");
$q->execute([get_session('user_id'), '2']);
$data = $q->fetch(PDO::FETCH_OBJ);
if (!$data) {
$q = $db->prepare("UPDATE pictures SET active_profile = ? WHERE id = ?");
$q->execute(['2', $picture_user_id]);
}
// End of the backup
$q = $db->prepare("SELECT user_id FROM notes_picture_personal WHERE user_id = ?");
$q->execute([$id]);
$data = $q->fetch(PDO::FETCH_OBJ);
// If this is the case we continue ...
if ($data) {
// Then we update the field of the database of the user ...
$q = $db->prepare("UPDATE notes_picture_personal SET notes_picture_perso = notes_picture_perso + 1 WHERE user_id = ?");
$q->execute([$id]);
} else {
// Write the number of fields that have inserted...
$q = $db->prepare("INSERT INTO notes_picture_personal(user_id, notes_picture_perso) VALUES(?, ?)");
$q->execute([$id, 1]);
// End of the backup
}
}
}
} else {
$returnText = "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}
} else {
$returnText = "Sorry, only JPG, JPEG files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
$returnText;
}
}
}
echo json_encode(array("status"=>$uploadOk,"returnText"=>$returnText));
?>
and here are the images of the error that is displayed
POST https://www.nanaje.com/ajax/uploadifive.php 500 jquery-3.3.1.min.js:
POST https://www.nanaje.com/ajax/uploadifive.php 500 jquery-3.3.1.min.js:

How to get JS variable value on one page passed back to another page in PHP

I currently have two pages coded in php one page is called upload.php and the other page is called processing.php.
in the processing.php I currently have some Javascript that is ran it’s purpose is to check a log file for a video encoding progress to get the percentage left. this variable is called “progress” (This works fine when using console.log on the processing.php and I can see the incrementing percentage) I need to be able to get this value back to my upload.php page so that I can dynamically update a progress bar with its current value.
I already have one part of the puzzle working and that's to show a progress bar of the file uploading.
I have included some of the JS code on my upload.php and the JS code using in the processing.php page.
One thing that I tried was to have the JS variable inserted into a PHP session variable on the processing.php page, then echo this session variable out on the upload.php.
I have included in my code snippets below my attempt at using sessions.
Upload.php
<?php session_start();?>
<?php
$formProvider = new VideoDetailsFormProvider($con);
echo $formProvider->createUploadForm();
?>
</div>
<script>
$("form").submit(function() {
$("#loadingModal").modal("show");
var $el = $("#loadingModal");
$form = $(this);
uploadVideo($form, $el);
});
function uploadVideo($form, $el){
var formdata = new FormData($form[0]); //formelement
var ajax= new XMLHttpRequest();
ajax.upload.addEventListener("progress", function(event){
var percent = Math.round(event.loaded /event.total) * 100;
$el.find('#progressBarUpload').width(percent+'%').html(percent+'%');
//console.log(percent);
});
//progress completed load event
ajax.addEventListener("load", function(event){
$el.find('#progressBarUpload').addClass('progress-bar bg-success').html('Upload completed...');
});
ajax.addEventListener("error", function(event){
$el.find('#status').innerhtml = "Upload Failed";
});
ajax.addEventListener("abort", function(event){
$el.find('#status').innerhtml = "Upload Aborted";
});
ajax.open("POST", "processing.php");
ajax.send(formdata);
}
Please wait. This might take a while.
<?php echo($_SESSION['convertProgress']);?>
<div class="progress">
<div id="progressBarUpload" class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Processing.php
<?php session_start();
$convertProgressTest = $_SESSION['convertProgress'];
?>
<script>
var _progress = function(i){
i++;
// THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
var logfile = 'uploads/videos/logs/output.txt';
/* (example requires dojo) */
$.post(logfile).then( function(content){
// AJAX success
var duration = 0, time = 0, progress = 0;
var resArr = [];
// get duration of source
var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
if( matches.length>0 ){
var rawDuration = matches[1];
// convert rawDuration from 00:00:00.00 to seconds.
var ar = rawDuration.split(":").reverse();
duration = parseFloat(ar[0]);
if (ar[1]) duration += parseInt(ar[1]) * 60;
if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;
// get the time
matches = content.match(/time=(.*?) bitrate/g);
console.log( matches );
if( matches.length>0 ){
var rawTime = matches.pop();
// needed if there is more than one match
if ($.isArray(rawTime)){
rawTime = rawTime.pop().replace('time=','').replace(' bitrate','');
} else {
rawTime = rawTime.replace('time=','').replace(' bitrate','');
}
// convert rawTime from 00:00:00.00 to seconds.
ar = rawTime.split(":").reverse();
time = parseFloat(ar[0]);
if (ar[1]) time += parseInt(ar[1]) * 60;
if (ar[2]) time += parseInt(ar[2]) * 60 * 60;
//calculate the progress
progress = Math.round((time/duration) * 100);
}
resArr['status'] = 200;
resArr['duration'] = duration;
resArr['current'] = time;
resArr['progress'] = progress;
console.log(resArr);
/* UPDATE YOUR PROGRESSBAR HERE with above values ... */
/* $("#progressBarconvert").width(progress+'%').html(progress+'%');
if(progress==100){
$("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
}*/
var convertProgress = progress;
if(progress==0 && i>20){
//TODO err - giving up after 8 sec. no progress - handle progress errors here
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
return;
} else if(progress<100){
setTimeout(function(){ _progress(i); }, 400);
}
} else if( content.indexOf('Permission denied') > -1) {
// TODO - err - ffmpeg is not executable ...
console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
}
},
function(err){
// AJAX error
if(i<20){
// retry
setTimeout(function(){ _progress(0); }, 400);
} else {
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
console.log( err );
}
return;
});
}
setTimeout(function(){ _progress(0); }, 800);
</script>
Since you dont want to leave upload.php you have to add return false; right after uploadVideo($form, $el);
Otherwise you trigger the upload asynchronously and go to progress.php synchronously(which means you leave upload.php)
You have 3 responsibilities here, so you could do it with 3 files:
upload.php - display the upload form
convert.php - do the conversion
progress.php - get the progress
In your convert.php you will need to add the line $_SESSION['convertProgress'] = convertProgress;
In your upload.php you can update your progressbar now by:
$.ajax('progress.php', function(content) {
// set element value etc...
});
As soon as you start the upload the File gets uploaded and converted by convert.php asynchronously. You can now trigger a JS-Timer, which does the above call to progress.php over and over until it reaches 100.
If you want to be able to do some errorhandling you can use JSON to pass more data back to your upload.php which calls progress.php.
PHP (example):
json_encode([
'progress' => 0,
'message' => '',
]);
JS decode:
JSON.parse(<content of progress.php>)
I have managed to resolve this now it's not pretty and it may not be the best way but it works for me, using #Pilan advice and help this is my workaround.
have 3 pages
The Update.php Page, The Processing.php Page and convertProgress.php, the convertProgress.php Page contains the the Javascript code mentioned at the beginning of my post. The upload.php contains the following.
var testing;
function beginUpload() {
$.ajax({
url: 'convertProgress.php',
type: 'POST',
//async: false,
data: {},
success: function (response) { //we got the response
if(response.progress){
testing = response.progress
console.log(testing);
}else {
beginUpload();
getProgress();
}
//var testing = response.progress;
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
});
//console.log(testing);
}
Upload.php also has the same javascript code as the convertProgress.php
<script>
function getProgress() {
var _progress = function (i) {
i++;
// THIS MUST BE THE PATH OF THE .txt FILE SPECIFIED IN [1] :
var logfile = 'uploads/videos/logs/output.txt';
/* (example requires dojo) */
$.post(logfile).then(function (content) {
// AJAX success
var duration = 0, time = 0, progress = 0;
var resArr = [];
// get duration of source
var matches = (content) ? content.match(/Duration: (.*?), start:/) : [];
if (matches.length > 0) {
var rawDuration = matches[1];
// convert rawDuration from 00:00:00.00 to seconds.
var ar = rawDuration.split(":").reverse();
duration = parseFloat(ar[0]);
if (ar[1]) duration += parseInt(ar[1]) * 60;
if (ar[2]) duration += parseInt(ar[2]) * 60 * 60;
// get the time
matches = content.match(/time=(.*?) bitrate/g);
console.log(matches);
if (matches.length > 0) {
var rawTime = matches.pop();
// needed if there is more than one match
if ($.isArray(rawTime)) {
rawTime = rawTime.pop().replace('time=', '').replace(' bitrate', '');
} else {
rawTime = rawTime.replace('time=', '').replace(' bitrate', '');
}
// convert rawTime from 00:00:00.00 to seconds.
ar = rawTime.split(":").reverse();
time = parseFloat(ar[0]);
if (ar[1]) time += parseInt(ar[1]) * 60;
if (ar[2]) time += parseInt(ar[2]) * 60 * 60;
//calculate the progress
progress = Math.round((time / duration) * 100);
}
resArr['status'] = 200;
resArr['duration'] = duration;
resArr['current'] = time;
resArr['progress'] = progress;
console.log(resArr);
/* UPDATE YOUR PROGRESSBAR HERE with above values ... */
$("#progressBarconvert").width(progress+'%').html(progress+'%');
if(progress==100){
$("#progressBarconvert").addClass('progress-bar bg-success').html('Conversion Completed...');
}
if (progress == 0 && i > 20) {
//TODO err - giving up after 8 sec. no progress - handle progress errors here
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
return;
} else if (progress < 100) {
setTimeout(function () {
_progress(i);
}, 400);
}
} else if (content.indexOf('Permission denied') > -1) {
// TODO - err - ffmpeg is not executable ...
console.log('{"status":-400, "error":"ffmpeg : Permission denied, either for ffmpeg or upload location ..." }');
}
},
function (err) {
// AJAX error
if (i < 20) {
// retry
setTimeout(function () {
_progress(0);
}, 400);
} else {
console.log('{"status":-400, "error":"there is no progress while we tried to encode the video" }');
console.log(err);
}
return;
});
}
setTimeout(function () {
_progress(0);
}, 800);
}
</script>
It's not pretty but it works for me. I hope this helps anyone that would like to get the conversion Progress from FFMPEG and populate a bootstrap Progress bar

upload fails with image greater than 800kb

I have a form where i can drag and drop an image into a canvas and then click an upload button to upload the file to the server. Below is my javascript file and php file. I cannot find where or why this will not allow me to upload something greater than 800kb? I believe its all failing in the php at if(file_put_contents($uploaddir.$randomName, $decodedData)) { but again i dont know why? The sql statment fails to by the way thats why i think its failing at that point in the php file. 32M is php max file size upload.
UPDATE... i removed anything to do with uploading with php in the php and only left echo $randomName.":uploaded successfully"; which now leads me to believe there is something wrong in the JS file at $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { for anything greater than 800kb (ish)
JS
$(document).ready(function() {
// Makes sure the dataTransfer information is sent when we
// Drop the item in the drop box.
jQuery.event.props.push('dataTransfer');
var z = -40;
// The number of images to display
var maxFiles = 1;
var errMessage = 0;
// Get all of the data URIs and put them in an array
var dataArray = [];
// Bind the drop event to the dropzone.
$('#drop-files').bind('drop', function(e) {
// Stop the default action, which is to redirect the page
// To the dropped file
var files = e.dataTransfer.files;
// Show the upload holder
$('#uploaded-holder').show();
$('#drop-files').hide();
// For each file
$.each(files, function(index, file) {
// Some error messaging
if (!files[index].type.match('image.*')) {
if(errMessage == 0) {
$('#drop-files').html('Hey! Images only');
++errMessage
}
else if(errMessage == 1) {
$('#drop-files').html('Stop it! Images only!');
++errMessage
}
else if(errMessage == 2) {
$('#drop-files').html("Can't you read?! Images only!");
++errMessage
}
else if(errMessage == 3) {
$('#drop-files').html("Fine! Keep dropping non-images.");
errMessage = 0;
}
return false;
}
// Check length of the total image elements
if($('#dropped-files > .image').length < maxFiles) {
// Change position of the upload button so it is centered
var imageWidths = ((220 + (40 * $('#dropped-files > .image').length)) / 2) - 20;
$('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'});
}
// Start a new instance of FileReader
var fileReader = new FileReader();
// When the filereader loads initiate a function
fileReader.onload = (function(file) {
return function(e) {
// Push the data URI into an array
dataArray.push({name : file.name, value : this.result});
// Move each image 40 more pixels across
z = z+40;
var image = this.result;
// Just some grammatical adjustments
if(dataArray.length == 1) {
$('#upload-button span').html("1 file to be uploaded");
} else {
$('#upload-button span').html(dataArray.length+" files to be uploaded");
}
// Place extra files in a list
if($('#dropped-files > .image').length < maxFiles) {
// Place the image inside the dropzone
$('#dropped-files').append('<div class="image" style="background: #fff url('+image+') no-repeat;background-size: cover;background-position: center center;"> </div>');
}
else {
$('#extra-files .number').html('+'+($('#file-list li').length + 1));
// Show the extra files dialogue
$('#extra-files').show();
// Start adding the file name to the file list
$('#extra-files #file-list ul').append('<li>'+file.name+'</li>');
}
};
})(files[index]);
// For data URI purposes
fileReader.readAsDataURL(file);
});
});
function restartFiles() {
// This is to set the loading bar back to its default state
$('#loading-bar .loading-color').css({'width' : '0%'});
$('#loading').css({'display' : 'none'});
$('#loading-content').html(' ');
// --------------------------------------------------------
// We need to remove all the images and li elements as
// appropriate. We'll also make the upload button disappear
$('#upload-button').hide();
$('#dropped-files > .image').remove();
$('#extra-files #file-list li').remove();
$('#extra-files').hide();
$('#uploaded-holder').hide();
$('#drop-files').show();
// And finally, empty the array/set z to -40
dataArray.length = 0;
z = -40;
return false;
}
$('#upload-button .upload').click(function() {
$("#loading").show();
var totalPercent = 100 / dataArray.length;
var x = 0;
var y = 0;
$('#loading-content').html('Uploading '+dataArray[0].name);
$.each(dataArray, function(index, file) {
bla = $('#gpID').val();
$.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) {
var fileName = dataArray[index].name;
++x;
// Change the bar to represent how much has loaded
$('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'});
if(totalPercent*(x) == 100) {
// Show the upload is complete
$('#loading-content').html('Uploading Complete!');
// Reset everything when the loading is completed
setTimeout(restartFiles, 500);
} else if(totalPercent*(x) < 100) {
// Show that the files are uploading
$('#loading-content').html('Uploading '+fileName);
}
// Show a message showing the file URL.
var dataSplit = data.split(':');
if(dataSplit[1] == 'uploaded successfully') {
alert('Upload Was Successfull');
var realData = '<li>'+fileName+' '+dataSplit[1]+'</li>';
$('#drop-files').css({
'background' :'url(/mods/photogallery/photos/' + dataSplit[0] + ') no-repeat',
'background-size': 'cover',
'background-position' : 'center center'
});
$('#uploaded-files').append('<li>'+fileName+' '+dataSplit[1]+'</li>');
// Add things to local storage
if(window.localStorage.length == 0) {
y = 0;
} else {
y = window.localStorage.length;
}
window.localStorage.setItem(y, realData);
} else {
$('#uploaded-files').append('<li><a href="/mods/photogallery/photos/'+data+'. File Name: '+dataArray[index].name+'</li>');
}
});
});
return false;
});
// Just some styling for the drop file container.
$('#drop-files').bind('dragenter', function() {
$(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #bb2b2b'});
return false;
});
$('#drop-files').bind('drop', function() {
$(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'});
return false;
});
// For the file list
$('#extra-files .number').toggle(function() {
$('#file-list').show();
}, function() {
$('#file-list').hide();
});
$('#dropped-files #upload-button .delete').click(restartFiles);
// Append the localstorage the the uploaded files section
if(window.localStorage.length > 0) {
$('#uploaded-files').show();
for (var t = 0; t < window.localStorage.length; t++) {
var key = window.localStorage.key(t);
var value = window.localStorage[key];
// Append the list items
if(value != undefined || value != '') {
$('#uploaded-files').append(value);
}
}
} else {
$('#uploaded-files').hide();
}
});
PHP
// We're putting all our files in a directory.
$uploaddir = '../photos/';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
$gpID = $_GET['gpID'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
// You can use the name given, or create a random name.
// We will create a random name!
$randomName = $gpID.'.'.$mime;
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
$sql = "UPDATE zmods_galleriesphotos SET gpFile = '$randomName' WHERE gpID = '$gpID'";
$rows = $db->query($sql);
echo $randomName.":uploaded successfully";
}
else {
echo "Something went wrong. Check that the file isn't corrupted";
}
Check the upload_max_filesize in your php.ini file (although it should be large enough by default)
Check the post_max_size as well
If you're uploading multiple files, then also check max_file_uploads
The fact that your sql is failing makes me wonder if this is a mysql problem and not a php problem. What is the SQL error that occurs?

textarea autogrow functionality jitters with every keystroke

I was playing around with the jquery autogrow plugin, which expands the height of the text automatically as the text needs it. The problem is that with every key down, the bottom border of the textarea jitters in a noticeable way. I'm not sure what the problem could be, so I'm going to go out on a limb and post the 132 lines of this GPL plugin here. Any hints where the problem could be or how to circumvent it?
/*
Auto Expanding Text Area (1.2.2) by Chrys Bader */
(function(jQuery) {
var self = null;
jQuery.fn.autogrow = function(o){
return this.each(function() {
new jQuery.autogrow(this, o);
});
};
/**
* The autogrow object.
*
* #constructor
* #name jQuery.autogrow
* #param Object e The textarea to create the autogrow for.
* #param Hash o A set of key/value pairs to set as configuration properties.
* #cat Plugins/autogrow
*/
jQuery.autogrow = function (e, o) {
this.options = o || {};
this.dummy = null;
this.interval = null;
this.line_height = this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
this.min_height = this.options.minHeight || parseInt(jQuery(e).css('min-height'));
this.max_height = this.options.maxHeight || parseInt(jQuery(e).css('max-height'));;
this.textarea = jQuery(e);
if(this.line_height == NaN) this.line_height = 0;
// Only one textarea activated at a time, the one being used
this.init();
};
jQuery.autogrow.fn = jQuery.autogrow.prototype = { autogrow: '1.2.2' };
jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
jQuery.autogrow.fn.extend({ init: function(){
var self = this;
this.textarea.css({overflow: 'hidden', display: 'block'});
this.textarea.bind('focus', function(){ self.startExpand() }).bind('blur', function() { self.stopExpand() });
this.checkExpand();
},
startExpand: function() {
var self = this;
this.interval = window.setInterval(function() { self.checkExpand()}, 400); },
stopExpand: function() { clearInterval(this.interval); },
checkExpand: function() {
if (this.dummy == null) {
this.dummy = jQuery('<div></div>');
this.dummy.css({
'font-size' : this.textarea.css('font-size'),
'font-family': this.textarea.css('font-family'),
'width' : this.textarea.css('width'),
'padding' : this.textarea.css('padding'),
'line-height': this.line_height + 'px',
'overflow-x' : 'hidden',
'position' : 'absolute',
'top' : 0,
'left' : -9999
}).appendTo('body');
}
// Strip HTML tags
var html = this.textarea.val().replace(/(<|>)/g,'');
// IE is different, as per usual
if ($.browser.msie){
html = html.replace(/\n/g, '<BR>new');
} else {
html = html.replace(/\n/g, '<br>new');
}
if (this.dummy.html() != html){
this.dummy.html(html);
if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height)){
this.textarea.css('overflow-y', 'auto');
} else {
this.textarea.css('overflow-y', 'hidden');
if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height())) {
this.textarea.animate({height: (this.dummy.height() + this.line_height) + 'px'}, 100);
}
}
}
}
});
})(jQuery);
In regard to jeerose's comment:
http://www.aclevercookie.com/aclevercookiecom-breached-problem-resolved/
It has been brought to my attention by
visitors that their virus protection
goes off when they come to this blog.
I investigated the matter and found
that harmful code had been injected
into the source of the site.
This has been resolved and measures
have been taken to increase the
security of the site.
Thanks for the report, and I apologize
for the alarm.
Which doesn't seem to be true. As my antivirus still fires when opening that site

Pretty Photo Set linking Issues

Yesterday a nice stack overflow user helped me to trigger the Jquery Prettyphoto Lightbox from a DIV element rather than an A element.
You can find that solution here
This works... Almost.
Pretty Photo looks for all the links that reference it and then compiles them into a slideshow of iframes. Normally when you click on a link it will open up the iframe lightbox corresponding to the link i clicked on.
However with this new DIV solution it is opening up to the first iframe link it finds on the page, rather than the link I click on.
This must obviously be happening because I have altered the javascript call code from
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto[iframes]']").prettyPhoto();
});
</script>
to
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("div[class^='prettyphoto[iframes]']").prettyPhoto();
});
</script>
I have been going through the other JS files but I am not a javascript programmer.
I am going to post the entire JS file. Maybe someone can see what javascript I need to change to make this DIV element work like an A element.
(function($) {
$.prettyPhoto = {version: '2.5.4'};
$.fn.prettyPhoto = function(settings) {
settings = jQuery.extend({
animationSpeed: 'normal', /* fast/slow/normal */
padding: 40, /* padding for each side of the picture */
opacity: 0.80, /* Value between 0 and 1 */
showTitle: true, /* true/false */
allowresize: true, /* true/false */
counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
modal: false, /* If set to true, only the close button will close the window */
changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
callback: function(){} /* Called when prettyPhoto is closed */
}, settings);
// Fallback to a supported theme for IE6
if($.browser.msie && $.browser.version == 6){
settings.theme = "light_square";
}
if($('.pp_overlay').size() == 0) {
_buildOverlay(); // If the overlay is not there, inject it!
}else{
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
}
// Global variables accessible only by prettyPhoto
var doresize = true, percentBased = false, correctSizes,
// Cached selectors
$pp_pic_holder, $ppt,
// prettyPhoto container specific
pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, pp_type = 'image',
//Gallery specific
setPosition = 0,
// Global elements
$scrollPos = _getScroll();
// Window/Keyboard events
$(window).scroll(function(){ $scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });
$(window).resize(function(){ _centerOverlay(); _resizeOverlay(); });
$(document).keydown(function(e){
if($pp_pic_holder.is(':visible'))
switch(e.keyCode){
case 37:
$.prettyPhoto.changePage('previous');
break;
case 39:
$.prettyPhoto.changePage('next');
break;
case 27:
if(!settings.modal)
$.prettyPhoto.close();
break;
};
});
// Bind the code to each links
$(this).each(function(){
$(this).bind('click',function(){
link = this; // Fix scoping
// Find out if the picture is part of a set
theRel = $(this).attr('rel');
galleryRegExp = /\[(?:.*)\]/;
theGallery = galleryRegExp.exec(theRel);
// Build the gallery array
var images = new Array(), titles = new Array(), descriptions = new Array();
if(theGallery){
$('a[rel*='+theGallery+']').each(function(i){
if($(this)[0] === $(link)[0]) setPosition = i; // Get the position in the set
images.push($(this).attr('href'));
titles.push($(this).find('img').attr('alt'));
descriptions.push($(this).attr('title'));
});
}else{
images = $(this).attr('href');
titles = ($(this).find('img').attr('alt')) ? $(this).find('img').attr('alt') : '';
descriptions = ($(this).attr('title')) ? $(this).attr('title') : '';
}
$.prettyPhoto.open(images,titles,descriptions);
return false;
});
});
/**
* Opens the prettyPhoto modal box.
* #param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
* #param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
* #param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
*/
$.prettyPhoto.open = function(gallery_images,gallery_titles,gallery_descriptions) {
// To fix the bug with IE select boxes
if($.browser.msie && $.browser.version == 6){
$('select').css('visibility','hidden');
};
// Hide the flash
if(settings.hideflash) $('object,embed').css('visibility','hidden');
// Convert everything to an array in the case it's a single item
images = $.makeArray(gallery_images);
titles = $.makeArray(gallery_titles);
descriptions = $.makeArray(gallery_descriptions);
if($('.pp_overlay').size() == 0) {
_buildOverlay(); // If the overlay is not there, inject it!
}else{
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
}
$pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme
isSet = ($(images).size() > 0) ? true : false; // Find out if it's a set
_getFileType(images[setPosition]); // Set the proper file type
_centerOverlay(); // Center it
// Hide the next/previous links if on first or last images.
_checkPosition($(images).size());
$('.pp_loaderIcon').show(); // Do I need to explain?
// Fade the content in
$('div.pp_overlay').show().fadeTo(settings.animationSpeed,settings.opacity, function(){
$pp_pic_holder.fadeIn(settings.animationSpeed,function(){
// Display the current position
$pp_pic_holder.find('p.currentTextHolder').text((setPosition+1) + settings.counter_separator_label + $(images).size());
// Set the description
if(descriptions[setPosition]){
$pp_pic_holder.find('.pp_description').show().html(unescape(descriptions[setPosition]));
}else{
$pp_pic_holder.find('.pp_description').hide().text('');
};
// Set the title
if(titles[setPosition] && settings.showTitle){
hasTitle = true;
$ppt.html(unescape(titles[setPosition]));
}else{
hasTitle = false;
};
// Inject the proper content
if(pp_type == 'image'){
// Set the new image
imgPreloader = new Image();
// Preload the neighbour images
nextImage = new Image();
if(isSet && setPosition > $(images).size()) nextImage.src = images[setPosition + 1];
prevImage = new Image();
if(isSet && images[setPosition - 1]) prevImage.src = images[setPosition - 1];
pp_typeMarkup = '<img id="fullResImage" src="" />';
$pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;
$pp_pic_holder.find('.pp_content').css('overflow','hidden');
$pp_pic_holder.find('#fullResImage').attr('src',images[setPosition]);
imgPreloader.onload = function(){
// Fit item to viewport
correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
_showContent();
};
imgPreloader.src = images[setPosition];
}else{
// Get the dimensions
movie_width = ( parseFloat(grab_param('width',images[setPosition])) ) ? grab_param('width',images[setPosition]) : "425";
movie_height = ( parseFloat(grab_param('height',images[setPosition])) ) ? grab_param('height',images[setPosition]) : "344";
// If the size is % based, calculate according to window dimensions
if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
movie_height = ($(window).height() * parseFloat(movie_height) / 100) - 100;
movie_width = ($(window).width() * parseFloat(movie_width) / 100) - 100;
percentBased = true;
}
movie_height = parseFloat(movie_height);
movie_width = parseFloat(movie_width);
if(pp_type == 'quicktime') movie_height+=15; // Add space for the control bar
// Fit item to viewport
correctSizes = _fitToViewport(movie_width,movie_height);
if(pp_type == 'youtube'){
pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" /><embed src="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
}else if(pp_type == 'quicktime'){
pp_typeMarkup = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'"><param name="src" value="'+images[setPosition]+'"><param name="autoplay" value="true"><param name="type" value="video/quicktime"><embed src="'+images[setPosition]+'" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
}else if(pp_type == 'flash'){
flash_vars = images[setPosition];
flash_vars = flash_vars.substring(images[setPosition].indexOf('flashvars') + 10,images[setPosition].length);
filename = images[setPosition];
filename = filename.substring(0,filename.indexOf('?'));
pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+filename+'?'+flash_vars+'" /><embed src="'+filename+'?'+flash_vars+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
}else if(pp_type == 'iframe'){
movie_url = images[setPosition];
movie_url = movie_url.substr(0,movie_url.indexOf('iframe')-1);
pp_typeMarkup = '<iframe src ="'+movie_url+'" width="'+(correctSizes['width']-10)+'" height="'+(correctSizes['height']-10)+'" frameborder="no"></iframe>';
}
// Show content
_showContent();
}
});
});
};
/**
* Change page in the prettyPhoto modal box
* #param direction {String} Direction of the paging, previous or next.
*/
$.prettyPhoto.changePage = function(direction){
if(direction == 'previous') {
setPosition--;
if (setPosition < 0){
setPosition = 0;
return;
}
}else{
if($('.pp_arrow_next').is('.disabled')) return;
setPosition++;
};
// Allow the resizing of the images
if(!doresize) doresize = true;
_hideContent();
$('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed,function(){
$(this).removeClass('pp_contract').addClass('pp_expand');
$.prettyPhoto.open(images,titles,descriptions);
});
};
/**
* Closes the prettyPhoto modal box.
*/
$.prettyPhoto.close = function(){
$pp_pic_holder.find('object,embed').css('visibility','hidden');
$('div.pp_pic_holder,div.ppt').fadeOut(settings.animationSpeed);
$('div.pp_overlay').fadeOut(settings.animationSpeed, function(){
$('div.pp_overlay,div.pp_pic_holder,div.ppt').remove();
// To fix the bug with IE select boxes
if($.browser.msie && $.browser.version == 6){
$('select').css('visibility','visible');
};
// Show the flash
if(settings.hideflash) $('object,embed').css('visibility','visible');
setPosition = 0;
settings.callback();
});
doresize = true;
};
/**
* Set the proper sizes on the containers and animate the content in.
*/
_showContent = function(){
$('.pp_loaderIcon').hide();
if($.browser.opera) {
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
}else{
windowHeight = $(window).height();
windowWidth = $(window).width();
};
// Calculate the opened top position of the pic holder
projectedTop = $scrollPos['scrollTop'] + ((windowHeight/2) - (correctSizes['containerHeight']/2));
if(projectedTop < 0) projectedTop = 0 + $pp_pic_holder.find('.ppt').height();
// Resize the content holder
$pp_pic_holder.find('.pp_content').animate({'height':correctSizes['contentHeight']},settings.animationSpeed);
// Resize picture the holder
$pp_pic_holder.animate({
'top': projectedTop,
'left': ((windowWidth/2) - (correctSizes['containerWidth']/2)),
'width': correctSizes['containerWidth']
},settings.animationSpeed,function(){
$pp_pic_holder.width(correctSizes['containerWidth']);
$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);
// Fade the new image
$pp_pic_holder.find('#pp_full_res').fadeIn(settings.animationSpeed);
// Show the nav
if(isSet && pp_type=="image") { $pp_pic_holder.find('.pp_hoverContainer').fadeIn(settings.animationSpeed); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
$pp_pic_holder.find('.pp_details').fadeIn(settings.animationSpeed);
// Show the title
if(settings.showTitle && hasTitle){
$ppt.css({
'top' : $pp_pic_holder.offset().top - 20,
'left' : $pp_pic_holder.offset().left + (settings.padding/2),
'display' : 'none'
});
$ppt.fadeIn(settings.animationSpeed);
};
// Fade the resizing link if the image is resized
if(correctSizes['resized']) $('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);
// Once everything is done, inject the content if it's now a photo
if(pp_type != 'image') $pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;
// Callback!
settings.changepicturecallback();
});
};
/**
* Hide the content...DUH!
*/
function _hideContent(){
// Fade out the current picture
$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
$pp_pic_holder.find('.pp_hoverContainer,.pp_details').fadeOut(settings.animationSpeed);
$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
$('.pp_loaderIcon').show();
});
// Hide the title
$ppt.fadeOut(settings.animationSpeed);
}
/**
* Check the item position in the gallery array, hide or show the navigation links
* #param setCount {integer} The total number of items in the set
*/
function _checkPosition(setCount){
// If at the end, hide the next link
if(setPosition == setCount-1) {
$pp_pic_holder.find('a.pp_next').css('visibility','hidden');
$pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
}else{
$pp_pic_holder.find('a.pp_next').css('visibility','visible');
$pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
$.prettyPhoto.changePage('next');
return false;
});
};
// If at the beginning, hide the previous link
if(setPosition == 0) {
$pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
$pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
}else{
$pp_pic_holder.find('a.pp_previous').css('visibility','visible');
$pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
$.prettyPhoto.changePage('previous');
return false;
});
};
// Hide the bottom nav if it's not a set.
if(setCount > 1) {
$('.pp_nav').show();
}else{
$('.pp_nav').hide();
}
};
/**
* Resize the item dimensions if it's bigger than the viewport
* #param width {integer} Width of the item to be opened
* #param height {integer} Height of the item to be opened
* #return An array containin the "fitted" dimensions
*/
function _fitToViewport(width,height){
hasBeenResized = false;
_getDimensions(width,height);
// Define them in case there's no resize needed
imageWidth = width;
imageHeight = height;
windowHeight = $(window).height();
windowWidth = $(window).width();
if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
hasBeenResized = true;
notFitting = true;
while (notFitting){
if((pp_containerWidth > windowWidth)){
imageWidth = (windowWidth - 200);
imageHeight = (height/width) * imageWidth;
}else if((pp_containerHeight > windowHeight)){
imageHeight = (windowHeight - 200);
imageWidth = (width/height) * imageHeight;
}else{
notFitting = false;
};
pp_containerHeight = imageHeight;
pp_containerWidth = imageWidth;
};
_getDimensions(imageWidth,imageHeight);
};
return {
width:imageWidth,
height:imageHeight,
containerHeight:pp_containerHeight,
containerWidth:pp_containerWidth,
contentHeight:pp_contentHeight,
contentWidth:pp_contentWidth,
resized:hasBeenResized
};
};
/**
* Get the containers dimensions according to the item size
* #param width {integer} Width of the item to be opened
* #param height {integer} Height of the item to be opened
*/
function _getDimensions(width,height){
$pp_pic_holder.find('.pp_details').width(width).find('.pp_description').width(width - parseFloat($pp_pic_holder.find('a.pp_close').css('width'))); /* To have the correct height */
// Get the container size, to resize the holder to the right dimensions
pp_contentHeight = height + $pp_pic_holder.find('.pp_details').height() + parseFloat($pp_pic_holder.find('.pp_details').css('marginTop')) + parseFloat($pp_pic_holder.find('.pp_details').css('marginBottom'));
pp_contentWidth = width;
pp_containerHeight = pp_contentHeight + $pp_pic_holder.find('.ppt').height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
pp_containerWidth = width + settings.padding;
}
function _getFileType(itemSrc){
if (itemSrc.match(/youtube\.com\/watch/i)) {
pp_type = 'youtube';
}else if(itemSrc.indexOf('.mov') != -1){
pp_type = 'quicktime';
}else if(itemSrc.indexOf('.swf') != -1){
pp_type = 'flash';
}else if(itemSrc.indexOf('iframe') != -1){
pp_type = 'iframe'
}else{
pp_type = 'image';
};
};
function _centerOverlay(){
if($.browser.opera) {
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
}else{
windowHeight = $(window).height();
windowWidth = $(window).width();
};
if(doresize) {
$pHeight = $pp_pic_holder.height();
$pWidth = $pp_pic_holder.width();
$tHeight = $ppt.height();
projectedTop = (windowHeight/2) + $scrollPos['scrollTop'] - ($pHeight/2);
if(projectedTop < 0) projectedTop = 0 + $tHeight;
$pp_pic_holder.css({
'top': projectedTop,
'left': (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2)
});
$ppt.css({
'top' : projectedTop - $tHeight,
'left' : (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2) + (settings.padding/2)
});
};
};
function _getScroll(){
if (self.pageYOffset) {
scrollTop = self.pageYOffset;
scrollLeft = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
scrollTop = document.documentElement.scrollTop;
scrollLeft = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
scrollTop = document.body.scrollTop;
scrollLeft = document.body.scrollLeft;
}
return {scrollTop:scrollTop,scrollLeft:scrollLeft};
};
function _resizeOverlay() {
$('div.pp_overlay').css({
'height':$(document).height(),
'width':$(window).width()
});
};
function _buildOverlay(){
toInject = "";
// Build the background overlay div
toInject += "<div class='pp_overlay'></div>";
// Basic HTML for the picture holder
toInject += '<div class="pp_pic_holder"><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content">Expand<div class="pp_loaderIcon"></div><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res"></div><div class="pp_details clearfix"><a class="pp_close" href="#">Close</a><p class="pp_description"></p><div class="pp_nav">Previous<p class="currentTextHolder">0'+settings.counter_separator_label+'0</p>Next</div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div>';
// Basic html for the title holder
toInject += '<div class="ppt"></div>';
$('body').append(toInject);
// So it fades nicely
$('div.pp_overlay').css('opacity',0);
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
$('div.pp_overlay').css('height',$(document).height()).hide().bind('click',function(){
if(!settings.modal)
$.prettyPhoto.close();
});
$('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; });
$('a.pp_expand').bind('click',function(){
$this = $(this); // Fix scoping
// Expand the image
if($this.hasClass('pp_expand')){
$this.removeClass('pp_expand').addClass('pp_contract');
doresize = false;
}else{
$this.removeClass('pp_contract').addClass('pp_expand');
doresize = true;
};
_hideContent();
$pp_pic_holder.find('.pp_hoverContainer, .pp_details').fadeOut(settings.animationSpeed);
$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
$.prettyPhoto.open(images,titles,descriptions);
});
return false;
});
$pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
$.prettyPhoto.changePage('previous');
return false;
});
$pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
$.prettyPhoto.changePage('next');
return false;
});
$pp_pic_holder.find('.pp_hoverContainer').css({
'margin-left': settings.padding/2
});
};
};
function grab_param(name,url){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
})(jQuery);
Here is the link to the lighbox.
All help is appreciated.
Thanks,
Tim
It looks like the pretty photos code is using the rel attribute explicitly, do your div's have rel? You are calling the code on $("div[class^='menuitem[iframes]']").prettyPhoto();
But then pretty photos is looking for theRel = $(this).attr('rel'); and running against that.

Categories

Resources