| Server IP : 10.200.247.200 / Your IP : 216.73.217.19 Web Server : Apache System : Linux synergy-usa-sites 6.8.0-138-generic #138-Ubuntu SMP PREEMPT_DYNAMIC Fri Jul 31 22:41:49 UTC 2026 x86_64 User : jeremy ( 1001) PHP Version : 8.4.25 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/usa_sites/governmentgrants.us/vx/usa/search/ |
Upload File : |
<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'].'/vx/lib/ua.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/vx/lib/func.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/vx_/site_info.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/vx/lib/mysql.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/vx/lib/States.php');
$pg = new PDO("pgsql:host=americasgotgrants.com;port=5432;dbname=grantsdb", "jeremy", 'Jbera092405!', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$openaiApiKey = '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';
function prepareTextForEmbedding(string $text): string {
$text = strip_tags($text);
$text = html_entity_decode($text);
$text = strtolower($text);
$text = preg_replace('/\s+/', ' ', $text);
$text = trim($text);
$text = mb_substr($text, 0, 20000); // truncate to ~8192 tokens
return trim($text);
}
function getEmbedding(string $text, string $apiKey): array {
$payload = json_encode([
"model" => "text-embedding-3-large",
"input" => $text,
"dimensions" => 1536 // Make sure it matches your column
]);
$ch = curl_init("https://api.openai.com/v1/embeddings");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer $apiKey"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
if(curl_errno($ch)) {
throw new Exception("cURL error: " . curl_error($ch));
}
curl_close($ch);
$result = json_decode($response, true);
// Check for API errors
if (!is_array($result) || isset($result['error'])) {
$errorMessage = $result['error']['message'] ?? 'Unknown API error';
throw new Exception("OpenAI API error: $errorMessage");
}
if (!isset($result['data']) || !is_array($result['data'])) {
throw new Exception("Unexpected OpenAI API response: " . $response);
}
return $result['data'][0]['embedding'];
}
function findMatchingGrants(string $clientInput, int $page, int $per_page, $start_date, $end_date): array {
global $pg, $openaiApiKey;
$text = prepareTextForEmbedding($clientInput);
$embedding = getEmbedding($text, $openaiApiKey);
// Convert to Postgres vector literal
$vectorLiteral = '[' . implode(',', $embedding) . ']';
$real_start_date = $start_date.' 00:00:00';
$real_end_date = $end_date.' 23:59:59';
// Query Postgres using cosine similarity
$stmt = $pg->prepare("
SELECT grants_id,
embeddings <#> :embedding AS distance
FROM grants
WHERE date_added >= :start_date
AND date_added <= :end_date
AND (deadline = NULL OR deadline >= :today)
ORDER BY embeddings <#> :embedding
LIMIT :top
OFFSET :offset
");
$offset = ($page==1) ? 0 : ($page - 1)*$per_page;
try {
$stmt->bindValue(':embedding', $vectorLiteral);
$stmt->bindValue(':top', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':start_date', $real_start_date);
$stmt->bindValue(':end_date', $real_end_date);
$stmt->bindValue(':today', date('Y-m-d').' 00:00:00');
$stmt->execute();
} catch(Exception $e) {
echo '<pre>'.print_r($e,true).'</pre>';
}
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
ob_start();
?>
<div class="rb p20 top">
<h2><span class="fas fa-magnifying-glass" style="color:#7a7a7a;"></span> Search</h2>
<hr />
<?php
$not_ignored_where = " AND gg.grants_id NOT IN (SELECT grants_id FROM grdb.grd_usa_ignored_grants WHERE site_code='".$db->clean($siteCode)."' AND client_id='".$db->clean($_SESSION['user'])."')";
if(!empty($_GET['ignored'])) {
$not_ignored_where = " AND gg.grants_id IN (SELECT grants_id FROM grdb.grd_usa_ignored_grants WHERE site_code='".$db->clean($siteCode)."' AND client_id='".$db->clean($_SESSION['user'])."')";
}
$start_time = (date('Y')*1 - 1).'-01-01';
$end_time = date('Y-m-d',strtotime('-30 day'));
$gets_new_stuff = " AND gg.ts < '".date('Y-m-d',strtotime('-30 day'))." 00:00:00'";
if(!empty($_SESSION['subscriptions']['2'])) {
$gets_new_stuff = "";
$end_time = date('Y-m-d');
}
$page = 1;
$per_page = 20;
if(!empty($_REQUEST['page'])) {
$page = $_REQUEST['page'];
}
$where = '';
$keyword = '';
$total_count = 0;
if(!empty($_REQUEST['search'])) {
$keyword = trim($_REQUEST['search']);
}
$results = array();
if(!empty($keyword)) {
$results = findMatchingGrants($keyword, $page, $per_page, $start_time, $end_time);
$res = $db->get_results("SELECT COUNT(*) as c
FROM grdb.grd_grants AS gg
WHERE (gg.deadline='0000-00-00' OR gg.deadline >= CURDATE())
{$gets_new_stuff}
{$where}");
$total_count = $res[0]->c;
}
if(!empty($_REQUEST['page'])) {
track_member_action('Changed Page',$_REQUEST['page']);
} elseif(!empty($keyword)) {
track_member_action('Searched',$keyword);
} else {
track_member_action('Page Visit','Search Database');
}
$max_page = ceil($total_count/$per_page);
if($page<1) {
$page = 1;
}
if($page>$max_page) {
$page = $max_page;
}
$limit = '';
if($total_count >= $per_page) {
$limit = "LIMIT ".(($page-1)*$per_page).", ".$per_page;
}
$grant_list = array();
if(!empty($results)) {
foreach($results as $grant) {
$res = $db->get_results("SELECT
gg.*,
gusg.id AS favorite,
gga.did_apply,
gga.how_much_applied_for,
gt.name AS grant_type,
IF(gg.deadline='0000-00-00',1,0) as no_deadline,
ggl.bg_color_hex,
ggl.logo_url
FROM grdb.grant_categories_new_grants gbg
LEFT JOIN grdb.grd_grants AS gg ON gbg.grants_id=gg.grants_id
LEFT JOIN grdb.grd_usa_saved_grants AS gusg
ON gg.grants_id = gusg.grants_id
AND gusg.client_id = '$user'
AND gusg.site_code = '$siteCode'
LEFT JOIN grdb.grd_grants_applied AS gga
ON
gga.grants_id = gg.grants_id
AND
gga.user = gusg.client_id
AND
gga.site_code = gusg.site_code
LEFT JOIN grdb.grd_types AS gt
ON gt.types_id = gg.types_id
LEFT JOIN grdb.grd_site_logos ggl ON ggl.site_domain=gg.base_url AND ggl.status='active'
WHERE
gg.grants_id='".$db->clean($grant['grants_id'])."'
GROUP BY gg.grants_id
LIMIT 1");
if(!empty($res)) {
$grant_list[] = $res[0];
}
}
}
if(!empty($limit)) {
?>
<div id="paging">
<center>
<h3><?= paging_title($page,$total_count,$per_page);?> of <?= $total_count;?></h3>
<button onclick="grant_list_change_page('1'); return false;" title="<?= paging_title(1,$total_count,$per_page);?>"><<</button>
<button onclick="grant_list_change_page('<?= $page-1;?>'); return false;" title="<?= paging_title($page-1,$total_count,$per_page);?>"><</button>
<?php for($i=$page-5;$i<$page+5;$i++) {
if($i>=1 && $i<=$max_page) { ?>
<button onclick="grant_list_change_page('<?= $i;?>'); return false;" <?= ($i==$page) ? 'class="selected_page"' : '';?> title="<?= paging_title($i,$total_count,$per_page);?>"><?= $i;?></button>
<?php } ?>
<?php } ?>
<button onclick="grant_list_change_page('<?= $page+1;?>'); return false;" title="<?= paging_title($page+1,$total_count,$per_page);?>">></button>
<button onclick="grant_list_change_page('<?= $max_page;?>'); return false;" title="<?= paging_title($max_page,$total_count,$per_page);?>">>></button>
</center>
</div>
<?php } ?>
<div id="search_form" style="margin:10px 0px;">
<center>
<form method="GET" action="">
<?php /*
<input type="hidden" name="page" value="<?= $page;?>" />
*/ ?>
<input type="hidden" name="page" value="1" />
<div class="rib">
<input type="text" id="searchKeyword" name="search" class="searchKeyword fleft" placeholder="Search Term" value="<?= $_GET['search'];?>" style="border-color:rgba(0,0,0,0.2);" />
<button type="submit" name="submit" value="submit" class="fleft white-bg bborder tborder rborder searchButton" style="margin:0px 0px 0px -1px;"><i class="glyphicons glyphicons-search f18"></i></button>
</div>
</form>
</center>
</div>
<div id="grantList">
<?php if($phone) {
include($_SERVER['DOCUMENT_ROOT'].'/vx/usa/layout/inc/non_angular_grant_list_mobile.php');
} else {
include($_SERVER['DOCUMENT_ROOT'].'/vx/usa/layout/inc/non_angular_grant_list.php');
} ?>
</div>
</div>
<?php
$body = ob_get_clean();
$title = "Advanced Searching : ".$_SESSION['site_name'];
include($_SERVER['DOCUMENT_ROOT'].'/vx/usa/layout/non_angular_layout.php');
?>