public function login() { $params = request()->all(); $user = auth()->attempt($params); if (auth()->check()) { return jsonSuccess($user); } else { return jsonError('登录失败', '4011'); } }
function getInnerValue(&$obj, $innerVar) { if (substr($innerVar, 0, 1) != ".") { jsonError("invalid variable name"); } $nextIndex = strpos($innerVar, ".", 1); if ($nextIndex !== FALSE) { // recurse $nextVarName = substr($innerVar, 1, $nextIndex - 1); if (!is_array(@$obj[$nextVarName])) { return NULL; } return getInnerValue($obj[$nextVarName], substr($innerVar, $nextIndex), $value); } else { return $obj[substr($innerVar, 1)]; } }
function validatePrivileges($privileges = array(), $no_error = false) { return function () use($privileges, $no_error) { try { // Inicjalizacja modelu użytkownika $user = new \Model\User(); // Pobranie instancji szkieletu Slim Framework $app = \Slim\Slim::getInstance(); // Pobranie tokenu z pola Authorization nagłówka HTTP i jego walidacja $token = validateToken($app->request->headers->get('Authorization')); try { // Pobranie danych uzytkownika o zadanym tokenie $u = $user->getByToken($token, 'administrator'); } catch (Exception $e) { throw new Exception('Użytkownik nie jest zalogowany.', 401); } // Sprawdzenie wymaganych uprawnień if (!in_array($u['privileges'], $privileges)) { throw new Exception('Brak uprawnień.', 401); } // Zapamiętanie danych potrzebnych do logowania jako zmienne globalne $GLOBALS['user_id'] = $u['user_id']; $GLOBALS['token'] = $token; $GLOBALS['privileges'] = $u['privileges']; try { // Jeśli różnica pomiędzy ostatnią aktywnością, a bierzącym czasem // wynosi 60 sekund, to odświeżamy autoryzację $diff = abs(strtotime(date('Y-m-d H:i:s')) - strtotime($u['last_auth'])); if ($diff > 60) { $res = $user->refreshAuth($token); } } catch (Exception $e) { } } catch (Exception $e) { $GLOBALS['user_id'] = -1; $GLOBALS['token'] = ''; $GLOBALS['privileges'] = 'guest'; if (!$no_error) { jsonError($app, $e, true); } } }; }
/** * procore.json.php * @author Adam Lee & Yaakov Albietz - ejectcore.com * @copyright Copyright Eject Core 2009-2010. All rights reserved. * @license GPLv3 License http://www.gnu.org/licenses/gpl-3.0.html * @credit 3rd Party Development: Seth Benjamin * @package Pro Core Manager API * @version v1.0 Final * */ function bootstrap() { if (isset($_GET['act'])) { include realpath(dirname(__FILE__) . '/../../../') . '/config/config.inc.php'; include realpath(dirname(__FILE__) . '/../../../') . '/init.php'; if (file_exists('procore.api.php')) { include_once 'procore.api.php'; $api = new ProCoreApi($smarty); $action = isset($_GET['act']) ? $_GET['act'] : FALSE; $reference = isset($_GET['reference']) ? $_GET['reference'] : FALSE; $data = isset($_GET['data']) ? $_GET['data'] : FALSE; if ($action !== FALSE) { $output = $api->moduleAction($action, $reference, $data); } else { jsonError('Error: Action not defined.'); } return $output; } else { return jsonError('Fatal Error: Core Manager API could not be located'); } } }
print mysql_affected_rows() . " DELETED\n \n"; } else { if (preg_match("/^insert/i", $x)) { print mysql_affected_rows() . " INSERTED\n \n"; } } } } return $res; } require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php"; require_once dirname(__FILE__) . "/../../common/php/dbMySqlWrappers.php"; require_once dirname(__FILE__) . "/../../records/edit/deleteRecordInfo.php"; if (!is_logged_in()) { jsonError("no logged-in user"); } $_REQUEST = json_decode(@$_POST["data"] ? $_POST["data"] : base64_decode(@$_GET["data"]), true); mysql_connection_overwrite(DATABASE); mysql_query("start transaction"); $out = deleteRecord(@$_REQUEST["id"]); if (array_key_exists("error", $out)) { jsonError($out["error"]); } mysql_query("commit"); print json_format($out); function jsonError($message) { mysql_query("rollback"); print "{\"error\":\"" . addslashes($message) . "\"}"; exit(0); }
if (preg_match("/^insert/i", $x)) { print mysql_affected_rows() . " INSERTED\n \n"; } } } } return $res; } require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php"; require_once dirname(__FILE__) . "/../../common/php/dbMySqlWrappers.php"; require_once dirname(__FILE__) . "/../../common/php/saveRecord.php"; require_once dirname(__FILE__) . "/../../common/php/utilsTitleMask.php"; // 26/3/14 Functions to index record being saved using Elastic Search (Lucene) require_once dirname(__FILE__) . "/../../records/index/elasticSearchFunctions.php"; if (!is_logged_in()) { jsonError("no logged-in user"); } $_REQUEST = json_decode(@$_POST["data"] ? $_POST["data"] : base64_decode(@$_GET["data"]), true); mysql_connection_overwrite(DATABASE); mysql_query("start transaction"); $out = saveRecord(@$_REQUEST["id"], @$_REQUEST["type"], @$_REQUEST["url"], @$_REQUEST["notes"], @$_REQUEST["group"], @$_REQUEST["vis"], @$_REQUEST["bookmark"], @$_REQUEST["pnotes"], @$_REQUEST["rating"], @$_REQUEST["tags"], @$_REQUEST["wgTags"], @$_REQUEST["detail"], @$_REQUEST["-notify"], @$_REQUEST["+notify"], @$_REQUEST["-comment"], @$_REQUEST["comment"], @$_REQUEST["+comment"]); mysql_query("commit"); // 26/3/14 Add record to index in Elastic Search (Lucene) updateRecordIndexEntry(HEURIST_DBNAME, @$_REQUEST["type"], @$_REQUEST["id"]); print json_format($out); function jsonError($message) { mysql_query("rollback"); print "{\"error\":\"" . addslashes($message) . "\"}"; exit(0); }
function ajaxController($path, $request) { global $smarty, $dao, $error; list($reqPath, $queryString) = explode('?', $path); $pathParts = explode('/', substr($reqPath, 1)); list($action) = $pathParts; session_start(); $authnStatus = checkAuthn(); if (!isLoggedIn()) { echo "AUTHN_FAILED"; die; } switch ($action) { case 'main': echo "null"; break; case 'submitForm': $data = $request["formData"]; $userId = $_SESSION["loginId"]; $title = $data["title"]; $formData = $data["content"]; $xml = $request["xml"]; if (!validate_project_name($title)) { jsonError(TITLE_INVALID, "Your form's name is invalid."); } if (count($data["content"]) > 10) { jsonError(FORM_OVERFLOW, "Your form is too large. 10 controls may be present in a form. You have " . count($data["content"]) . "."); } if ($dao->checkFormName($title, $userId)) { jsonError(FORM_NAME_EXISTS, "You already have a form with the same name. Please choose another name."); } $dao->newForm($title, $userId, $formData, $xml); break; case 'updateForm': $data = $request["formData"]; $userId = $_SESSION["loginId"]; $title = $data["title"]; $formData = $data["content"]; $xml = $request["xml"]; if (count($data["content"]) > 10) { jsonError(FORM_OVERFLOW, "Your form is too large. 10 controls may be present in a form. You have " . count($data["content"]) . "."); } $dao->updateForm($title, $userId, $formData, $xml); break; case 'listForms': $formList = json_encode($dao->listForms($_SESSION["loginId"])); echo $formList; break; case 'loadForm': $data = $request["formData"]; $title = $data["title"]; $userId = $_SESSION["loginId"]; $formData = $dao->loadForm($userId, $title); $responseObject = '{"title": "' . $title . '", "description" : "", "owner" : "foo", "controls" :' . $formData . ' , "id": "xwfsdfs"}'; echo $responseObject; break; case 'username': echo $_SESSION["loginEmail"]; break; case 'renameExpedition': $data = $request["expData"]; $expId = $data["expId"]; $newName = $data["name"]; if (!validate_project_name($newName)) { jsonError(TITLE_INVALID, "Your expedition's name is invalid."); } $dao->renameExpedition($expId, $newName); break; case 'getFindTimeStamps': $data = $request["projectData"]; $projectId = $data["projId"]; $lastUpdate = $dao->getLastFindTime($projectId); echo $lastUpdate; break; case 'updateFinds': $data = $request["projectData"]; $projectId = $data["projId"]; $projectTime = $data["projTime"]; $newFinds = $dao->getFinds($projectId, $projectTime); if (count($newFinds) >= 1) { echo json_encode($newFinds); } break; case 'getTimeStamps': $data = $request["expData"]; $expId = $data["expId"]; if ($data["expId"] != "") { $lastUpdate = $dao->getLastUpdate($expId); echo $lastUpdate; } break; case 'updateTracks': $data = $request["expData"]; $expId = $data["expId"]; $expTime = $data["expTime"]; if ($expId != "") { $newPoints = $dao->getNewPoints($expId, $expTime); if (count($newPoints) >= 1) { echo json_encode($newPoints); } } break; default: header("Location: main"); } }
* @package Heurist academic knowledge management system * @todo **/ require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php"; require_once dirname(__FILE__) . "/../../common/php/dbMySqlWrappers.php"; require_once dirname(__FILE__) . "/../../common/php/saveRecord.php"; require_once dirname(__FILE__) . "/../../common/php/utilsTitleMask.php"; if (!is_logged_in()) { jsonError("no logged-in user"); } $_REQUEST = json_decode(@$_POST["data"] ? $_POST["data"] : base64_decode(@$_GET["data"]), true); mysql_connection_overwrite(DATABASE); /* check if there are any records identified only by their hhash values */ if (!is_logged_in()) { // must be logged into save jsonError("invalid workgroup"); } $nonces = array(); $retitleRecs = array(); $addRecDefaults = @$_SESSION[HEURIST_SESSION_DB_PREFIX . 'heurist']["display-preferences"]['addRecDefaults']; if ($addRecDefaults) { if ($addRecDefaults[0]) { $userDefaultRectype = intval($addRecDefaults[0]); } if ($addRecDefaults[1]) { $userDefaultOwnerGroupID = intval($addRecDefaults[1]); } if ($addRecDefaults[2]) { $userDefaultVisibility = $addRecDefaults[2]; } }
* @package Heurist academic knowledge management system * @todo **/ require_once dirname(__FILE__) . "/../../common/connect/applyCredentials.php"; require_once dirname(__FILE__) . "/../../common/php/dbMySqlWrappers.php"; function jsonError($message) { print "{\"error\":\"" . addslashes($message) . "\"}"; exit(0); } if (!is_logged_in()) { jsonError("no logged-in user"); } $label = @$_REQUEST["label"]; $wg = intval(@$_REQUEST["wg"]); $ssid = intval(@$_REQUEST["ssid"]); if ($label && $ssid) { jsonError("missing argument (id or label) for saved search deletion"); } mysql_connection_overwrite(DATABASE); if ($ssid > 0) { mysql_query("delete from usrSavedSearches where svs_ID={$ssid}"); } else { if ($wg > 0) { //OLD WAY mysql_query("delete from usrSavedSearches where svs_Name='{$label}' and svs_UGrpID={$wg}"); } else { mysql_query("delete from usrSavedSearches where svs_Name='{$label}' and svs_UGrpID=" . get_user_id()); } } print "{\"deleted\":" . (mysql_affected_rows() > 0 ? "true" : "false") . "}";
} } if ($action == "doMod") { $paramKey = isset($_REQUEST["paramKey"]) ? $_REQUEST["paramKey"] : ""; $paramValue = isset($_REQUEST["paramValue"]) ? $_REQUEST["paramValue"] : ""; if (trim($paramKey) == "") { jsonError("fail", "paramKey is NULL"); } $param = new param(); $result = $param->setParamValue($paramKey, $paramValue); switch ($result) { case "success": jsonError("succ"); break; case "error": jsonError("fail", $param->getActionError()); break; } } if ($action == "doAdd") { $param = new param(); $result = $param->add(); switch ($result) { case "success": error("添加成功!", "alertGoTo", $_SERVER['HTTP_REFERER']); break; case "error": error($news->getActionError(), "alertGoTo", $_SERVER['HTTP_REFERER']); break; } }
<?php /** * 用户密码修改 * */ if ($action == "userPasswordModi") { $user = new user(); $result = $user->ModiPassword(); switch ($result) { case "success": jsonError("success"); break; case "error": jsonError("error", $user->getActionError()); break; } }
throw new Exception('Niekompletne dane.', 400); } $notify_text = validateString('wiadomość', $postVars['notify_text'], 6, 2048); $result = $thread->notify($id, $notify_text); $email_to = implode(',', $result); $subject = 'Powiadomienie'; $message = $notify_text . " \nJeśli nie chcesz otrzymywać wiadomości e-mail, zaloguj się na www.bariery.wroclaw.pl i wycofaj subskrypcję dla zgłoszeń."; $headers = 'From: admin@bariery.wroclaw.pl' . "\r\n" . 'Reply-To: no-reply@bariery.wroclaw.pl' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $subject, $message, $headers); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->delete('/id/:id', validatePrivileges(array('administrator')), function ($id) use($app, $thread) { try { $result = $thread->delete($id); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); $app->delete('/marker/id/:id', validatePrivileges(array('administrator')), function ($id) use($app, $thread) { try { $result = $thread->deleteMarker($id); jsonSuccess($app, $result); } catch (Exception $e) { jsonError($app, $e); } }); });
function settings($project_id = null) { // Edit Project Settings $project_id = intval($project_id); $this->Project =& ClassRegistry::init('Project'); $this->Project->contain(array('State.Step' => array('Condition', 'Action'))); $conditions = array('Project.id' => $project_id, 'Project.user_id' => $this->DarkAuth->id, 'Project.live' => 1); $project = $this->Project->find('first', compact('conditions')); if (empty($project)) { $this->_Flash('Unable to find Project', 'mean', '/'); } // Must be my project if ($project['Project']['user_id'] != $this->DarkAuth->id) { $this->_Flash('Invalid project chosen', 'mean', $this->referer('/')); } if ($this->RequestHandler->isGet()) { $this->data = $project; return; } // Parse input // - type cannot be changed App::import('Sanitize'); $data = array(); $data['id'] = $project['Project']['id']; $data['enable_state'] = intval($this->data['Project']['enable_state']); // Save if (!$this->Project->save($data, false, array_keys($data))) { echo jsonError(101, 'Failed saving Project Settings'); exit; } echo jsonSuccess('Settings Saved'); exit; }
case 'zayav_spisok': $_POST['find'] = win1251($_POST['find']); $data = zayav_spisok($_POST); if ($data['filter']['page'] == 1) { $send['all'] = utf8($data['result']); } $send['spisok'] = utf8($data['spisok']); jsonSuccess($send); break; case 'zayav_status': if (!($zayav_id = _num($_POST['zayav_id']))) { jsonError(); } if (!($zayav_status = _num($_POST['status']))) { jsonError(); } $sql = "SELECT * FROM `zayav` WHERE `ws_id`=" . WS_ID . " AND !`deleted` AND `id`=" . $zayav_id; if (!($z = query_assoc($sql))) { jsonError(); } if ($z['status'] == $zayav_status) { jsonError(); } $sql = "UPDATE `zayav`\n\t\t\t\tSET `status`=" . $zayav_status . ",\n\t\t\t\t\t`status_dtime`=CURRENT_TIMESTAMP\n\t\t\t\tWHERE `id`=" . $zayav_id; query($sql); _history(array('type_id' => 71, 'client_id' => $z['client_id'], 'zayav_id' => $zayav_id, 'v1' => $z['status'], 'v2' => $zayav_status)); jsonSuccess(); break; } jsonError();
<?php include_once '../lib/functions.php'; include_once 'config.php'; switch ($_GET['action']) { case 'channel_thumbnail': $feed = $_GET['feed']; //XXX: Further feed validation is in order. if (!preg_match("/\\/(r|domain)\\//", $feed)) { jsonError('Invalid feed.'); } if ($cacheAvailable) { $thumbnail_url = $memcache->get("chthmb-{$feed}"); if (!empty($thumbnail_url)) { $channel = new stdClass(); $channel->feed = $feed; $channel->thumbnail_url = $thumbnail_url; $channel->data_source = 'memcache'; jsonForAjax(array($channel)); } } //Reload the bean $channel = R::findOne('channel', ' feed = ?', array($feed)); if (empty($channel) || empty($channel->thumbnail_url)) { if (empty($channel)) { $channel = R::dispense('channel'); } $channel->feed = $feed; $channel->thumbnail_url = getChannelThumbnail($feed); //Store the bean $id = R::store($channel);
function error($str = "", $id = "", $type = "html", $show = "die") { $debug = debug_backtrace(); //print_r($debug); if (Q_DEBUG == true) { $d = $debug[0]; $d = array("file" => $debug["file"], "line" => $debug["line"], "function" => $debug["function"], "args" => $debug["args"]); $_d = "trace:\r\n\t\t\t<br> <b>[file:]</b>{$d["file"]}\r\n\t\t\t<br> <b>[line:]</b>{$d["line"]}\r\n\t\t\t<br> <b>[function:]</b>{$d["function"]}\r\n\t\t\t"; } $t = date("Y-m-d H:i:s", time()); $str = !empty($str) ? $str : "Unknow Error"; $ROOT = "http://" . $_SERVER["HTTP_HOST"] . "/ErrList.php?ERR_ID={$id}"; $json_err_id = $id; $id = empty($id) ? "" : "<br><b>Visit For More:</b><a target='_blank' style='font-size:12px; color:#357dce' href='{$ROOT}'>{$id}</a>"; if ($type == "html") { if ($show == "echo") { echo "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body><div style='font-family:Verdana; background:url(http://" . $_SERVER["HTTP_HOST"] . "/src/img/error.gif) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px;font-size:12px; border:1px solid #8cb7d7; margin:10px; color:#369'><br><b>Error:</b>{$str}{$id}<br><b>Time:{$t}</b><br>{$_d}</div></body></html></body>"; return; } elseif ($show == "button") { die("<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body><div style='font-family:Verdana;background:url(http://" . $_SERVER["HTTP_HOST"] . "/src/img/error.gif) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px;font-size:12px; border:1px solid #8cb7d7; margin:10px; color:#369'><br><b>Error:</b>{$str}{$id}<br><b>Time:{$t}</b><br>{$_d}<br><input type='button' onclick='window.close();' value='关闭'></div></body></html></body>"); return; } else { die("<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body><div style='font-family:Verdana;background:url(http://" . $_SERVER["HTTP_HOST"] . "/src/img/error.gif) #F6FBFF no-repeat 0px 0px; height:117px; overflow-x: hidden; overflow-y: auto; width:550px; padding-left:140px; font-size:12px; border:1px solid #8cb7d7; margin:10px; color:#369'><br><b>Error:</b>{$str}{$id}<br><b>Time:</b>{$t}<br>{$_d}</div></body></html>"); } } if ($type == "json") { $ROOT = empty($json_err_id) ? "" : "for the error, visit <a href='http://{$_SERVER["HTTP_HOST"]}/ErrList.php?ERR_ID={$json_err_id}' style='display:block;font-size:12px; ' target='_blank'>this -> {$json_err_id}</a>"; jsonError("fail", $str . "{$ROOT} @" . $t, $debug); } if ($show == "echo") { echo $str . " " . $id . " @" . $t . $_d; } elseif ($show == "asasdasdasda") { } else { die($str . " " . $id . " @" . $t); } }
case "success": error("添加成功!", "alertGoTo", $_SERVER['HTTP_REFERER']); break; case "error": error($news->getActionError(), "alertGoTo", $_SERVER['HTTP_REFERER']); break; } } if ($action == "doRm") { $id = isset($_POST["id"]) ? intval($_POST["id"]) : ""; if (empty($id)) { jsonError("fail", "id为空"); } $sql = "delete {$mysqlConfig["db_perfix"]}web_news where id = {$id} limit 1"; sqlExecute($sql, "", "json"); jsonError("succ"); } if ($action == "doMod") { $news = new news(); $result = $news->modi(); switch ($result) { case "success": error("添加成功!", "alertGoTo", $_SERVER['HTTP_REFERER']); break; case "error": error($news->getActionError(), "alertGoTo", $_SERVER['HTTP_REFERER']); break; } } jsonError("fail", "action is null");
function move($action_id = null, $order = null, $step_id = null) { // Move a Action somewhere $action_id = intval($action_id); $order = intval($order); $step_id = intval($step_id); // Only used when moving to a new Step // Re-order every element (right?) if ($this->RequestHandler->isGet()) { echo jsonError(101, 'Expecting POST'); exit; } // Get Action $this->Action =& ClassRegistry::init('Action'); $this->Action->contain(array('Step.State.Project')); $conditions = array('Action.id' => $action_id, 'Action.live' => 1); $action = $this->Action->find('first', compact('conditions')); if (empty($action)) { $this->_Flash('Unable to find Action', 'mean', $this->referer('/')); } // Must be my Action if ($action['Step']['State']['Project']['user_id'] != $this->DarkAuth->id) { $this->_Flash('Not your Action', 'mean', $this->referer('/')); } // Moving Steps? $this->Step =& ClassRegistry::init('Step'); if ($step_id != $action['Action']['step_id']) { // Validate the new step $this->Step->contain(array('State.Project')); $conditions = array('Step.id' => $step_id, 'Step.live' => 1); $step = $this->Step->find('first', compact('conditions')); // Step Exists? if (empty($step)) { echo jsonError(101, 'Not in a step'); exit; } // My Step? if ($step['State']['Project']['user_id'] != $this->DarkAuth->id) { echo jsonError(101, 'Not your Step'); exit; } $action['Action']['step_id'] = $step['Step']['id']; } $action['Action']['order'] = $order; $this->Action->save($action['Action']); echo jsonSuccess(); exit; }
$cmd = getScriptCmd($script); if ($DEBUG) { jsonDebug("SCRIPT-COMMAND", $cmd); } $rc = -1; $output = execScript($script, $rc); $res['result'][] = array($cmd, $rc, $output); $res['duration'] = durationStop($start); echo json_encode($res); } elseif (isset($probeConf['CMD'])) { $cmds = expandCommand($probeConf['CMD']); if ($DEBUG) { jsonDebug("EXPANDED COMMAND", $cmds); } foreach ($cmds as $cmd) { $rc = -1; $output = execCommand($cmd, $rc); $res['result'][] = array($cmd, $rc, $output); } $res['duration'] = durationStop($start); echo json_encode($res); } else { jsonError('CONF', "invalid probe-config", array('probe' => $probeID)); } } catch (InvalidCommandException $e) { $details = array('probe' => $probeID, 'cmd' => $e->cmd); jsonError('EXEC', $e->getMessage(), $details); } catch (Exception $e) { $details = array('probe' => $probeID); jsonError('EXEC', $e->getMessage(), $details); }
echo json_encode(array('type' => 'error', 'message' => $errorMessage)); exit; } function jsonSuccess($message, array $seatChanges) { echo json_encode(array('type' => 'success', 'message' => $message, 'seatChanges' => $seatChanges)); exit; } if (!Session::isLoggedIn()) { jsonError('You are not logged in!'); } $status = getSignupStatus(Session::getUser()->getId(), $event['id']); if ($status != 'PAID' && $status != 'CONFIRMED' && $status != 'PAYPAL_WAITING' && $status != 'STAFF') { jsonError("You haven't paid for a ticket!"); } if (getUserInSeat($event['id'], $seat)) { jsonError("That seat is already occupied!"); } $seatChanges = array(); $currentSeats = getSeatForUser($event['id']); foreach ($currentSeats as $itemCurrentSeat) { $seatChanges[] = getJsonSeatChange('delete', $itemCurrentSeat['seat'], Session::getUser()->getUsername()); } deleteSeatsForUser($event['id']); setUserInSeat($event['id'], $seat); $seatChanges[] = getJsonSeatChange('set', $seat, Session::getUser()->getUsername()); jsonSuccess('Seat selected!', $seatChanges); ?>
function checkCsrfToken() { if (!constant_time_compare(CSRF_TOKEN, $_POST['csrf_token'])) { jsonError('Invalid CSRF token'); } }
/** * the main apiController function that outputs json_encoded results * @param $path * @param $request * @param $files */ function apiController($path, $request, $files = null) { global $dao, $smarty; list($reqPath, $queryString) = explode('?', $path); $pathParts = explode('/', substr($reqPath, 1)); list($action) = $pathParts; Log::getInstance()->log("Reached server"); Log::getInstance()->log("{$path} , {$request}"); if ($action != "addExpeditionPoint" && $action != "getDeviceByAuthKey") { $log = Log::getInstance(); $log->log("{$action}"); $log->log("{$path}, {$request}"); } $authKey = $request["authKey"]; if ($action != "isreachable" && $action != "login" && $action != "registerUser" && $action != "registerDevice" && $action != "getPendingDeviceStatus" && !$authKey) { $response = array("errorCode" => ERR_AUTHKEY_MISSING, "errorMessage" => "You must provide an authentication key with each request."); echo json_encode($response); die; } if ($action != isreachable && $action != "login" && $action != "registerUser") { $device = $dao->getDeviceByAuthKey($authKey); if ($action != "registerDevice" && $action != "getPendingDeviceStatus" && !$device) { $response = errorResponseCode(ERR_AUTHKEY_INVALID, "Invalid authentication key."); echo json_encode($response); die; } $deviceUserId = $device["user_id"]; $deviceIdentifier = $device["imei"]; } switch ($action) { case 'isreachable': jsonMessage(AUTHN_OK, "The server is reachable"); break; case 'login': extract($request); Log::getInstance()->log("Login = {$request} email={$email} imei={$imei}"); if (!$email) { jsonError(ERR_EMAIL_MISSING, "Email Address is required"); } else { if (!validate_email_address($email)) { jsonError(ERR_EMAIL_INVALID, "Email Address is invalid"); } } if (!$password) { jsonError(ERR_PASSWORD_MISSING, "Password is required"); } // NOTE: Tablets don't have imei. So this will only work for phones. // if (!$imei){ // jsonError(ERR_IMEI_MISSING, "IMEI Code is required"); // } if ($login = $dao->checkLogin($email, $password)) { $authKey = genAuthKey(); $userId = $login["id"]; if ($dao->registerDevicePending($userId, $authKey)) { jsonMessage(AUTHN_OK, $authKey); } else { jsonError(ERR_SERVER, "Authentication Key cannot be generated"); } } else { jsonError(AUTHN_FAILED, "Authentication failed. Please Check email address or password."); } break; case 'registerUser': extract($request); if (!$email) { jsonError(ERR_EMAIL_MISSING, "Email Address is required"); } else { if (!validate_email_address($email)) { jsonError(ERR_EMAIL_INVALID, "Email Address is invalid"); } } if (!$firstname) { jsonError(ERR_FIRSTNAME_MISSING, "Firstname is required"); } if (!$lastname) { jsonError(ERR_LASTNAME_MISSING, "LastName is required"); } if (strlen($password1) < 6) { jsonError(ERR_PASSWORD1_INVALID, "Password must be 6 characters or longer"); } if ($password1 != $password2) { jsonError(ERR_PASSWORD_UNMATCHED, "Passwords must match"); } $newUser = array($email, $firstname, $lastname, $password1); $result = $dao->registerUser($newUser); if ($result === REGISTRATION_EMAILEXISTS) { jsonError(ERR_EMAIL_INVALID, "Email already exists"); } $smarty->assign('link', SERVER_BASE_URI . "/web/verifyEmail?email={$email}"); sendEmail($email, "email verification", $smarty->fetch("emails/new_user.tpl")); jsonMessage(AUTHN_OK, "Registration Successful"); break; case 'getDeltaFindsIds': echo $dao->getDeltaFindsIds($authKey, $request["projectId"]); break; case 'recordSync': $projectId = -1; if ($request["projectId"]) { $projectId = (int) $request["projectId"]; } echo $dao->recordSync($request["imei"], $authKey, $projectId); //echo $dao->recordSync($deviceIdentifier, $authKey); break; case 'registerDevice': $imei = $request["imei"]; $name = null; if (strstr($authKey, "sb_")) { $result = $dao->addSandboxDevice($authKey, $imei); } else { $result = $dao->confirmDevice($authKey, $imei, $name); } echo json_encode($result); break; case 'addExpedition': echo $dao->addExpedition($request["projectId"]); break; case 'addExpeditionPoint': echo $request["expedition"] . ","; echo $dao->addExpeditionPoint($request["expedition"], $request["latitude"], $request["longitude"], $request["altitude"], $request["swath"], $request["time"]); break; case 'getPendingDeviceStatus': $device = $dao->getDeviceByAuthKey($authKey); if ($device["status"] == "ok") { echo json_encode($device); } else { echo json_encode(false); } break; case 'listOpenProjects': $result = $dao->getProjects(PROJECTS_OPEN); echo json_encode($result); break; case 'listMyProjects': $result = $dao->getUserProjects($deviceUserId); echo json_encode($result); break; case 'newProject': extract($request); if (!$name) { jsonError(ERR_NAME_INVALID, "Project name is invalid."); } $result = $dao->newProject($name, $description, $deviceUserId); if (is_string($result)) { jsonMessage(PROJ_CREATE_SUCCESS, "Project created successfully."); } else { jsonError(PROJ_CREATE_FAIL, "Project creation failed."); } break; case 'projectExists': if ($request["projectId"]) { echo $dao->projectExists($request["projectId"]); } break; case 'listFinds': echo json_encode($dao->getFinds($request["project_id"])); break; case 'getFind': $result = $dao->getFind($request["guid"]); echo json_encode($result); break; case 'deleteFind': echo $dao->deleteFind($request["id"]); break; case 'deleteProject': $dao->deleteProject($request["projectId"]); break; case 'deleteAllFinds': $dao->deleteAllFinds($request["projectId"]); break; case 'createFind': echo $dao->createFind($authKey, $request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["latitude"], $request["longitude"], $request["revision"], $request["data"]); break; case 'updateFind': echo $dao->updateFind($authKey, $request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["revision"], $request["data"], $request["latitude"], $request["longitude"]); break; case 'attachPicture': $imagedata = base64_decode($request["data_full"]); $imagethumbdata = base64_decode($request["data_thumbnail"]); $result = $dao->addPictureToFind($request["imei"], $request["guid"], $request["identifier"], $request["project_id"], $request["mime_type"], $request["timestamp"], $imagedata, $imagethumbdata, $authKey); echo json_encode($result); break; case 'attachVideo': $video_data = $files['file']['tmp_name']; $video_type = $request["mimeType"]; $video_name = str_replace(' ', '_', $files["file"]["name"]); move_uploaded_file($video_data, "uploads/{$video_name}"); $result = $dao->addVideoToFind($request['id'], $request["findId"], $video_type, $video_name); return $result; break; case 'attachAudio': $audio_data = $files['file']['tmp_name']; $audio_type = $request["mimeType"]; $audio_name = str_replace(' ', '_', $files["file"]["name"]); move_uploaded_file($audio_data, "uploads/{$audio_name}"); $result = $dao->addAudioClipToFind($request['id'], $request["findId"], $audio_type, $audio_name); return $result; break; case 'removePicture': $dao->deletePictureFromFind($request["id"]); break; case 'removeVideo': $dao->deleteVideoFromFind($request["id"]); break; case 'removeAudioClip': $dao->deleteAudioClipFromFind($request["id"]); break; case 'deleteAllPictures': $dao->deleteImages($request["findId"]); break; case 'deleteAllVideos': $dao->deleteVideos($request["findId"]); break; case 'deleteAllAudioClips': $dao->deleteAudioClips($request["findId"]); break; case 'getPicture': $picture = $dao->getPicture($request["id"]); $imageEncoded = base64_encode($picture["data_full"]); $imageThumbEncoded = base64_encode($picture["data_thumb"]); $pictureEncoded = $picture; if ($imageEncoded != "") { $pictureEncoded["data_full"] = $imageEncoded; } if ($imageThumbEncoded != "") { $pictureEncoded["data_thumb"] = $imageThumbEncoded; } if (count($pictureEncoded) > 0) { echo json_encode($pictureEncoded); } else { echo "false"; } break; case 'getPicturesByFind': $pictures = $dao->getPicturesByFind($request["guid"]); $result = array(); foreach ($pictures as $pic) { $imageEncoded = base64_encode($pic["data_full"]); $imageThumbEncoded = base64_encode($pic["data_thumb"]); $pictureEncoded = $pic; if ($imageEncoded != "") { $pictureEncoded["data_full"] = $imageEncoded; } if ($imageThumbEncoded != "") { $pictureEncoded["data_thumb"] = $imageThumbEncoded; } if (count($pictureEncoded) > 0) { $result[] = $pictureEncoded; } } if (count($result) > 0) { echo json_encode($result); } else { echo "false"; } break; case 'getVideo': $video = $dao->getVideo($request["id"]); $video_name = $video["data_path"]; $video_path = "uploads/{$video_name}"; $fp_v = fopen($video_path, 'r'); $video_data = fread($fp_v, filesize($video_path)); $videoEncoded = base64_encode($video_data); $clipEncoded = $video; $clipEncoded["data_full"] = $videoEncoded; echo json_encode($clipEncoded); break; case 'getAudio': $audio = $dao->getAudioClip($request["id"]); $audio_name = $audio["data_path"]; $audio_path = "uploads/{$audio_name}"; $fp_v = fopen($audio_path, 'r'); $audio_data = fread($fp_v, filesize($audio_path)); $audioEncoded = base64_encode($audio_data); $clipEncoded = $audio; $clipEncoded["data_full"] = $audioEncoded; echo json_encode($clipEncoded); break; case 'searchFinds': $search_value = $request['search_value']; $project_id = $request['project_id']; $result = $dao->searchFinds($search_value, $project_id); echo json_encode($result); break; case 'execCommand': $command = $request['command']; echo $dao->execCommand($command); break; default: break; } }
/** * 输出json * * @param string $state * @param string $msg * @param string $error * @param string $type * @return string | json */ function error($str = "", $type = "die", $href = "") { //global $debug; $str = !empty($str) ? $str : "未定义的错误"; $ACTION_ERRORS = $str; if (is_array($str)) { $ACTION_ERRORS = ""; foreach ($str as $k => $v) { $ACTION_ERRORS = "<B>[" . $k . "]</B>" . $v . "<BR>"; } } $href = !empty($href) ? $href : "#"; $err_img = WEB_PATH . "src/img/icon_error.gif"; $debug = debug_backtrace(); $debug = $debug[0]; //print_r($debug); $d = array("file" => $debug["file"], "line" => $debug["line"], "function" => $debug["function"], "args" => $debug["args"]); $_d = ""; if (debug) { $_d = "trace:\r\n\t\t\t<br> <b>[file:]</b>{$d["file"]}\r\n\t\t\t<br> <b>[line:]</b>{$d["line"]}\r\n\t\t\t<br> <b>[function:]</b>{$d["function"]}\r\n\t\t\t"; } $head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'; switch ($type) { /* goBack */ case "goBack": die("<html>{$head} <body><script>\r\n\t\t\tsetTimeout('history.back()', 2000);\t\t\t\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "<br>正在返回...</div></body></html>"); break; /* alertGoBack */ /* alertGoBack */ case "alertGoBack": die("<html>{$head} <body><script>\r\n\t\t\tvar str = " . json_encode($str) . ";\r\n\t\t\talert(str);\r\n\t\t\thistory.back();\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; /* alert */ /* alert */ case "alert": die("<html>{$head} <body><script>\r\n\t\t\tvar str = " . json_encode($str) . ";\r\n\t\t\talert(str);\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; /* -1 */ /* -1 */ case "-1": die("<html>{$head} <body><script>\r\n\t\t\t//var str = " . json_encode($str) . ";\r\n\t\t\t//alert(str);\r\n\t\t\thistory.go(-1);\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; /* alertGoTo */ /* alertGoTo */ case "alertGoTo": die("<html>{$head} <body><script>\r\n\t\t\tvar _href = " . json_encode($href) . ", str = " . json_encode($str) . ";\r\n\t\t\talert(str);\r\n\t\t\tlocation.href = _href;\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; /* goTo */ /* goTo */ case "goTo": die("<html>{$head} <body><script>\r\n\t\t\tvar _href = " . json_encode($href) . ", str = " . json_encode($str) . ";\r\n\t\t\t//alert(str);\r\n\t\t\tlocation.href = _href;\r\n\t\t\t</script><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; case "die": die("<html>{$head} <body><div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div></body></html>"); break; case "json": jsonError("fail", $str); break; default: echo "<!--error info -->{$head} <div style='font-size:12px; font-family:Verdana;background:url({$err_img}) #F6FBFF no-repeat 0px 0px; height:117px; width:550px; overflow-x: hidden; overflow-y: auto; padding-left:140px; border:1px solid #8cb7d7; margin:10px; color:#369'><br>错误:{$ACTION_ERRORS}<br>" . $_d . "</div><!--error info -->"; break; } }
$assn_json = json_decode($row['json']); $assn_id = $row['assn_id']; } if ($assn_id == false) { jsonError('This assignment is not yet set up'); return; } // Compute the user's grade $grade = computeGrade($assn_id, $assn_json, $user_id); if ($grade <= 0) { jsonError('Nothing to grade for this user', $row); return; } // Lookup the result row if we are grading the non-current user $result = false; if ($user_id != $USER->id) { $result = lookupResult($LTI, $user_id); } // Send the grade $debug_log = array(); $status = LTIX::gradeSend($grade, $result, $debug_log); // This is the slow bit if ($status === true) { if ($user_id != $USER->id) { jsonOutput(array("status" => $status, "debug" => $debug_log)); } else { jsonOutput(array("status" => $status, "grade" => $grade, "debug" => $debug_log)); } } else { jsonError($status, $debug_log); }
mysql_connection_overwrite(DATABASE); mysql_query("start transaction"); //POST Content-Length of 103399974 bytes exceeds the limit of 29360128 bytes in Unknown on line //$upload["type"] $fileID = upload_file($upload["name"], null, $upload["tmp_name"], $upload["error"], $upload["size"], $_REQUEST["description"], false); if (is_numeric($fileID)) { $file = get_uploaded_file_info($fileID, false); print json_format($file); mysql_query("commit"); } else { if ($fileID) { jsonError($fileID); } else { if ($_FILES["file"]["error"]) { jsonError("uploaded file was too large"); } else { jsonError("file upload was interrupted"); } } } } else { jsonError("File data are not posted to server side"); } } //***** END OF OUTPUT *****/ function jsonError($message) { mysql_query("rollback"); print json_encode(array('error' => $message)); //print "{\"error\":\"" . addslashes($message) . "\"}"; }
function doWgTagInsertion($recordID, $wgTagIDs) { if ($wgTagIDs != "" && !preg_match("/^\\d+(?:,\\d+)*\$/", $wgTagIDs)) { return; } if ($wgTagIDs) { mysql_query("delete usrRecTagLinks from usrRecTagLinks, usrTags, " . USERS_DATABASE . ".sysUsrGrpLinks where rtl_RecID={$recordID} and rtl_TagID=tag_ID and tag_UGrpID=ugl_GroupID and ugl_UserID=" . get_user_id() . " and tag_ID not in ({$wgTagIDs})"); if (mysql_error()) { jsonError("database error - " . mysql_error()); } } else { mysql_query("delete usrRecTagLinks from usrRecTagLinks, usrTags, " . USERS_DATABASE . ".sysUsrGrpLinks where rtl_RecID={$recordID} and rtl_TagID=tag_ID and tag_UGrpID=ugl_GroupID and ugl_UserID=" . get_user_id()); if (mysql_error()) { jsonError("database error - " . mysql_error()); } return; } $existingKeywordIDs = mysql__select_assoc("usrRecTagLinks, usrTags, " . USERS_DATABASE . ".sysUsrGrpLinks", "rtl_TagID", "1", "rtl_RecID={$recordID} and rtl_TagID=tag_ID and tag_UGrpID=ugl_GroupID and ugl_UserID=" . get_user_id()); $newKeywordIDs = array(); foreach (explode(",", $wgTagIDs) as $kwdID) { if (!@$existingKeywordIDs[$kwdID]) { array_push($newKeywordIDs, $kwdID); } } if ($newKeywordIDs) { mysql_query("insert into usrRecTagLinks (rtl_TagID, rtl_RecID) select tag_ID, {$recordID} from usrTags, " . USERS_DATABASE . ".sysUsrGrpLinks where tag_UGrpID=ugl_GroupID and ugl_UserID=" . get_user_id() . " and tag_ID in (" . join(",", $newKeywordIDs) . ")"); if (mysql_error()) { jsonError("database error - " . mysql_error()); } } }