Jump to content

Widget:UPDEvents: Difference between revisions

From Iskomunidad
Created page with " <?php →* * UP Diliman Events feed for Iskomunidad. * Retrieves up to five upcoming events from upd.edu.ph.: header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: public, max-age=900'); date_default_timezone_set('Asia/Manila'); $sourceUrl = 'https://upd.edu.ph/events-list/'; function respond($events, $status = 200) { http_response_code($status); echo json_encode( $events, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_..."
 
No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
<includeonly>
<div id="upd-events-widget" class="upd-events-widget">
  <div class="upd-events-loading">Loading upcoming events...</div>
  <ul class="upd-events-list" style="display:none;"></ul>
</div>


<?php
<style>
/**
.upd-events-widget {
* UP Diliman Events feed for Iskomunidad.
  color: #000;
* Retrieves up to five upcoming events from upd.edu.ph.
  font-size: 15px;
*/
}
.upd-events-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.upd-events-list li {
  margin: 0;
  padding: 10px 0;
  border-bottom: 1px solid #e5e5e5;
}
.upd-events-list li:last-child {
  border-bottom: none;
}
.upd-events-list a {
  color: #0E6021 !important;
  text-decoration: none;
  font-weight: 600;
}
.upd-events-list a:hover {
  text-decoration: underline;
}
.upd-events-loading,
.upd-events-empty {
  color: #555;
  font-size: 14px;
}
</style>


header('Content-Type: application/json; charset=utf-8');
<script>
header('Cache-Control: public, max-age=900');
(function () {
  var container = document.getElementById('upd-events-widget');


date_default_timezone_set('Asia/Manila');
  if (!container || container.dataset.loaded === '1') {
    return;
  }


$sourceUrl = 'https://upd.edu.ph/events-list/';
  container.dataset.loaded = '1';


function respond($events, $status = 200) {
  var loading = container.querySelector('.upd-events-loading');
     http_response_code($status);
  var list = container.querySelector('.upd-events-list');
     echo json_encode(
 
        $events,
  loading.textContent =
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
     'Widget JavaScript is running. Requesting UP Diliman...';
     );
 
     exit;
  var endpoint = new URL(
}
    'https://upd.edu.ph/wp-admin/admin-ajax.php'
  );
 
  var params = {
    action: 'search_events',
     id: '1',
    scope: 'future',
    orderby: 'event_start_date,event_start_time,event_name',
    view: 'list-grouped',
     pno: '1'
  };
 
  Object.keys(params).forEach(function (key) {
     endpoint.searchParams.set(key, params[key]);
  });
 
  var finished = false;


if (!function_exists('curl_init')) {
  var timeout = setTimeout(function () {
     respond(['error' => 'PHP cURL is not installed.'], 500);
     if (finished) return;
}


$ch = curl_init($sourceUrl);
    finished = true;
    loading.textContent =
      'The UP Diliman request timed out or is blocked.';
  }, 10000);


curl_setopt_array($ch, [
  fetch(endpoint.toString(), {
     CURLOPT_RETURNTRANSFER => true,
     method: 'GET',
     CURLOPT_FOLLOWLOCATION => true,
     mode: 'cors',
     CURLOPT_MAXREDIRS => 3,
     credentials: 'omit'
    CURLOPT_CONNECTTIMEOUT => 8,
  })
    CURLOPT_TIMEOUT => 15,
  .then(function (response) {
    CURLOPT_USERAGENT => 'Iskomunidad-Events/1.0',
     if (finished) return null;
     CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);


$html = curl_exec($ch);
    if (!response.ok) {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      throw new Error('HTTP ' + response.status);
$error = curl_error($ch);
    }
curl_close($ch);


if ($html === false || $httpCode < 200 || $httpCode >= 300) {
    return response.text();
    error_log('UPD events retrieval failed: ' . $error);
  })
     respond(['error' => 'The UP Diliman events page is temporarily unavailable.'], 502);
  .then(function (html) {
}
     if (finished || html === null) return;


libxml_use_internal_errors(true);
    finished = true;
    clearTimeout(timeout);


$dom = new DOMDocument();
    var doc = new DOMParser().parseFromString(html, 'text/html');
$loaded = $dom->loadHTML('<?xml encoding="UTF-8">' . $html);


libxml_clear_errors();
    var anchors = doc.querySelectorAll(
      '#em-events-list-grouped-1 a[href*="/events/"], ' +
      '.em-events-list a[href*="/events/"]'
    );


if (!$loaded) {
    var seen = new Set();
     respond(['error' => 'Could not parse the UP Diliman events page.'], 502);
     var events = [];
}


$xpath = new DOMXPath($dom);
    anchors.forEach(function (anchor) {
$links = $xpath->query('//a[@href]');
      var heading = anchor.querySelector('h4');
$today = new DateTimeImmutable('today', new DateTimeZone('Asia/Manila'));
      if (!heading) return;


$events = [];
      var title = heading.textContent.trim();
$seen = [];
      var url;


foreach ($links as $link) {
      try {
    $url = trim($link->getAttribute('href'));
        url = new URL(
    $title = trim(preg_replace('/\s+/u', ' ', $link->textContent));
          anchor.getAttribute('href'),
          'https://upd.edu.ph'
        ).href;
      } catch (e) {
        return;
      }


    // Only accept links to individual UP Diliman event pages.
      if (!title || seen.has(url)) return;
    $path = parse_url($url, PHP_URL_PATH) ?: '';


    if (!preg_match('~^/events/[^/]+/$~', $path)) {
      if (!/^https:\/\/upd\.edu\.ph\/events\//i.test(url)) {
         continue;
         return;
    }
      }


    // Event URLs contain their start date, e.g. ...-2026-10-26/
      seen.add(url);
    if (!preg_match('/-(\d{4}-\d{2}-\d{2})\/?$/', $path, $match)) {
      events.push({
         continue;
        title: title,
     }
         url: url
      });
     });


     $dateString = $match[1];
     list.replaceChildren();


     $eventDate = DateTimeImmutable::createFromFormat(
     if (events.length === 0) {
         '!Y-m-d',
      loading.textContent =
        $dateString,
         'The request succeeded, but no event titles were found.';
        new DateTimeZone('Asia/Manila')
    );


    if (!$eventDate || $eventDate->format('Y-m-d') !== $dateString) {
      return;
        continue;
     }
     }


     // Include events starting today or later.
     events.slice(0, 5).forEach(function (event) {
    if ($eventDate < $today) {
      var li = document.createElement('li');
        continue;
      var a = document.createElement('a');
    }
 
      a.href = event.url;
      a.textContent = event.title;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';


    if ($title === '' || isset($seen[$path])) {
      li.appendChild(a);
        continue;
      list.appendChild(li);
     }
     });


     $seen[$path] = true;
     loading.style.display = 'none';
    list.style.display = 'block';
  })
  .catch(function (error) {
    if (finished) return;


     $events[] = [
     finished = true;
        'title' => $title,
     clearTimeout(timeout);
        'url' => 'https://upd.edu.ph' . $path,
        'date' => $dateString,
     ];
}


// Sort by event start date, earliest first.
    console.error('UPEvents widget error:', error);
usort($events, function ($a, $b) {
    return strcmp($a['date'], $b['date']);
});


respond(array_slice($events, 0, 5));
    loading.textContent =
      'Request failed: ' +
      error.name + ' — ' + error.message;
  });
})();
</script>
</includeonly>

Latest revision as of 03:24, 29 October 2026