krz/hn

A brutalist web client for Hacker News.

clone: git clone https://gitbay.org/krz/hn.git

a066660764583d754d3f91e4e095cc78d69b0075

unsigned

author: Christian Cleberg <hello@cleberg.net> · 2023-06-01T13:52:18Z

add get_user function
 index.php | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)

diff --git a/index.php b/index.php
index 2359934..bca506d 100644
--- a/index.php
+++ b/index.php
@@ -130,6 +130,52 @@ function get_stories($api_url, $inline_title) {
 	return $html_output;
 }
 
+/**
+*Extract a user's profile from Hacker News API and format in HTML
+*
+* @access public
+* @author cmc <hello@cleberg.net>
+* @param string $api_url The API endpoint to use for extraction
+* @param string $inline_title The <h1> title to use in the HTML
+* @return string $html_output The formatted HTML result of stories from the API
+*/
+function get_user(string $api_url, string $inline_title) {
+	$response_raw = file_get_contents($api_url);
+	if (is_null($response_raw) || $response_raw == "null") {
+		$html_output .= '<p>ERROR: User not found.</p>';
+		return $html_output;
+	} else {
+		$response = json_decode($response_raw, true);
+	}
+
+	$html_output = '<h1>' . $inline_title . '</h1>';
+	$html_output .= '<p>About: ' . $response['about']  . '</p>';
+	$html_output .= '<p>Karma: ' . $response['karma']  . '</p>';
+	$html_output .= '<p>Created: <time datetime="' . date('Y-m-d h:m:s', $response['created'])  . '>
+	$html_output .= '<p>Recently Submitted Posts:</p>';
+
+	$limit = count($response['submitted']) > 10 ? 10 : count($response['submitted']);
+	if (count($response['submitted']) > 0) {
+		for ($i = 0; $i < $limit; $i++) {
+			$sub_url = 'https://hacker-news.firebaseio.com/v0/item/' . $response['submitted>
+			$sub_response_raw = file_get_contents($sub_url);
+			$sub_response = json_decode($sub_response_raw, true);
+
+			// TODO: Create switch-case to cover a story, comment, job, poll, or pollopt
+			$html = '<div><a href="' . $sub_response['url'] . '">' . $sub_response['title']>
+			$html .= '<p><time datetime="' . date('Y-m-d h:m:s', $sub_response['time']) . '>
+			$html .= date('Y-m-d h:m:s', $sub_response['time'])  . '</time> by ';
+			$html .= $sub_response['by'] . ' | ' . $sub_response['score'] . ' points</p></d>
+		$html_output .= $html;
+		}
+	} else {
+		$html_output .= '<p>User has no subsmissions.</p>';
+	}
+
+	return $html_output;
+}
+
+
 /**
 * Send formatted HTML results to the user via a template
 *