### Basic XenForo Setup Class Structure Source: https://docs.xenforo.com/devs/lets-build-an-add-on This snippet shows the fundamental structure of a XenForo `Setup.php` class, extending `AbstractSetup` and incorporating traits for handling installation, uninstallation, and upgrade processes. ```php " url := "https://example.com/api/resources/" client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer " + token) resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } var data map[string]interface{} if err := json.Unmarshal(body, &data); err != nil { fmt.Println("Error unmarshalling JSON:", err) return } fmt.Println(data) } ``` -------------------------------- ### Execute XenForo Add-on Install Steps via CLI Source: https://docs.xenforo.com/devs/lets-build-an-add-on These commands demonstrate how to execute specific installation steps for a XenForo add-on using the command-line interface. Each command targets a particular step number for the 'Demo/Portal' add-on. ```bash php cmd.php xf-addon:install-step Demo/Portal 1 ``` ```bash php cmd.php xf-addon:install-step Demo/Portal 2 ``` ```bash php cmd.php xf-addon:install-step Demo/Portal 3 ``` -------------------------------- ### Install or Reinstall XenForo via CLI Source: https://docs.xenforo.com/devs Commands to initiate the XenForo installation process. The clear flag is used during reinstallation to remove existing database tables. ```Bash php cmd.php xf:install ``` ```Bash php cmd.php xf:install --clear ``` -------------------------------- ### Alternative Package Installation for MySQL Source: https://docs.xenforo.com/devs/appendix/macos-dev This snippet shows how to substitute MariaDB with MySQL 8.0 during package installation and service startup. This is recommended for users who require CJK language support, as MariaDB has known issues with it. ```bash # install packages including MariaDB: brew install pkg-config mariadb httpd mailhog imagemagick elastic/tap/elasticsearch-full shivammathur/php/php@5.6 shivammathur/php/php@7.4 shivammathur/php/php@8.0; # install packages using MySQL instead: brew install pkg-config mysql httpd mailhog imagemagick elastic/tap/elasticsearch-full shivammathur/php/php@5.6 shivammathur/php/php@7.4 shivammathur/php/php@8.0; # start MariaDB service brew services start mariadb # start MySQL service instead brew services start mysql ``` -------------------------------- ### Auto-starting Services with Homebrew Source: https://docs.xenforo.com/devs/appendix/macos-dev This command sequence uses Homebrew services to start essential development services, including Elasticsearch, multiple PHP versions (5.6, 7.4, 8.0), and the Apache HTTP server. These services are also configured to start automatically on system startup. ```bash brew services start elasticsearch-full; brew services start php@5.6; brew services start php@7.4; brew services start php@8.0; brew services start httpd; ``` -------------------------------- ### XenForo API Request Examples (JavaScript) Source: https://docs.xenforo.com/api/get-resources Illustrates how to interact with the XenForo API using JavaScript's `fetch` API. This includes setting the necessary headers for authentication and content type. These examples are suitable for client-side or Node.js applications. ```javascript // Example for fetching resources const token = ''; const url = 'https://example.com/api/resources/'; fetch(url, { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` } }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('Error fetching resources:', error); }); ``` -------------------------------- ### XenForo API Request Examples (PHP) Source: https://docs.xenforo.com/api/get-resources Provides examples of how to make API requests using PHP, including setting up authorization headers and constructing request URLs. These snippets illustrate common interactions with the XenForo API. ```php // Example for fetching resources $token = ''; $url = 'https://example.com/api/resources/'; $headers = [ 'Accept: application/json', 'Authorization: Bearer ' . $token ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); if (curl_errno($ch)) { echo 'Curl error: ' . curl_error($ch); } curl_close($ch); $data = json_decode($response, true); print_r($data); ``` -------------------------------- ### Install Development Stack via Homebrew Source: https://docs.xenforo.com/devs/appendix/macos-dev Configures Homebrew taps and installs essential development services including MariaDB, Apache, MailHog, ImageMagick, ElasticSearch, and multiple PHP versions (5.6, 7.4, 8.0). ```bash brew tap elastic/tap; brew tap shivammathur/php; brew install pkg-config mariadb httpd mailhog imagemagick elastic/tap/elasticsearch-full shivammathur/php/php@5.6 shivammathur/php/php@7.4 shivammathur/php/php@8.0; ``` -------------------------------- ### Fetch User Profile Posts (PHP) Source: https://docs.xenforo.com/api/get-users-id-profile-posts Example of how to fetch a user's profile posts using PHP. This involves making an HTTP GET request with the necessary authorization headers. ```php ``` -------------------------------- ### Get Media Comments - JavaScript Example Source: https://docs.xenforo.com/api/get-media-comments-id This example illustrates how to get media comments using JavaScript's Fetch API. It sets the required headers for the request. ```javascript fetch('https://example.com/api/media-comments/:id/', { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('Error fetching media comments:', error); }); ``` -------------------------------- ### Implementing an Add-on Setup class Source: https://docs.xenforo.com/devs/add-on-structure A PHP class implementation extending AbstractSetup to handle database schema creation, modification, and removal during the add-on lifecycle. ```php schemaManager()->createTable('xf_demo', function(\XF\Db\Schema\Create $table) { $table->addColumn('demo_id', 'int'); }); } public function upgrade(array $stepParams = []) { if ($this->addOn->version_id < 1000170) { $this->schemaManager()->alterTable('xf_demo', function(\XF\Db\Schema\Alter $table) { $table->addColumn('foo', 'varchar', 10)->setDefault(''); }); } } public function uninstall(array $stepParams = []) { $this->schemaManager()->dropTable('xf_demo'); } } ``` -------------------------------- ### GET /api/index/ Source: https://docs.xenforo.com/api/get-index Example request to the API index endpoint using a Bearer token for authorization. ```APIDOC ## GET /api/index/ ### Description This endpoint is an example of how to make a request to the XenForo API using an access token. It demonstrates the use of the `Authorization` header with a Bearer token. ### Method GET ### Endpoint `https://example.com/api/index/` ### Parameters #### Query Parameters - **api_bypass_permissions** (boolean) - Optional - If true, bypasses permission checks for the request. #### Headers - **Accept** (string) - Required - Specifies the desired response format, typically `application/json`. - **Authorization** (string) - Required - Contains the Bearer token for authentication. Format: `Bearer `. - **XF-Api-User** (string) - Optional - Specifies the user ID to perform the request as. ### Request Example ```curl curl -L 'https://example.com/api/index/' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` ### Response #### Success Response (200) - **response_data** (object) - Contains the data returned by the API. #### Response Example ```json { "response_data": { "message": "Welcome to the XenForo API!" } } ``` ``` -------------------------------- ### Fetch User Profile Posts (Go) Source: https://docs.xenforo.com/api/get-users-id-profile-posts Example of how to fetch a user's profile posts using Go's standard library. This involves creating an HTTP client and making a GET request with appropriate headers. ```go package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { client := &http.Client{} req, err := http.NewRequest("GET", "https://example.com/api/users/:id/profile-posts", nil) if err != nil { fmt.Println(err) return } req.Header.Add("Accept", "application/json") req.Header.Add("Authorization", "Bearer YOUR_ACCESS_TOKEN") resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() bodyText, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Print(string(bodyText)) } ``` -------------------------------- ### Install Homebrew Package Manager Source: https://docs.xenforo.com/devs/appendix/macos-dev Executes the official Homebrew installation script to set up the package manager on macOS. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"; ``` -------------------------------- ### Get Media Comments - PHP Example Source: https://docs.xenforo.com/api/get-media-comments-id This example shows how to fetch media comments using PHP. It utilizes cURL to make the HTTP request with appropriate headers. ```php $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://example.com/api/media-comments/:id/'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Accept: application/json', 'Authorization: Bearer YOUR_ACCESS_TOKEN' )); $response = curl_exec($curl); if (curl_errno($curl)) { echo 'Error:' . curl_error($curl); } c_url_close($curl); $data = json_decode($response, true); print_r($data); ``` -------------------------------- ### Create XenForo Add-on via Command Line Source: https://docs.xenforo.com/devs/lets-build-an-add-on This command initiates the creation of a new XenForo add-on. It prompts the user for an add-on ID, title, version information, and whether it supersedes a XenForo 1 add-on. It also asks about the need for a Setup file and multi-step support, ultimately generating the `addon.json` and `Setup.php` files. ```bash php cmd.php xf-addon:create ``` -------------------------------- ### Get Media Comments - CURL Example Source: https://docs.xenforo.com/api/get-media-comments-id This example demonstrates how to retrieve media comments using a CURL request. It includes the necessary headers for authentication and content negotiation. ```curl curl -L 'https://example.com/api/media-comments/:id/' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` -------------------------------- ### Fetch Media Categories Content (Go) Source: https://docs.xenforo.com/api/get-media-categories-id-content Example using Go's net/http package to fetch content for a specific media category. It shows how to set request headers, including authorization and accept types. ```go package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { url := "https://example.com/api/media-categories/:id/content" req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer YOUR_ACCESS_TOKEN") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } fmt.Println(string(body)) } ``` -------------------------------- ### Get Media Comments - Python Example Source: https://docs.xenforo.com/api/get-media-comments-id This Python example shows how to fetch media comments using the `requests` library. It includes setting the necessary headers for the API call. ```python import requests url = "https://example.com/api/media-comments/:id/" headers = { "Accept": "application/json", "Authorization": "Bearer YOUR_ACCESS_TOKEN" } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes data = response.json() print(data) except requests.exceptions.RequestException as e: print(f"Error fetching media comments: {e}") ``` -------------------------------- ### GET /api/index/ Source: https://docs.xenforo.com/api/get-index Fetches site and API information for the XenForo installation. This endpoint is useful for understanding the basic configuration and capabilities of the API. ```APIDOC ## GET /api/index/ ### Description Retrieves general information about the XenForo site and API configuration. ### Method GET ### Endpoint https://example.com/api/index/ ### Parameters #### Query Parameters - **api_bypass_permissions** (boolean) - Optional - Whether or not to bypass the context user permissions. Requires a super user API key. #### Header Parameters - **XF-Api-User** (integer) - Optional - User ID to execute the request as. Requires a super user API key. ### Response #### Success Response (200) - **version_id** (integer) - XenForo version ID - **site_title** (string) - Title of the site this API relates to - **base_url** (string) - The base URL of the XenForo install this API relates to - **api_url** (string) - The base API URL - **key[type]** (string) - Type of the API key accessing the API (guest, user or super) - **key[user_id]** (integer | null) - If a user key, the ID of the user the key is for; null otherwise - **key[allow_all_scopes]** (boolean) - If true, all scopes can be accessed - **key[scopes]** (string[]) - A list of scopes this key can access (if not allowed to access all scopes) **Response Headers** - **XF-Latest-Api-Version** - The latest API version available. - **XF-Used-Api-Version** - The API version used to render the response. - **XF-Request-User** - The user ID of the request user. - **XF-Request-User-Extras** - Additional information about the request user in JSON encoding. Requires XF-Request-User header to be non-zero. #### Response Example (200) ```json { "version_id": 0, "site_title": "string", "base_url": "string", "api_url": "string", "key[type]": "string", "key[user_id]": 0, "key[allow_all_scopes]": true, "key[scopes]": [ "string" ] } ``` #### Error Response **Response Headers** - **XF-Latest-Api-Version** - The latest API version available. - **XF-Used-Api-Version** - The API version used to render the response. - **XF-Request-User** - The user ID of the request user. - **XF-Request-User-Extras** - Additional information about the request user in JSON encoding. Requires XF-Request-User header to be non-zero. **Schema** - **errors** (object[]) - An array of error objects. - **code** (string) - The error code. - **message** (string) - The error message. - **params** (object) - Additional parameters for the error. #### Response Example (Error) ```json { "errors": [ { "code": "string", "message": "string", "params": {} } ] } ``` ``` -------------------------------- ### Setup Thread Creation with Featuring Option Source: https://docs.xenforo.com/devs/lets-build-an-add-on This method extends the `setupThreadCreate` method in the forum controller. It retrieves the creator service, checks if the forum has the auto-feature flag enabled, and if so, instructs the creator service to feature the thread. ```php protected function setupThreadCreate(\XF\Entity\Forum $forum) { /** @var \Demo\Portal\XF\Service\Thread\Creator $creator */ $creator = parent::setupThreadCreate($forum); if ($forum->demo_portal_auto_feature) { $creator->setFeatureThread(true); } return $creator; } ``` -------------------------------- ### Get Flattened Node Tree API Request Source: https://docs.xenforo.com/api/get-nodes-flattened This snippet demonstrates how to make a GET request to the XenForo API to retrieve a flattened list of nodes. It includes example URL and potential query parameters for bypassing permissions. ```http GET /api/nodes/flattened # Example with query parameter: GET /api/nodes/flattened?api_bypass_permissions=true ``` -------------------------------- ### Fetch Users API Request (Go) Source: https://docs.xenforo.com/api/get-users This Go program demonstrates how to retrieve user data from the XenForo API. It uses the `net/http` package to construct and send a GET request with the necessary authorization header. ```go package main import ( "fmt" "io/ioutil" "net/http" "encoding/json" ) func main() { token := "YOUR_ACCESS_TOKEN" url := "https://example.com/api/users/" client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer " + token) res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("Error reading response body:", err) return } var data map[string]interface{} err = json.Unmarshal(body, &data) if err != nil { fmt.Println("Error unmarshalling JSON:", err) return } fmt.Println(data) // Process the user data } ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://docs.xenforo.com/devs/appendix/macos-dev Installs the necessary Apple developer tools required for compiling and managing software packages on macOS via the terminal. ```bash sudo xcode-select --install; ``` -------------------------------- ### Configure Sidebar Widgets in Setup Class Source: https://docs.xenforo.com/devs/lets-build-an-add-on This PHP code defines the `installStep4` method in the XenForo Setup class to create and configure several widgets for the newly added sidebar position on the portal page. It uses the `createWidget` method to assign predefined widgets like 'members_online' and 'new_posts' to the 'demo_portal_view_sidebar' position with specific display orders. ```php public function installStep4() { $this->createWidget('demo_portal_view_members_online', 'members_online', [ 'positions' => ['demo_portal_view_sidebar' => 10] ]); $this->createWidget('demo_portal_view_new_posts', 'new_posts', [ 'positions' => ['demo_portal_view_sidebar' => 20] ]); $this->createWidget('demo_portal_view_new_profile_posts', 'new_profile_posts', [ 'positions' => ['demo_portal_view_sidebar' => 30] ]); $this->createWidget('demo_portal_view_forum_statistics', 'forum_statistics', [ 'positions' => ['demo_portal_view_sidebar' => 40] ]); $this->createWidget('demo_portal_view_share_page', 'share_page', [ 'positions' => ['demo_portal_view_sidebar' => 50] ]); } ``` -------------------------------- ### Manually Build Imagick Extension for PHP 8 Source: https://docs.xenforo.com/devs/appendix/macos-dev Instructions for manually compiling and installing the Imagick extension for PHP 8 when the standard 'pecl install imagick' command fails. This involves cloning the Imagick repository, configuring, compiling, and installing the extension. ```bash brew link --force --overwrite php@8.0 git clone https://github.com/Imagick/imagick cd imagick phpize && ./configure make make install ``` -------------------------------- ### Retrieve site statistics via GET request Source: https://docs.xenforo.com/api/get-stats Fetches the current statistics for the XenForo installation. The request supports optional query parameters for permission bypassing and header parameters for user context. ```http GET https://example.com/api/stats/ ``` -------------------------------- ### XenForo OAuth2 Authorization Example Source: https://docs.xenforo.com/api/post-auth Examples demonstrating how to obtain an access token using XenForo's OAuth2 authorization flow. This typically involves sending a POST request to the token URL with appropriate credentials and headers. ```curl curl -L -X POST 'https://example.com/api/auth/' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Accept: application/json' \ -H 'Authorization: Bearer ' ``` ```php // PHP example for OAuth2 token request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/oauth2/token'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response; ``` ```javascript // JavaScript example for OAuth2 token request using fetch fetch('https://example.com/api/oauth2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ```go // Go example for OAuth2 token request package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { url := "https://example.com/api/oauth2/token" payload := strings.NewReader("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") client := &http.Client{} res, err := client.Do(req) if err != nil { panic(err) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { panic(err) } fmt.Println(string(body)) } ``` ```python # Python example for OAuth2 token request import requests url = "https://example.com/api/oauth2/token" data = { "grant_type": "client_credentials", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET" } response = requests.post(url, data=data) print(response.json()) ``` -------------------------------- ### GET /users/find-name Source: https://docs.xenforo.com/api/openapi.json Find users by a prefix of their username. This endpoint allows searching for users whose usernames start with a given string. ```APIDOC ## GET /users/find-name ### Description Find users by a prefix of their user name. This endpoint allows searching for users whose usernames start with a given string. ### Method GET ### Endpoint /users/find-name ### Parameters #### Query Parameters - **username** (string) - Required - The prefix of the username to search for. ### Request Example ```json { "username": "joh" } ``` ### Response #### Success Response (200) - **exact** (User | null) - The user that matched the given username exactly. - **recommendations** (array[User]) - A list of users that match the prefix of the username (but not exactly). #### Response Example ```json { "exact": { "user_id": 1, "username": "john_doe", "avatar_urls": { "128": "/avatars/1/128x128_1.jpg" } }, "recommendations": [ { "user_id": 2, "username": "johnny_appleseed", "avatar_urls": { "128": "/avatars/2/128x128_2.jpg" } } ] } ``` ``` -------------------------------- ### Create Media Comment using Go Source: https://docs.xenforo.com/api/post-media-comments Example of how to create a media comment using Go's net/http package. This code snippet shows how to construct and send the POST request. ```go package main import ( "fmt" "net/http" "strings" ) func main() { url := "https://example.com/api/media-comments/" payload := strings.NewReader("album_id=1&media_id=1&message=This is a test comment.") req, err := http.NewRequest("POST", url, payload) if err != nil { fmt.Println(err) return } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Accept", "application/json") req.Header.Add("Authorization", "Bearer YOUR_ACCESS_TOKEN") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() // Read response body (omitted for brevity) fmt.Println("Status:", res.Status) } ``` -------------------------------- ### Publishing stub templates via CLI Source: https://docs.xenforo.com/devs/add-on-structure Command-line instructions to copy core XenForo stub templates into an add-on directory for customization. ```bash php cmd.php xf-make:stub-publish entity --addon=Vendor/AddOn ``` -------------------------------- ### GET /api/media/ Source: https://docs.xenforo.com/api/get-media Retrieves a paginated list of media items from the XenForo installation, supporting filters for media type, user, and sorting criteria. ```APIDOC ## GET /api/media/ ### Description Retrieves a list of media items. Supports filtering by media type, user, and various sorting parameters. ### Method GET ### Endpoint https://example.com/api/media/ ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number of results to return. - **media_type** (string) - Optional - Filters to only media of the specified type (image, audio, video, embed). - **user_id** (integer) - Optional - Filters to only media created by the specified user ID. - **order** (string) - Optional - Method of ordering: media_date, comment_count, rating_weighted, reaction_score, view_count. - **direction** (string) - Optional - Either "asc" or "desc" for ascending or descending order. - **api_bypass_permissions** (boolean) - Optional - Whether or not to bypass the context user permissions. Requires a super user API key. #### Header Parameters - **XF-Api-User** (integer) - Optional - User ID to execute the request as. Requires a super user API key. ### Request Example GET https://example.com/api/media/?media_type=image&order=media_date&direction=desc ### Response #### Success Response (200) - **media** (array) - A list of media item objects. - **pagination** (object) - Pagination metadata including total results and current page. #### Response Example { "media": [ { "media_id": 1, "title": "Example Image", "media_type": "image" } ], "pagination": { "total": 1, "page": 1 } } ```