dir/api2.php

407 lines
17 KiB
PHP

<?php
$TESTSITE = 1;
if ($TESTSITE) {
$DBUser = 'phowell'; $DBServer = '192.168.1.6';
$DBPass = 'rolley34'; $DBName = 'db';
} else {
$DBUser = 'phowell'; $DBServer = 'localhost';
$DBPass = 'p^howell'; $DBName = 'PeterDB';
}
// Establish database connection
//
$c = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($c->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 "<p>{$s}</p>\n"; }
function p2($val){ echo '<pre>'; print_r($val); echo "</pre>\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, '<p><br><ul><ol><li><b><i><strong><em>')); }
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];
?>
<!--
<?php print_r($attributes); ?>
-->
<?php
session_start();
$_SESSION['USER_TYPE'] = $USER_TYPE;
$_SESSION['USER_GOO'] = $USER_GOO;
$_SESSION['USER_EMAIL'] = $USER_EMAIL;
} else { // already logged in....
$USER_TYPE = $_SESSION['USER_TYPE'];
$USER_GOO = $_SESSION['USER_GOO'];
$USER_EMAIL = $_SESSION['USER_EMAIL'];
}
} else { // just testing on a different server...
$USER_TYPE = 'FACULTY'; $USER_GOO = 'G00102586'; $USER_EMAIL = 'phowell@gavilan.edu';
session_start();
$_SESSION['USER_TYPE'] = $USER_TYPE;
$_SESSION['USER_GOO'] = $USER_GOO;
$_SESSION['USER_EMAIL'] = $USER_EMAIL;
}
// No email? Might be a problem. Look up by goo
if (! $USER_EMAIL) {
$goo = substr($USER_GOO, 3);
$q0 = "SELECT email,name FROM conf_users WHERE goo='{$goo}'";
$temp_usr = single_row_select($q0,0);
$USER_NAME = '';
// Is this a "MISSING USER?" Create an account for them.
if (is_null($temp_usr)) {
$LC_EMAIL = strtolower($USER_EMAIL);
$result = single_row_insert("INSERT INTO conf_users (goo, email, name) VALUES ('{$goo}','{$LC_EMAIL}','{$USER_NAME}');");
//echo "INSERT INTO conf_users (goo, email, name) VALUES ('{$goo}','{$LC_EMAIL}','{$USER_NAME}');";
//print_r($result);
//$logaction = log_it("Made a new conf_users row for {$USER_NAME} / {$LC_EMAIL} / {$USER_GOO}");
}
$USER_NAME = $temp_usr['name'];
$USER_EMAIL = strtolower($temp_usr['email']);
}
//
//
//
//
// Set up user global
$usr_qry = "SELECT id AS conf_id, goo AS conf_goo, email AS conf_email, name AS conf_name, active AS conf_active FROM conf_users WHERE LOWER(email)='{$USER_EMAIL}'";
$USER = single_row_select($usr_qry, 0);
// Check again for missing user entry. Create an account for them.
if (is_null($USER)) {
$LC_EMAIL = strtolower($USER_EMAIL);
$goo = substr($USER_GOO, 3);
$USER_NAME = '';
$result = single_row_insert("INSERT INTO conf_users (goo, email, name) VALUES ('{$goo}','{$LC_EMAIL}','{$USER_NAME}');");
//echo "INSERT INTO conf_users (goo, email, name) VALUES ('{$goo}','{$LC_EMAIL}','{$USER_NAME}');";
//print_r($result);
//$logaction = log_it("Made a new conf_users row for {$USER_NAME} / {$LC_EMAIL} / {$USER_GOO}");
$usr_qry = "SELECT id AS conf_id, goo AS conf_goo, email AS conf_email, name AS conf_name, active AS conf_active FROM conf_users WHERE LOWER(email)='{$USER_EMAIL}'";
$USER = single_row_select($usr_qry, 0);
}
// Define URL templates and associated SQL queries
$queries = array(
'/users/{id}' => '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 . "<br>";
// 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 . "<br>";
$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 . "<br>";
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;
}*/