示例#1
0
function doAction($action)
{
    $forwardpage = "";
    $forward = true;
    $loggedin = isUserLoggedIn();
    if (!$loggedin && strcmp($action, "login") != 0 && strcmp($action, "register") != 0 && strcmp($action, "getTags") != 0) {
        addError("fatal", "user.unathorized");
        outputJSON("error");
    } else {
        if (strcmp($action, "login") == 0) {
            login();
        } else {
            if (strcmp($action, "logout") == 0) {
                logout();
            } else {
                if (strcmp($action, "isLoggedIn") == 0) {
                    isLoggedIn();
                } else {
                    if (strcmp($action, "register") == 0) {
                        register();
                    } else {
                        if (strcmp($action, "addquestion") == 0) {
                            addQuestion();
                        } else {
                            if (strcmp($action, "getTags") == 0) {
                                getTags();
                            } else {
                                if (strcmp($action, "getquestions") == 0) {
                                    getQuestions();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
示例#2
0
}
// backward
if (!in_array($_GET['mod'], $mods)) {
    $_GET['mod'] = 'dictionary';
}
$mod = $_GET['mod'];
// shortcut
$_GET['mod'] = 'dictionary';
$_GET['action'] = 'view';
$_GET['format'] = $_GET['format'] == 'json' ? 'json' : 'xml';
// process
require_once $base_dir . '/modules/class_' . $mod . '.php';
$page = new $mod(&$db, &$auth, $msg);
$page->process();
if ($apiData = $page->getAPI()) {
    $ret = $_GET['format'] == 'json' ? outputJSON($apiData) : outputXML($apiData);
} else {
    $ret = '<p>Antarmuka pemrograman aplikasi (API) yang (masih) sangat sederhana ini dibuat untuk memungkinkan para pengembang memanfaatkan data yang disediakan oleh Kateglo. Untuk tahap awal, baru modul kamus yang dapat diakses dengan API ini.</p>
	<p>Gunakan format</p>
	<blockquote>http://bahtera.org/kateglo/api.php?format=[xml|json]&phrase=[lema_yang_dicari].</blockquote></p>
	<p>Contoh:</p>
	<blockquote><a href="api.php?format=xml&phrase=kata">http://bahtera.org/kateglo/api.php?format=xml&phrase=kata</a><br /><a href="api.php?format=json&phrase=bahtera">http://bahtera.org/kateglo/api.php?format=json&phrase=bahtera</a></blockquote>
	<p>Silakan pelajari sendiri dulu keluaran XML atau JSON yang dihasilkan karena dokumentasi masih belum sempat dibuat.</p>
	<p>API ini disediakan dengan apa adanya, dan ada kemungkinan akan berubah format.</p>';
}
echo $ret;
/**
 * output XML
 */
function outputXML(&$apiData)
{
示例#3
0
        print json_encode(array("status" => "success", "filename" => $file->getName() . '.' . $file->getExtension()));
        exit;
    } catch (\Exception $e) {
        header("Content-Type: text/html");
        print json_encode(array("status" => "error", "errors" => $file->getErrors()));
        exit;
    }
});
$app->get("/mailsubscription/:uid", function ($uid) {
    try {
        $mailSubscription = MailSubscription::getByUserId($uid);
        $subscribed = true;
    } catch (MailSubscriptionNotFoundException $e) {
        $subscribed = false;
    }
    outputJSON(array("subscribed" => $subscribed));
});
$app->get("/mailsubscription/subscribe/:uid", function ($uid) {
    try {
        $mailSubscription = MailSubscription::getByUserId($uid);
    } catch (MailSubscriptionNotFoundException $e) {
        $mailSubscription = new MailSubscription();
        $mailSubscription->setUser($uid);
        $mailSubscription->save();
    }
});
$app->get("/mailsubscription/unsubscribe/:uid", function ($uid) {
    try {
        $mailSubscription = MailSubscription::getByUserId($uid);
        $mailSubscription->delete();
    } catch (MailSubscriptionNotFoundException $e) {
示例#4
0
        $log->error("Missing primary key as PK was not in POST[] array");
        outputJSON("Missing Primary Key value for upload");
    } else {
        $pkId = $_POST['pkId'];
    }
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $originalFileName = $_FILES['file']['name'];
    if (in_array($ext, $blockedExt)) {
        $log->error("File extension is not supported for upload: " . $_FILES['file']['type']);
        outputJSON('Unsupported file type uploaded: ' . $_FILES['file']['type']);
    }
    $filenameTemp = transformFilename($_FILES['file']['name'], $_POST['pkId']);
    $log->debug("The FileMaker temporary name " . $filenameTemp);
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $filenameTemp)) {
        $log->error("Error uploading file: " . $_FILES['file']['name']);
        outputJSON("Error uploading file: " . $_FILES['file']['name']);
    }
    $log->debug("Copied temp file name: " . $_FILES['file']['tmp_name'] . " to file " . $filenameTemp);
    pushImageToFM($originalFileName, $filenameTemp, $pkId);
    $containerUrl = getFileContainerURL($pkId, $originalFileName);
    $containerStatus = "";
    if (empty($containerUrl)) {
        $containerStatus = "empty";
    } else {
        $containerStatus = "have_url";
    }
    returnJsonToAjax("success", $containerStatus, $containerUrl, $originalFileName);
}
function getFileContainerURL($pkId, $originalName)
{
    global $log, $fmOrderDB;
require_once "json_encode.php";
// Output JSON
function outputJSON($msg, $status = 'error')
{
    header('Content-Type: application/json');
    die(json_encode(array('data' => $msg, 'status' => $status)));
}
$allowed_exts = array("pdf", "doc", "docx", "xls", "xlsx", "gif", "jpg", "jpeg", "png", "txt", "rtf", "dot", "mp3");
// Check for errors
if ($_FILES['SelectedFile']['error'] > 0) {
    outputJSON('An error ocurred when uploading.');
}
// Check extension type
if (!in_array(end(split("\\.", $_FILES['SelectedFile']['name'])), $allowed_exts)) {
    outputJSON('File extension not allowed.');
}
// Check filesize - 20MB
if ($_FILES['SelectedFile']['size'] > 20971520) {
    outputJSON('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if (file_exists('upload/' . $_FILES['SelectedFile']['name'])) {
    outputJSON('File with that name already exists.');
}
// Upload file
if (!move_uploaded_file($_FILES['SelectedFile']['tmp_name'], 'upload/' . $_FILES['SelectedFile']['name'])) {
    outputJSON('Error uploading file - check destination is writeable.');
}
// Success!
outputJSON('File uploaded successfully to "' . 'upload/' . $_FILES['SelectedFile']['name'] . '".', 'success');
示例#6
0
            case "JSON":
                echo outputJSON($row);
                break;
            case "TEXT":
                echo outputText($row);
                break;
            case "YAML":
                echo outputYaml($row);
                break;
            case "ID":
                echo outputID($row);
                break;
            case "DUMP":
                echo outputDump($row);
                break;
            default:
                echo outputJSON($row);
                break;
        }
    }
}
if ($_GET['download'] == "true") {
    $updateQuery = "UPDATE `Books` SET `downloads` = :downloads WHERE `ID` = :id";
    $stmt = $db->prepare($updateQuery);
    $stmt->bindParam(':downloads', $downloads);
    $stmt->bindParam(':id', $ID);
    $stmt->execute();
}
?>
 
示例#7
0
include 'util.php';
header("Pragma: public");
header("Expires: 0");
$filename = 'db.php';
$templine = '';
initializeDB();
if (!file_exists($filename)) {
    addError("install.file.missing");
    outputJSON($errormsg);
} else {
    $lines = file($filename);
    foreach ($lines as $line_num => $line) {
        if (substr($line, 0, 2) != '--' && $line != '') {
            $templine .= $line;
            if (substr(trim($line), -1, 1) == ';') {
                try {
                    queryDB($templine);
                } catch (Exception $e) {
                    addError("error", $e->getMessage(), false);
                    debug_display($e);
                }
                $templine = '';
            }
        }
    }
    if (getErrorCount() > 1) {
        addError("error", "install.sql.error");
        outputJSON("error");
    }
}
示例#8
0
}
// Check filetype
if ($_FILES['SelectedFile']['type'] != 'audio/mp3') {
    outputJSON('Unsupported filetype.');
}
// Check filesize
if ($_FILES['SelectedFile']['size'] > 500000000) {
    outputJSON('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if (file_exists($path . $_FILES['SelectedFile']['name'])) {
    outputJSON('File with that name already exists.');
}
// Upload file
if (!move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $path . $_FILES['SelectedFile']['name'])) {
    outputJSON('Error uploading file - check destination is writeable.');
}
// Success!
//outputJSON('File uploaded successfully', 'success');
$file = "directory/music_dir.json";
$json_dir = json_decode(file_get_contents($file), true);
$dirArray = $json_dir['directory'];
$fullPath = $_FILES['SelectedFile']['name'];
$noExtension = substr($_FILES['SelectedFile']['name'], 0, -4);
$count = count($dirArray);
// index of new song
//$dirArray[$count]['artist'] = $_POST['artist'];
//$dirArray[$count]['title'] = $_POST['title'];
$dirArray[$count]['artist'] = getAuthor($noExtension);
$dirArray[$count]['title'] = getTitle($noExtension);
$dirArray[$count]['path'] = $noExtension;
示例#9
0
    //Assigning points to the $username
    //If n number of tasks is completed => the task is completed, assign points
    //============
    if ($researcher['confirms'] == $researcher['taskTestsNumber']) {
        $pointsGained = $points[$taskNumber];
        $sql_request = "UPDATE results SET code_task{$taskNumber}  = '{$parsedCode}' WHERE username = '******'";
        $sql_upd = "UPDATE results SET points = points + {$pointsGained} WHERE username = '******'";
        $connection->query($sql_upd);
        $connection->query($sql_request);
        $output_string = 'Output from cpp:<br><b> ' . '</b><br>' . $researcher['status'] . ' ' . $researcher['confirms'] . '/5' . '<br><br>' . implode(' ', $researcher['time']) . '    ' . implode(' ', $researcher['memory']) . '<br><br>' . implode(' ', $exec_comm) . '<br><br>also your code:<br><pre class="prettyprint">' . $parsedCode . '</pre>' . '<br>' . $taskNumber;
        if ($compiler != 'python') {
            unlink($uploadDir . $generatedRunnerName);
        }
        #УНИЧТОЖЕНИЕ
    }
} else {
    $output_string = "Task was completed already.";
}
unlink($uploadDir . $generatedSourceName);
//============
//Sending time of completion and number of attempts to the database
//=============
$x = date("d/m/Y H:i:s");
$sql_request1 = "UPDATE results SET task{$taskNumber} = '{$x}', attempt_task{$taskNumber} = attempt_task{$taskNumber} + 1 WHERE username = '******'";
if (!$connection->query($sql_request1)) {
    die('BD connection problems.');
}
//=============
//Succes!
outputJSON($output_string, "succes");
示例#10
0
            if (!rmdir($dir)) {
                $output[] = "failed to delete {$dir} .";
            }
        }
    }
    /// Drop the collection.
    $res = $col->drop();
    if (!$res['ok']) {
        $output[] = "failed to drop {$colName}.";
    }
}
/// Delete photo files in which the user/page is tagged.
$dir = "{$config['data_storage']}/photos/{$_GET['type']}_{$_GET['id']}";
if (is_dir($dir)) {
    foreach (scandir($dir) as $filename) {
        if (in_array($filename, ['.', '..'])) {
            continue;
        }
        if (!unlink("{$dir}/{$filename}")) {
            $output[] = "failed to delete {$dir}/{$filename} .";
        }
    }
    if (!rmdir($dir)) {
        $output[] = "failed to delete {$dir} .";
    }
}
/// Delete the document in the node collection.
$db->selectCollection($_GET['type'] . 's')->remove(['_id' => $_GET['id']]);
///< How to know whether it succeeds?
outputJSON(['status' => 'success', 'messages' => $output]);
示例#11
0
 */
function outputJSON($imageInfo, $callback)
{
    header('Content-type: text/plain');
    $jsonOutput = json_encode($imageInfo);
    if ($callback) {
        $jsonOutput = $callback . '(' . $jsonOutput . ');';
    }
    echo $jsonOutput;
}
// Get the image size and depth
$imageInfo = getImageInfo($zipPath, $file);
// Output json if requested
if ('json' == $ext) {
    // $$$ we should determine the output size first based on requested scale
    outputJSON($imageInfo, $callback);
    exit;
}
// Unfortunately kakadu requires us to know a priori if the
// output file should be .ppm or .pgm.  By decompressing to
// .bmp kakadu will write a file we can consistently turn into
// .pnm.  Really kakadu should support .pnm as the file output
// extension and automatically write ppm or pgm format as
// appropriate.
$decompressToBmp = true;
if ($decompressToBmp) {
    $stdoutLink = '/tmp/stdout.bmp';
} else {
    $stdoutLink = '/tmp/stdout.ppm';
}
$fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION));
示例#12
0
文件: upload.ajax.php 项目: rair/yacs
        $_SESSION['last_uploaded'][$name]['tmp_name'] = $path;
        // @see safe::is_uploaded_file()
        $_SESSION['last_uploaded']['pathes'][] = $path;
        $preview = Files::preview($path, $name);
        // Success!
        outputJSON('File uploaded successfully to "' . UPLOAD_PATH . $_FILES[$name]['name'] . '".', 'success', $preview);
    }
} elseif ($action === 'destroy') {
    if ($name === "all") {
        foreach ($_SESSION['last_uploaded'] as $up) {
            // destroy file
            if (isset($up['tmp_name'])) {
                Safe::unlink($up['tmp_name']);
            }
        }
        unset($_SESSION['last_uploaded']);
        outputJSON(i18n::s('all temporary file destroyed'), 'success');
    }
    if (isset($_SESSION['last_uploaded'][$name])) {
        $filename = $_SESSION['last_uploaded'][$name]['name'];
        // destroy file
        Safe::unlink($_SESSION['last_uploaded'][$name]['tmp_name']);
        // destroy session memory
        unset($_SESSION['last_uploaded'][$name]);
        outputJSON(sprintf(i18n::s('temporary file %s destroyed'), $filename), 'success', Skin::build_input_file($name));
    }
}
////// no direct access
Safe::header('Status: 401 Unauthorized', TRUE, 401);
Logger::error(i18n::s('You are not allowed to perform this operation.'));
render_skin();
示例#13
0
    outputJSON('File size exceeds maximum upload size');
}
//TODO Have we decided if the filename exists in directory we will not delete the file then replace the file???
if (file_exists('upload/' . $filenameTemp)) {
    outputJSON('File with that name already exists');
}
if (!move_uploaded_file($_FILES['SelectedFile']['tmp_name'], '../upload/' . $filenameTemp)) {
    $log->error("Error on moving file to upload location");
    outputJSON('Error uploading the file - check destination has write access');
}
//The file was successfully uploaded to the server now push the original filename and temp name to FileMaker view
pushDocumentDataToFM($originalFilename, $filenameTemp, $metaId);
if (isset($error)) {
    outputJSON($error);
}
outputJSON('upload/' . $filenameTemp, 'success');
/** Now replace the file name prefix with Meta __pk_ID */
function transformFilename($actual, $metapkId)
{
    $ext = pathinfo($actual, PATHINFO_EXTENSION);
    return $metapkId . "." . $ext;
}
//This method opens the WEB Meta View version and pushes filename and original name to the text fields below:
//Upload_Filename_Original_t	---> this represent the actual file name like 'a.png'
//Upload_Filename_Temp_t		---> this represents the Meta _pk_ID prefix with extension
function pushDocumentDataToFM($original, $temp, $pkId)
{
    global $fmOrderDB, $log;
    /* TODO need to investigate why getRelatedRecords() Stopped Working */
    $metaFind = $fmOrderDB->newFindCommand('[WEB] Project Meta Fields');
    $metaFind->addFindCriterion('__pk_ID', '==' . $pkId);
示例#14
0
function getQuestions()
{
    $type = "general";
    if (isset($_GET['type']) && $_GET['type'] != "") {
        $type = $_GET["type"];
    }
    $allowedtypes = array("top10" => "top10", "general" => "general");
    if (!array_key_exists($type, $allowedtypes)) {
        addError("parameter_error", "getquestion.parameter.error");
        outputJSON("error");
        return;
    }
    $results = array();
    if (strcmp($type, "top10") == 0) {
        $results = getTop10Questions();
    }
    echo json_encode($results);
}