connect_error) { die('Database connection failed: ' . $c->connect_error ); }
if (!mysqli_select_db($c, $DBName)) { die("Uh oh, couldn't select database $DBName"); }
mysqli_set_charset($c, 'utf8');
$server = $_SERVER['SERVER_NAME'];
$DEBUG = 0;
function p($s) { echo "
{$s}
\n"; }
function p2($val){ echo ''; print_r($val); echo "
\n"; }
function d_err($s) { global $DEBUG; if ($DEBUG) { p($s); } }
function ok($str) { global $c; return mysqli_real_escape_string($c, strip_tags($str, '
- ')); }
function okh($str) { global $c; return mysqli_real_escape_string($c, $str); }
function sanitizeAndValidate($s) { return okh($s); }
function unescape_commas($s) { return preg_replace('/\[CMA\]/', ',', $s); }
function single_row_select($qry, $j=1) {
global $c;
$r = mysqli_query($c, $qry); d_err($qry);
$e = mysqli_error($c); if($e) { d_err("sql error: " . $e ); }
if (!$r) { return $r; }
$a = mysqli_fetch_assoc($r);
$e = mysqli_error($c); if($e) { d_err("sql error: " . $e ); }
if (! $j) { return $a; } return json_encode($a); }
function single_row_insert($qry) { global $c;
$r = mysqli_query($c, $qry);
return mysqli_insert_id($c); }
function single_row_update($qry, $j=1) { global $c;
$r = mysqli_query($c, $qry);
return 1; }
function multi_row_select($qry, $j=1) { global $c; $rows = array();
$result = mysqli_query($c, $qry);
while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; }
if (! $j) { return $rows; } return json_encode( $rows); }
function multi_row_1d($qry) { global $c;
$savedQuery = mysqli_query($c, $qry);
while($savedResult = mysqli_fetch_array($savedQuery)) { $savedArray[] = $savedResult[0]; }
return $savedArray; }
// _____ _____ _ _ _____ _ ______ _ ____ _ _
// / ____|_ _| \ | |/ ____| | | ____| (_) / __ \| \ | |
// | (___ | | | \| | | __| | | |__ ___ _ __ _ _ __ | | | | \| |
// \___ \ | | | . ` | | |_ | | | __| / __| |/ _` | '_ \ | | | | . ` |
// ____) |_| |_| |\ | |__| | |____| |____ \__ \ | (_| | | | | | |__| | |\ |
// |_____/|_____|_| \_|\_____|______|______| |___/_|\__, |_| |_| \____/|_| \_|
// __/ |
// |___/
// SSO
//
// Set GLOBAL VARS corresponding to current logged in user.
// They may only edit their own dir info.
//
if ( $server == 'intranet1.gavilan.edu' ) { // The SSO check should have happened on the actual page. If it gets
// // stuck on an api call the app will break.
if ( session_id() == '' ) { // session_status() == PHP_SESSION_ACTIVE // newer php uses this
require 'mAuth.php';
$USER_TYPE = $attributes['http://wso2.org/claims/Roles'][0];
$USER_GOO = $attributes['http://wso2.org/claims/uid'][0];
$USER_EMAIL = $attributes['http://wso2.org/claims/emailaddress'][0];
?>
'SELECT * FROM users WHERE id = :id',
'/users' => 'SELECT * FROM users',
'/products' => 'SELECT * FROM products',
'/sessions' => 'SELECT c.id,c.title,c.desc,c.length,c.starttime,c.track,c.location,c.location_irl,c.mode,c.gets_survey,c.category,c.parent,c.recording,c.instructions,c.image_url,c.is_flex_approved,c.cal_uid,sst.type AS typeStr, sst.id AS type, GROUP_CONCAT(ctg.tag) AS tags FROM conf_sessions c LEFT JOIN conf_sessiontypes sst ON c.type=sst.id LEFT JOIN conf_tagmember ct ON c.id=ct.session LEFT JOIN conf_tags ctg ON ctg.id=ct.tag GROUP BY c.id ORDER BY c.track, c.starttime;',
'/ses/{day}' => 'SELECT c.id,c.title,c.desc,c.length,c.starttime,c.track,c.location,c.location_irl,c.mode,c.gets_survey,c.category,c.parent,c.recording,c.image_url,c.is_flex_approved,c.cal_uid,sst.type AS typeStr, sst.id AS type, GROUP_CONCAT(ctg.tag) AS tags FROM conf_sessions c LEFT JOIN conf_sessiontypes sst ON c.type=sst.id LEFT JOIN conf_tagmember ct ON c.id=ct.session LEFT JOIN conf_tags ctg ON ctg.id=ct.tag WHERE c.starttime LIKE \'%:day%\' GROUP BY c.id ORDER BY c.track, c.starttime;',
'/settings' => 'SELECT * FROM conf_uinforecord;'
);
$functions = array(
'/app' => 'appdata',
'/start' => 'startup',
'/update/activity' => 'set_sessioninfo',
);
if (1) { //// ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_REQUEST['query'])) {
$requestUrl = '/' . $_REQUEST['query']; /// $_SERVER['REQUEST_URI'];
// Check if a matching URL template exists
// Execute corresponding SQL query based on the request URL
foreach ($queries as $urlTemplate => $sqlTemplate) {
$pattern = preg_replace('/{([\-_\w]+)}/', '([\-_\w]+)', $urlTemplate);
if (preg_match("#^$pattern$#", $requestUrl, $matches)) {
// Extract parameter values
$params = array();
preg_match_all('/{([\-_\w]+)}/', $urlTemplate, $paramNames);
foreach ($paramNames[1] as $index => $paramName) {
$paramValue = $matches[$index + 1];
//echo ". . index:" . $index . ". . paramName:" . $paramName . ". . paramValue:" . $paramValue . "
";
// Sanitize and validate the parameter value
// Store the sanitized value in the $params array
$params[':' . $paramName] = sanitizeAndValidate($paramValue);
}
// Prepare the SQL query with the parameter values
$sql = strtr($sqlTemplate, $params);
// Execute the SQL query and retrieve data
//echo "query:" . $sql . "
";
$result = mysqli_query($c, $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) { $rows[] = $r; }
$jsonString = json_encode($rows);
$sizeInBytes = strlen($jsonString);
echo json_encode(array(
"size" => $sizeInBytes,
"result" => "success",
//"query" => $sql,
"data" => $rows,
"err" => mysqli_error($c)
));
}
}
foreach ($functions as $urlTemplate => $functionCall) {
$pattern = preg_replace('/{([\-_\w]+)}/', '([\-_\w]+)', $urlTemplate);
if (preg_match("#^$pattern$#", $requestUrl, $matches)) {
// Extract parameter values
$params = array();
preg_match_all('/{([\-_\w]+)}/', $urlTemplate, $paramNames);
foreach ($paramNames[1] as $index => $paramName) {
$paramValue = $matches[$index + 1];
// Sanitize and validate the parameter value
// Store the sanitized value in the $params array
$params[':' . $paramName] = sanitizeAndValidate($paramValue);
}
$rows = call_user_func($functionCall);
$jsonString = json_encode($rows);
$sizeInBytes = strlen($jsonString);
echo json_encode(array(
"size" => $sizeInBytes,
"result" => "success",
"data" => $rows,
"err" => mysqli_error($c)
));
}
}
}
} /*elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle updates / inserts
$tableName = $_GET['table'];
$postData = $_POST;
$recordId = isset($postData['id']) ? $postData['id'] : null;
$date = date('Y-m-d H:i:s');
$columns = explode(',', $_REQUEST['cols']);
$values = explode(',', $_REQUEST['vals']);
$values = array_map('unescape_commas', $values);
$columnValuePairs = array_combine($columns, $values);
// Build the update/insert query
if ($recordId) {
$query = "UPDATE $tableName SET ";
$query .= join(", ", array_map(function ($column, $value) {
return okh($column) . " = '" . okh($value) . "'";
}, array_keys($columnValuePairs), $columnValuePairs));
$query .= ", changed = '$date'";
$query .= " WHERE id = $recordId";
} else {
$query = "INSERT INTO $tableName (";
$query .= join(", ", array_map('okh', $columns));
$query .= ", changed) VALUES ('";
$query .= join("', '", array_map('okh', $values));
$query .= "', '$date')";
}
// Execute the query
echo "Query: " . $query . "
";
exit();
$r = mysqli_query($c, $query);
echo json_encode(array(
"rawvalstr" => $_REQUEST['vals'],
"result" => "success",
"action" => ($recordId ? "updated" : "inserted"),
"logaction" => $logaction,
"query" => $query,
"err" => mysqli_error($c)
));
exit();
} */
function startup() {
global $USER;
$ddd = multi_row_select('SELECT * FROM gavi_departments ORDER BY name',0);
$ttt = multi_row_select('SELECT * FROM gavi_titles ORDER BY name',0);
$rrr = multi_row_select("SELECT * FROM gavi_roles ORDER BY 'descr'",0);
$ccc = multi_row_select('SELECT * FROM gavi_committees ORDER BY name',0);
$sss = multi_row_select('SELECT * FROM conf_sessiontypes ORDER BY id',0);
$aya = multi_row_select('SELECT * FROM conf_academicyears ORDER BY id',0);
$set = multi_row_select('SELECT id,label,value FROM conf_uinforecord',0);
$ppp = multi_row_select("SELECT * FROM `conf_sessions` WHERE `type` = '20' OR `type` = '21' ORDER BY starttime",0);
$SET = array();
foreach ($set as $setting) {
$SET[$setting['label']] = $setting['value'];
}
echo json_encode( array( 'user'=>$USER, 'departments'=>$ddd, 'titles'=>$ttt, 'roles'=>$rrr, 'committees'=>$ccc,
'sessiontypes'=>$sss, 'settings'=>$SET, 'ay'=>$aya, 'parents'=>$ppp ) );
exit();
}
function appdata() {
global $USER;
// mysessions
$m = multi_row_select("SELECT c.id,c.title,c.desc,c.length,c.starttime,c.track,c.location,c.location_irl,c.mode,c.gets_survey,c.category,c.parent,c.recording,c.instructions,c.image_url,c.is_flex_approved,sst.type,sst.id AS typeId, GROUP_CONCAT(ctg.tag) AS tags FROM conf_sessions c LEFT JOIN conf_signups as sup on c.id=sup.session LEFT JOIN conf_hosts as h ON h.session=c.id JOIN conf_sessiontypes sst ON c.type=sst.id LEFT JOIN conf_tagmember ct ON c.id=ct.session LEFT JOIN conf_tags ctg ON ctg.id=ct.tag WHERE (h.host='{$USER['conf_id']}' OR sup.user='{$USER['conf_id']}') GROUP BY c.id ORDER BY c.track, c.starttime;",0);
// sessions
$s = multi_row_select('SELECT c.id,c.title,c.desc,c.length,c.starttime,c.track,c.location,c.location_irl,c.mode,c.gets_survey,c.category,c.parent,c.recording,c.instructions,c.image_url,c.is_flex_approved,c.cal_uid,sst.type AS typeStr, sst.id AS type, GROUP_CONCAT(ctg.tag) AS tags FROM conf_sessions c LEFT JOIN conf_sessiontypes sst ON c.type=sst.id LEFT JOIN conf_tagmember ct ON c.id=ct.session LEFT JOIN conf_tags ctg ON ctg.id=ct.tag GROUP BY c.id ORDER BY c.track, c.starttime;',0);
// hosts
$hh = multi_row_1d("select session FROM conf_hosts WHERE host='{$USER['conf_id']}';");
// conferences
$c = multi_row_select('SELECT * FROM conf_conferences;',0);
$y = multi_row_select('SELECT * FROM conf_academicyears',0);
// options
$o = multi_row_select('SELECT * FROM conf_uinforecord',0);
echo json_encode(array(
"mysessions" => $m,
"sessions" => $s,
"host" => $hh,
"user" => $USER,
"conference" => $c,
"ay" => $y,
"options" => $o,
));
exit();
}
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
//
// Editing of session info
//
function reducer ($memo, $a) { return $memo . "`" . ok($a[0]) . "` = '" . okh($a[1]) . "', "; }
function set_sessioninfo() {
global $c, $USER;
$table = 'conf_sessions';
if (isset($_POST['id'])) {
$ID = ok($_REQUEST['id']);
$WHERECLAUSE = " WHERE id={$ID}";
$date = date('Y-m-d H:i:s');
$cols = explode(',', $_REQUEST['cols']); $vals = explode(',', $_REQUEST['vals']);
$vals = array_map('unescape_commas', $vals);
$cv = array_map(null,$cols,$vals);
$q = array_reduce($cv, 'reducer', "UPDATE `{$table}` SET ");
$q = substr($q, 0, -2);
$q .= $WHERECLAUSE;
single_row_update($q,0);
echo json_encode( array("rawvalstr"=>$_REQUEST['vals'], "result"=>"success","action"=>"updated", "query"=>$q,"err"=>mysqli_error($c2)));
} else {
echo json_encode( array("result"=>"fail", "err"=>"no activity id specified") ); }
exit();
}
// Return an appropriate response indicating success or failure
// ...
// Close the database connection
// ...
// later... permission check
// Check if the user has permission to update the record
/*if (isset($_POST['id'])) { // Editing another person's data
if (!check_permission($USER->id, $_POST['id'], 'personnel')) {
echo json_encode(array("result" => "fail", "err" => "You don't have permission to edit this"));
exit();
} else {
$logaction = log_it("Updating $tableName record with id {$_POST['id']}");
$recordId = $_POST['id'];
}
} else {
$logaction = log_it("Updating $tableName record");
$recordId = $USER->id;
}*/