Dropbox API logout url is not working properly - php

I am using php sdk provided by dropbox to import images from user's account after the authorization.
All is working perfectly.
But the logout url (Which I have created) is not working properly.
Below is my code:
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
<style>
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
});
</script>
<script>
function loader(){
$('#load').show();
}
function loadExistingImages(){
window.opener.$('#loader_img').show();
result=null;
window.opener.$('#fileupload').each(function () {
var that = this;
$.getJSON(this.action, function (result) {
if (result && result.length) {
window.opener.$(that).fileupload('option', 'done')
.call(that, null, {result: result});
//console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
if(window.opener.$('.table-striped tbody').find('.btn-danger').length>0){
window.opener.$('.coo-images-other-buttons').show();
}else{
window.opener.$('.coo-images-other-buttons').hide();
}
}
window.opener.$('#loader_img').hide();
if (window.opener.$('.table-striped tbody tr').length > 0)
{
window.opener.$('.table_tagline').show();
}
});
});
}
</script>
<script type="text/javascript">$('#load').hide();</script>
<?php
/***********************************************************************
* Plugin Name: Dropbox Plugin
* Plugin URI: http://www.picpixa.com/
* Version: 1.0
* Author: Ashish Shah
* Description: Plugin To Import Images From User's Dropbox Account
**********************************************************************/
session_start();
include_once '/home/picpixa/wp-config.php';
//ini_set("display_errors",0);
if(isset($_POST['copy']) && $_POST['dropbox'])
{
$imgArray = $_POST['dropbox'];
$current_user = wp_get_current_user();
if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
$extraSessionStr = 'usr-'.md5($current_user->ID).'/';
$user = $current_user->ID;
}else{
$sesstionId = session_id();
$user = $sesstionId;
$extraSessionStr = $sesstionId.'/';
}
foreach ($imgArray as $img)
{
$fileName=basename($img);
// Read file content
$file_content = file_get_contents($img);
file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
//file_put_contents('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName, $file_content);
//Get the image size
$imgsize=get_headers($img,1);
$imgsize = number_format(($imgsize["Content-Length"]/1024),2);
/* To create thumbnail */
// Max vert or horiz resolution
$maxsize=80;
// create new Imagick object
$image = new Imagick($img); //"input_image_filename_and_location"
// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
?>
<script type="text/javascript">
//window.opener.$("#fileupload").append(div);
window.opener.$('tbody.files').find('tr').remove();
loadExistingImages();
</script>
<?php
echo "<h2>The selected images have been moved.<br></h2>";
echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="";'>
<input type='button' name='closeWindow' value='Proceed With Uploaded Images' class='btn btn-primary' onClick="window.close();">
</div>
<?php
die();
}
elseif (isset($_POST['copy']))
{
echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
echo "<h3>Please click on \"Close\" button to Close the window OR ";
echo "Click on the \"Upload Images\" Button to upload images.</h3>";
?>
<div class="modal-footer">
<input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
</div>
<?php
die();
}
require_once __DIR__.'/dropbox-sdk/Dropbox/strict.php';
$appInfoFile = __DIR__."/AppInfo.json";
// NOTE: You should be using Composer's global autoloader. But just so these examples
// work for people who don't have Composer, we'll use the library's "autoload.php".
require_once __DIR__.'/dropbox-sdk/Dropbox/autoload.php';
use \Dropbox as dbx;
$requestPath = init();
if ($requestPath === "/") {
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
$path = "/";
if (isset($_GET['path'])) $path = $_GET['path'];
$entry = $dbxClient->getMetadataWithChildren($path);
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
else if ($requestPath == "/download") {
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
if (!isset($_GET['path'])) {
header("Location: ".getPath(""));
exit;
}
$path = $_GET['path'];
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
}
else if ($requestPath === "/upload") {
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}
else if ($requestPath === "/dropbox-auth-start") {
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($requestPath === "/dropbox-auth-finish") {
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
// We didn't pass in $urlState to finish, and we're assuming the session can't be
// tampered with, so this should be null.
assert($urlState === null);
}
catch (dbx\WebAuthException_BadRequest $ex) {
respondWithError(400, "Bad Request");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it could contain
// sensitive information.
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header("Location: ".getPath("dropbox-auth-start"));
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
respondWithError(403, "Unauthorized", "CSRF mismatch");
// Write full details to server error log.
// IMPORTANT: Never show the $ex->getMessage() string to the user -- it contains
// sensitive information that could be used to bypass the CSRF check.
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
respondWithError(500, "Internal Server Error");
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!",
"Authorization complete, <a href='".htmlspecialchars(getPath(""))."' onclick='loader()'>click here</a> to browse.");
}
else if ($requestPath === "/dropbox-auth-unlink") {
// "Forget" the access token.
unset($_SESSION['access-token']);
//$_SESSION = array();
echo renderHtmlPage("Logged Out",
"<div class='modal-footer'>
You have been logged out.<br>To Login Again click \"Login To Dropbox\"
OR Click on the \"Proceed With Uploaded Images\" Button to upload more images.<br>
<input type='button' name='login' value='Login To Dropbox' class='btn btn-primary' onClick='location.href = \"https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/index.php\";'>
<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick='window.close();'>
</div>"
);
}
else {
echo renderHtmlPage("Bad URL", "No handler for $requestPath");
exit;
}
function renderFolder($entry)
{
/*echo "entry:<pre>";
print_r($entry);
echo "</pre>entry end.<br>Session:<pre>";
print_r($_SESSION);
echo "</pre>Session end.";
die;*/
$dbxClient = getClient();//Using to use the createTemporaryDirectLink() function
// TODO: Add a token to counter CSRF attacks.
// $upload_path = htmlspecialchars(getPath('upload'));
//$path = htmlspecialchars($entry['path']);
//$form = <<<HTML <form action='$upload_path' method='post' enctype='multipart/form-data'> <label for='file'>Upload file:</label> <input name='file' type='file'/> <input type='submit' value='Upload'/> <input name='folder' type='hidden' value='$path'/> </form> HTML;
//$form = <<<HTML HTML;
$listing = "<div id='load' class='loader'></div>
<div class='container'>
<div class='row'>
<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>";
if(isset($entry['contents']) && $entry['contents']){
$listing .= "<div class='modal-footer'>
<script>
function goDirect(){
alert(window.location);
window.location.href='dropbox-auth-unlink';
}
</script>
<input type='button' name='logout' value='Logout' class='btn btn-primary' onclick='goDirect()'>
</div>";
}
$listing .= "<form method='POST' action=''>
<div class='modal-body'>";
$i=0;
$showBtn=False;
foreach($entry['contents'] as $child) {
$type='Folder';
$cp = $child['path'];
$cn = basename($cp);
if (!$child['is_dir']){
$type=$child['mime_type'];
}
$cp = htmlspecialchars($cp);
$link = getPath("?path=".htmlspecialchars($cp));
if ($child['is_dir']){
$listing .= "<div class='baby_img'>Folder: <a style='text-decoration: none' href='$link'>$cn</a></div>";
$cn .= '/';
}
else{
if(strcmp($type,'image/*')==1){
$img = $dbxClient->createTemporaryDirectLink($cp);
$listing .= "<div class='baby_img'>
<input type='checkbox' id='dropbox_".$i."' name='dropbox[]' value='".$img[0]."' class='styled' />";
$listing .= "<img src='".$img[0]."' height = '100px' width = '100px' class='img-responsive'/>";
$listing .= '</div>';
$i++;
$showBtn=true;
}
}
}
$listing .= '<div class="clearfix"></div>
<div class="modal-footer">';
if($showBtn){
$listing .= "<input type='submit' name='copy' value='Copy Selected Files' class='btn btn-primary' onclick='loader()'>";
}
$listing .= "<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary' onClick='window.close();'>";
$listing .= '</div>';
$listing .= "</form>
</div>
</div>
</div>";
return renderHtmlPage("App/picpixa$entry[path]", $listing);
}
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if(!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale, $appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function renderFile($entry)
{
$metadataStr = htmlspecialchars(print_r($entry, true));
$downloadPath = getPath("download?path=".htmlspecialchars($entry['path']));
$body = <<<HTML
<pre>$metadataStr</pre>
Download this file
HTML;
return renderHtmlPage("File: ".$entry['path'], $body);
}
function renderHtmlPage($title, $body)
{
return <<<HTML
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>$title</title>
<!-- Bootstrap -->
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/bootstrap.css' rel='stylesheet'>
<link href='https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-dropbox/css/style.css' rel='stylesheet'>
</head>
<body>
$body
</body>
</html>
HTML;
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")<br>".
"doesn't have a built-in web server. You need PHP 5.4 or newer.<br>".
"<br>".
"You can still run this example if you have a web server that supports PHP 5.3.<br>".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.<br>");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.<br>".
"Usage: php $argv[0] [server-port]<br>");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:<br>".
" $cmd<br>");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
?>
Can anyone please help me?
My Observation:
when the url in the address bar is "/index.php/" , then the logout button is working fine.
But when the url in the address bar is "/index.php" , then the logout button is not working.
I tried to give if condition in the script but failed.
Please help me out.

You have this code:
function goDirect(){
alert(window.location);
window.location.href='dropbox-auth-unlink';
}
Setting window.location.href to a relative path will replace the last segment of the URL. So if the URL is .../plugin-dropbox/index.php, you'll end up browsing to .../plugin-dropbox/dropbox-auth-unlink. If, on the other hand, you have .../plugin-dropbox/index.php/ (note the extra, empty, segment at the end of the URL), you'll end up browsing to .../plugin-dropbox/index.php/dropbox-auth-unlink.
Apparently the latter is the URL you want. So you could drop the trailing slash (just use index.php) and try one of these:
function goDirect() {
// Simple but doesn't work well with query string parameters:
// window.location.href += '/dropbox-auth-unlink';
// An alternative that requires hardcoding the 'index.php' part:
window.location.href = 'index.php/dropbox-auth-unlink';
}

Related

include loading webpages in slideshow

I am totally new to stackoverflow. I'm trying to adjust an excisting script in which an folder containing photo and video is getting loaded and displayed like a slideshow.
I'd like to add the option to load webpages also. Is there any easy way to do this?
Thank you so much.
This is my code:
<?php
include "class.getFiles.php";
$images = new getFiles();
// list of all files in the images folder (includes videos)
$imageArray = $images->getImageArray();
$sortedImages = new sortFiles();
$sortedImages->sortImageArray($imageArray);
// remove files not in the correct time period
$imageArray = $sortedImages->getImageArray();
$randImage = $sortedImages->randomImageNum();
$fileName = $imageArray[$randImage];
$info = new SplFileInfo($fileName);
?>
<!DOCTYPE html>
<html>
<head>
<title>Fiction Slideshow</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<?php
if($info->getExtension() == "mp4")
{
echo '<video id="vid" class="videoDisplay" autoplay>
<source src="images/'.$fileName.'" type="video/mp4">
Your browser does not support the video tag.
</video>';
echo '<script type="text/javascript">
var vid = document.getElementById("vid");
vid.addEventListener("ended", function(){
window.location.reload();
});
</script>';
}
else
{
echo '<img class="imageDisplay" src="images/'.$fileName.'" />';
echo '<script type="text/javascript">
setTimeout(function(){
window.location.reload();
}, 30000);
</script>';
}
?>
</body>
</html>
This is the class.getFiles.php file that the other script calls.
<?php
class getFiles{
protected $dir;
protected $imageArray;
function __construct()
{
$this->get_dir();
$this->get_images();
}
protected function get_dir()
{
$this->dir = getcwd();
}
protected function get_images()
{
if(count(scandir($this->dir."/images")) != 2)
{
$this->imageArray = scandir($this->dir."/images");
}
else
{
die("There are no files in the directory");
}
}
public function getImageArray()
{
return $this->imageArray;
}
}
class sortFiles{
protected $sortedImageArray = [];
public function sortImageArray($imageArray)
{
foreach ($imageArray as $imageFile )
{
if($imageFile !== ".." && $imageFile !== ".")
{
$imagePath = $imageFile;
$imageFile = (substr($imageFile, 0, -4));
$BeginningPos = strpos($imageFile, '_');
$beginningDate = (substr($imageFile, 0, $BeginningPos));
$beginningDateformatted = str_replace("-","/", $beginningDate);
$stringToStartTime = strtotime($beginningDateformatted);
$EndingPos = strpos($imageFile, '_', $BeginningPos + strlen('_'));
$EndingPos = $EndingPos + 1;
$EndingDate = (substr($imageFile, $EndingPos));
$EndingDateformatted = str_replace("-","/", $EndingDate);
$stringToEndTime = strtotime($EndingDateformatted);
$time = time();
if($time <= $stringToStartTime && $time >= $stringToEndTime)
{
array_push($this->sortedImageArray, $imagePath);
}
}
}
}
public function getImageArray()
{
if(count($this->sortedImageArray) != 0)
{
return $this->sortedImageArray;
}
else
{
die("There are no files in the time range");
}
}
public function randomImageNum()
{
$imageArrayLength = count($this->sortedImageArray);
$imageRand = rand(0, $imageArrayLength-1);
return $imageRand;
}
}
?>
Well you can save the web pages as links within your media folder. For example if you want to display the web page http://www.example.com, then you can create a file webpage1.txt inside the media folder. This file can have the link http://www.example.com.
In your code you can add a new condition that checks if the file type is txt. If the file type is txt, then your code can read the link inside the file and display the link using an iframe. The following code should work:
else if(strpos($fileName, "weblink") !== false)
{
/** The path to the web page link */
$file_path = (getcwd() . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . $fileName);
/** Read contents of file */
$web_page_link = file_get_contents($file_path);
/** Display the link in iframe */
echo "<iframe src='".$web_page_link."' width='100%' height='100%'></iframe>";
}
The above code should go above the else statement

Simple Ajax request to echo data from textfile onto HTML getting GET 500 (Internal Server Error)

Problem
I'm new to AJAX request so I believe I might be making a simple mistake, but whenever I want to run my script using an AJAX request I get a 500 (Internal Server Error)
Basically what I want to happen is if the user presses the #show-all button I will run a showall.php script that reads tasks from a data.txt file and prints the tasks in HTML on the webpage.
Any advice would be greatly appreciated!
PS: Line 24 refers to $.ajax({ and Line 27 refers to console.log("Error: " + error);
Code
Ajax request
$("#show-all").on("click", function () {
console.log("button pressed");
$.ajax({
url: '../p2/showall.php'
, error: function (error) {
console.log("Error: " + error);
}
, success: function (response) {
console.log("Success: " + response);
}
});
});
showall.php
<?php
$filename = 'data.txt';
include('file.php');
include('add.php');
$tasks = read_file($filename);
foreach($tasks as $task){
echo_task($task);
}
?>
file.php
<?php
//Write task element to file
function write_file($filename, $task){
$arr = array($task->title, $task->due_date, $task->priority, $task->course, $task->note);
$line = implode("\t", $arr);
$line .= "\n";
$file_pointer = fopen($filename, 'a' );
if ( ! $file_pointer ) { echo( 'error' ); exit; }
$error = fputs($file_pointer,$line);
fclose($file_pointer);
}
//Read file $filename and return array of Tasks
function read_file($filename){
$lines = file($filename);
if(!$lines){
print( 'error' );
exit;
}
$tasks = array();
foreach($lines as $line){
//Assume every entry should have notes
$arr = explode("\t", $line);
//Assume notes should not have \n in it
$arr[4] = str_replace("\n", "", $arr[4]);
$task = new Task($arr[0], $arr[1], $arr[2], $arr[3], $arr[4]);
$tasks[] = $task;
}
return $tasks;
}
?>
add.php
<?php
//Returns true if text field input isset & not empty string, otherwise returns false & echos issue to use
function validText($field){
if(isset($_POST['add'])){
if(isset($_POST[$field])){
if($_POST[$field] !== ''){
return true;
}
echo "<h3 class='error'>*Task $field cannot be empty</h3>";
return false;
}
echo "<h3 class='error'>*Task $field must be set</h3>";
return false;
}
return true;
}
//Return task from form elements
function task_from_form(){
if(isset($_POST['add']) && isset($_POST['title']) && isset($_POST['note'])){
if($_POST['title'] !== '' && $_POST['note'] !== ''){
$title = $_POST['title'];
$note = $_POST['note'];
$title_trim = trim($title);
$note_trim = trim($note);
$title_html = htmlentities($title_trim);
$note_html = htmlentities($note_trim);
$due_date = $_POST['due-date'];
$priority = $_POST['priority'];
$course = $_POST['course'];
$course_space = str_replace("-", " ", $course);
$task = new Task($title_html, $due_date, $priority, $course_space, $note_html);
return $task;
}
}
}
//Echo task
function echo_task($task){
echo "<div class='task row'>
<div class='task-title row'>
<button type='button' class='checkbox col'><span class='icon-checkbox-box' aria-hidden='true'></span></button>
<h1 class='col'>{$task->title}</h1>
<div class='task-info'>
<h2 class='due-date col task-date'>{$task->due_date}</h2>
<button type='button' class='priority {$task->priority} col'><span class='icon-circle' aria-hidden='true'></span></button>
</div>
</div>
<div class='task-details'>
<div class='row'>
<h2 class='col'>{$task->course}</h2> </div>
<div class='row'>
<p class='note col'>{$task->note}</p>
</div>
</div>
</div>";
}
?>
I believe this is not an ajax issue. If you visit http://localhost:8888/p2/showall.php I think you will get the same 500 error. Try to check your server, if its a php issue, create a html file to return same content as you want, will be easier to debug.

OOP PHP Safe Project

I have this "safe" project to get the basics down just to become more familiar with OOP.
Here is my code:
chest.php
<?php
class safe{
public $isLocked = true;
public $isClosed = true;
public function unlock(){
if ($this->isLocked == true) {
$this->isLocked = false;
echo "Safe Unlocked<br>";
}else{
echo "Safe Already Unlocked<br>";
}
}
public function lock(){
if ($this->isLocked == false) {
if ($this->isClosed == true) {
$this->isLocked = true;
echo "Safe Now Locked<br>";
}else{
echo "Safe Needs To Be Closed To Be Locked<br>";
}
}else{
echo "Safe Is Already Locked<br>";
}
}
public function checkLock(){
if ($this->isLocked == true) {
echo "<span style='color:red;'>Safe Is Locked</span><br>";
}else{
echo "<span style='color:red;'>Safe Is Not Locked</span><br>";
}
}
public function open(){
if ($this->isClosed == true) {
if ($this->isLocked == false) {
$this->isClosed = false;
echo "Safe Is Now Open<br>";
}else{
echo "Safe Is Locked, Cannot Open<br>";
}
}else{
echo "Safe Already Open<br>";
}
}
public function close(){
if ($this->isClosed == false) {
if ($this->isLocked == false) {
$this->isClosed = true;
echo "Safe Now Closed<br>";
}else{
echo "Safe Is Currently Locked Cannot Close<br>";
}
}else{
echo "Safe Already Closed<br>";
}
}
}
index.php
<?php
require 'chest.php';
$safe = new safe();
if ($safe->isLocked == true) {
echo "Safe Currently Locked<br><br>";
}
$safe->open();
$safe->lock();
$safe->unlock();
$safe->open();
$safe->lock();
$safe->open();
$safe->unlock();
$safe->checkLock();
$safe->lock();
$safe->close();
$safe->lock();
$safe->open();
$safe->lock();
$safe->checkLock();
if (isset($_POST['unlock'])) {
$safe->unlock();
}
if (isset($_POST['lock'])) {
$safe->lock();
}
if (isset($_POST['open'])) {
$safe->open();
}
if (isset($_POST['close'])) {
$safe->close();
}
if (isset($_POST['check'])) {
$safe->checkLock();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Safe</title>
</head>
<body>
<form method="post">
<input type="submit" name="unlock" value="Unlock">
<input type="submit" name="lock" value="Lock">
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
<input type="submit" name="check" value="Check Lock">
</form>
</body>
</html>
It works fine when I call the functions without the if statement, but when I try to put them into an isset($_POST['value'] it keeps displaying only 1 output and always sets isLocked(); back to being true so it never works.
To stop the page from refreshing each time would require javascript and ajax. Your javascript could stop the page from loading on click, and your ajax could make a call to the server to execute your PHP

javascript for onClick not executing?

ok maybe i must put all my code:
<?php
include('header_application.php');
$obj_clean->check_user();
$limit = 10;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$msg = "";
if (isset($_GET['unblock']))
{
$code = $obj_clean->unblockUser($_GET['unblock'],$_GET['code']);
if ($code == "error")
{
$msg = "Could not delete message!";
}
else
{
$msg = "You have unblocked ".$code;
}
}
//Get dynamic data required for this page from the database
$users = $obj_clean->getContacts($_SESSION['user_id'], $from, $limit);
$rows = $obj_clean->getContactsCount($_SESSION['user_id']);
include ("header.php");
?>
<div class="innerContainer">
<head>
<script type="text/JavaScript">
function yesnolist(val)
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location.href = "http://www-rainbowcode-mobi/confirmfreechat.php";
//window.location('http://www-rainbowcode-mobi/confirmfreechat.php');
return true;
}
else
return false;
}
</script>
</head>
<span class="headings2">CONTACTS</span>
<?php if (isset($msg) && !empty($msg)) echo "<br/><font color='red'>".$msg."</font>"; ?>
<br/><br/>
<?php
if (count($users) > 0)
{
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
foreach ($users as $user)
{
//Breaks the unique code into 3 parts so that the numeric part can be a different colour
$codeLength = strlen($user['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($user['unique_code'], -2);
$uniqueCode2 = substr($user['unique_code'], -5, 3);
$uniqueCode1 = substr($user['unique_code'], 0, $firstPartLength);
echo '<tr>';
echo '<td>';
echo '<a class="charcoal_link" style="line-height: 20px;" href="'.ADDRESS.'view_profile.php?id='.$user['profile_id_contact'].'">'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</a>';
$requestor_id = $_SESSION['user_id'];
$profile_id = $user['profile_id_contact'];
$rel1 = $obj_clean->hasRelation($requestor_id,$profile_id);
$rel2 = $obj_clean->hasRelation($profile_id,$requestor_id);
if($rel1 && $rel2)
{
echo " ";
//echo 'Free Chat';
echo 'Free Chat';
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "You have no contacts yet";
}
?>
</div>
<?php include("footer.php"); ?>
hope this will help better
Free Chat
should be:
Free Chat
try this:
function yesnolist()
{
if (confirm('Do you want to send a free chat request?'))
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
}
.
.
.
<a href="#" onClick="yesnolist()">
I'd assume changing the URLs to valid domains might help things, so try:
window.location.href = "http://www.rainbowcode.mobi/confirmfreechat.php";
window.location('http://www.rainbowcode.mobi/confirmfreechat.php');
function yesnolist()
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
return true;
}
else
return false;
}
and
<label onClick="return yesnolist();">Free Chat</a>
You can not pass onclick event on (a href="") tag because href part redirects the page and after that the javascript redirect part is called.
Or
(a href="#" onclick="return yesnolist();")Free Chat(/a)

Php, IMAP logout how to?

didn't find any solution in previous questions.
I've developed a simple imap access to my server, it's working well, but I've a big problem.
Server is running slow and is getting down due to open imap sessions.
How do I close / logout? In the php imap documentation I don't find a solution, I use this
function correio ($caixa) {
if($caixa ==="Inbox") {
if($_REQUEST['user'] == "Gmail") {
$box = imap_open(servidor."INBOX", user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.$caixa, SA_ALL);
} else {
$box = imap_open(servidor, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.".".$caixa, SA_ALL);
}
} else {
if($_REQUEST['user'] == "Gmail") {
$box = imap_open(servidor."[Gmail]/".$caixa, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor."[Gmail]/".$caixa, SA_ALL);
} else {
$box = imap_open(servidor.".".$caixa, user, pass) or die (imap_last_error());
$informacoes = imap_status($box, servidor.".".$caixa, SA_ALL);
}
}
if($box) {
$n = imap_check($box);
$conteudos = imap_fetch_overview($box,"1:{$n->Nmsgs}", 0);
$msgs .= "<div id='div_".$caixa."' class='menu'>";
$msgs .= "<h3 id='".$caixa."' class='".$caixa."'>".$caixa." Total: ".$informacoes->messages.", Últimas: ".$informacoes->recent.", Não lidas: ".$informacoes->unseen."</h3>";
$msgs .= "<div class='mensagens'>";
if($conteudos) {
foreach($conteudos as $mensagem) {
$de = imap_mime_header_decode($mensagem->from);
$msgs .= "<h1 class='".$caixa."'><input type='checkbox' id='".$mensagem->uid."' class='in_".$caixa."' /> ".$de[0]->text."
<script type='text/javascript'>
$('input:checkbox').click(function(event) {
event.stopPropagation();
});
</script>
</h1>";
$subject = imap_mime_header_decode($mensagem->subject);
for ($i=0; $i<count($subject); $i++) {
$assunto = $subject[$i]->text;
}
$msgs .= "<p id='msg_".$mensagem->uid."'>".$assunto."
<script type='text/javascript'>
$('#msg_".$mensagem->uid."').click(function() {
ver_mensagem('".$caixa."', '".$mensagem->uid."');
});
</script>
</p>";
}
} else {
$msgs .= "<h1 class='".$caixa."'>Não há mensagens novas.</h1>";
}
$msgs .= "</div>";
$msgs .= "</div>";
return $msgs;
imap_close($box);
} else {
die("Ligação recusada: " . imap_last_error());
imap_close($box);
}
}
if($inbox =& correio("Inbox")) {
$f = $inbox;
if($spam =& correio("Spam")) {
$f .= $spam;
}
}
//echo "f = ".$f."<br />";
$str = "<div id='wrapper'><div id='mobimail' style='display:none'>";
$str .= $f;
$str .= "</div></div>";
$str .= "<div id='footer' class='footer' align='center'>
<div class='todos' align='center'></div>
<div class='apagar' align='center'></div>
<div class='mover' align='center'></div>
<div class='reload' align='center'></div>
<div class='sair' align='center'></div>
</div>";
echo $header."|||".$str;
imap_close($box);
var_dump(imap_close($box));
If the connection is closed, you obviously log out. Closing probably fails, what does imap_close($box) returns?
What is the return value of imap_close()? It can be Either True or False, there is no guarantee that it will always close the stream.
You can try running a simple test setup: imap_open() followed by a simple command such as imap_ping() and then immediate imap_close(). Does this close the connection as expected or does it stay open?
Also make sure you don't call multiple imap_open()s before first closing them. Use either imap_reopen(), call imap_close() before imap_open(), or use a different variable to store the connection identifier (But make sure you imap_close() both of them!).

Categories