diff --git a/.pubnub.yml b/.pubnub.yml index 3f6c229..924a57b 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,8 +1,15 @@ name: php -version: 8.0.0 +version: 8.0.1 schema: 1 scm: github.com/pubnub/php changelog: + - date: 2025-04-01 + version: 8.0.1 + changes: + - type: bug + text: "Added missing information in file publish endpoint." + - type: improvement + text: "Basic usage examples have been added." - date: 2025-03-19 version: 8.0.0 changes: @@ -457,8 +464,8 @@ sdks: - x86-64 - distribution-type: library distribution-repository: GitHub release - package-name: php-8.0.0.zip - location: https://github.com/pubnub/php/releases/tag/8.0.0 + package-name: php-8.0.1.zip + location: https://github.com/pubnub/php/releases/tag/8.0.1 requires: - name: rmccue/requests min-version: 1.0.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dc3d68..e526bbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## 8.0.1 +April 01 2025 + +#### Fixed +- Added missing information in file publish endpoint. + +#### Modified +- Basic usage examples have been added. + ## 8.0.0 March 19 2025 diff --git a/README.md b/README.md index 0cbeeeb..8072ea8 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ You will need the publish and subscribe keys to authenticate your app. Get your { "require": { - "pubnub/pubnub": "8.0.0" + "pubnub/pubnub": "8.0.1" } } ``` diff --git a/composer.json b/composer.json index 1b50921..14a5af5 100644 --- a/composer.json +++ b/composer.json @@ -5,7 +5,7 @@ "keywords": ["api", "real-time", "realtime", "real time", "ajax", "push"], "homepage": "http://www.pubnub.com/", "license": "proprietary", - "version": "8.0.0", + "version": "8.0.1", "authors": [ { "name": "PubNub", diff --git a/examples/Membersips/channel_members.php b/examples/Membersips/channel_members.php index bf989a6..275b40a 100644 --- a/examples/Membersips/channel_members.php +++ b/examples/Membersips/channel_members.php @@ -4,22 +4,28 @@ set_time_limit(0); -require('../../vendor/autoload.php'); +require('vendor/autoload.php'); use PubNub\PubNub; use PubNub\PNConfiguration; use PubNub\Models\Consumer\Objects\Member\PNMemberIncludes; use PubNub\Models\Consumer\Objects\Member\PNChannelMember; -$pnConfig = new PNConfiguration(); -$pnConfig->setPublishKey('demo'); -$pnConfig->setSubscribeKey('demo'); -$pnConfig->setUserId('demo'); +$config = new PNConfiguration(); +$config->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); +$config->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); +$config->setUserId('demo'); -$pubnub = new PubNub($pnConfig); +$pubnub = new PubNub($config); $includes = new PNMemberIncludes(); -$includes->user()->userId()->userCustom()->userType()->userStatus()->custom()->status()->type(); +$includes->user() + ->userCustom() + ->userType() + ->userStatus() + ->custom() + ->status() + ->type(); $channel_members = [ (new PNChannelMember('uuid1')) @@ -32,6 +38,10 @@ ->setType("type") ]; -$set_response = $pubnub->setMembers()->include($includes)->channel("ch")->members($channel_members)->sync(); +$set_response = $pubnub->setMembers() + ->include($includes) + ->channel("ch") + ->members($channel_members) + ->sync(); var_dump($set_response); diff --git a/examples/basic_usage/access_manager.php b/examples/basic_usage/access_manager.php new file mode 100644 index 0000000..4615b56 --- /dev/null +++ b/examples/basic_usage/access_manager.php @@ -0,0 +1,50 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setSecretKey(getenv("SECRET_KEY") ?? "demo"); // Required for Access Manager operations +$pnConfig->setUserId("php-token-granter"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Grant token with permissions to a channel + $token = $pubnub->grantToken() + ->ttl(15) // Time-to-live in minutes (min: 1, max: 43200) + ->authorizedUuid('php-authorized-user') + ->addChannelResources([ + 'my-channel' => ['read' => true, 'write' => true, 'update' => true], + ]) + ->sync(); + + // Print the token + echo "Generated token: " . $token . PHP_EOL; + + // Example of how to use the token in a client application + echo "How to use this token in a client:" . PHP_EOL; + echo " 1. Initialize a PubNub client without secretKey" . PHP_EOL; + echo " 2. Set token with: \$pubnub->setToken(\"" . $token . "\");" . PHP_EOL; + echo " 3. Use the authorized UUID: php-authorized-user" . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle errors + echo "Error generating token: " . $exception->getServerErrorMessage() . PHP_EOL; + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + + if ($exception->getServerErrorSource()) { + echo "Error Source: " . $exception->getServerErrorSource() . PHP_EOL; + } + + if ($exception->getServerErrorDetails()) { + echo "Error Details: " . print_r($exception->getServerErrorDetails(), true) . PHP_EOL; + } +} diff --git a/examples/basic_usage/channel_groups.php b/examples/basic_usage/channel_groups.php new file mode 100644 index 0000000..a201178 --- /dev/null +++ b/examples/basic_usage/channel_groups.php @@ -0,0 +1,46 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-channel-group-demo"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Add channels to channel group + $result = $pubnub->addChannelToChannelGroup() + ->channels(["news", "sports"]) + ->channelGroup("my-group") + ->sync(); + + // Print success message + echo "Channels added to group successfully!" . PHP_EOL; + + // Example of how to use this channel group for subscription + echo PHP_EOL . "To subscribe to this channel group:" . PHP_EOL; + echo '$pubnub->subscribe()->channelGroups(["my-group"])->execute();' . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle errors + echo "Error adding channels to group: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/configuration.php b/examples/basic_usage/configuration.php new file mode 100644 index 0000000..2f41471 --- /dev/null +++ b/examples/basic_usage/configuration.php @@ -0,0 +1,68 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); + +// Set publish key (only required if publishing) +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); + +// Set UUID (required to connect) +$pnConfig->setUserId("php-sdk-example-user"); + +// Set up cryptography for message encryption (optional) +// Uncomment the line below to enable encryption +// $pnConfig->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true)); + +// Set authentication key (optional, required only when using Access Manager) +// $pnConfig->setAuthKey("my_auth_key"); + +// Configure connection timeout in seconds +$pnConfig->setConnectTimeout(10); + +// Configure subscribe request timeout in seconds +$pnConfig->setSubscribeTimeout(310); + +// Configure non-subscribe request timeout in seconds +$pnConfig->setNonSubscribeRequestTimeout(10); + +// Set filter expression (optional) +// $pnConfig->setFilterExpression("channel == 'my-channel'"); + +// Create PubNub instance with the configured settings +$pubnub = new PubNub($pnConfig); + +// Display configuration information +echo "PubNub Configuration:\n"; +echo "Subscribe Key: " . $pnConfig->getSubscribeKey() . "\n"; +echo "Publish Key: " . $pnConfig->getPublishKey() . "\n"; +echo "User ID: " . $pnConfig->getUserId() . "\n"; +echo "Encryption: " . ($pnConfig->getCryptoSafe() ? "enabled" : "disabled") . "\n"; + +// Now you can use this PubNub instance to publish and subscribe + +// Example: Create a simple message +$message = ["text" => "Hello from PHP SDK!"]; + +// Example: Publish the message (uncomment to execute) +/* +$pubnub->publish() + ->channel("demo-channel") + ->message($message) + ->sync(); + +echo "Message published to 'demo-channel'\n"; +*/ + +// Keep this code running only if you plan to subscribe to messages +// Otherwise, the script will exit after publishing diff --git a/examples/basic_usage/files.php b/examples/basic_usage/files.php new file mode 100644 index 0000000..a3e5ecb --- /dev/null +++ b/examples/basic_usage/files.php @@ -0,0 +1,70 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-file-upload-demo"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Define channel and file paths + $channelName = "file-sharing-channel"; + $fileName = "example.txt"; + $filePath = __DIR__ . DIRECTORY_SEPARATOR . $fileName; + + // Create a sample file if it doesn't exist + if (!file_exists($filePath)) { + file_put_contents($filePath, "This is a sample file for PubNub file upload demo."); + } + + // Open file handle for reading + $fileHandle = fopen($filePath, "r"); + + // Send file to the channel + $sendFileResult = $pubnub->sendFile() + ->channel($channelName) + ->fileName($fileName) + ->message("Hello from PHP SDK") + ->fileHandle($fileHandle) + ->sync(); + + // Close file handle + fclose($fileHandle); + + // Print success message + echo "File uploaded successfully!" . PHP_EOL; + echo "File name: " . $sendFileResult->getFileName() . PHP_EOL; + echo "File ID: " . $sendFileResult->getFileId() . PHP_EOL; + + // Example of how to download this file + echo PHP_EOL . "To download this file, use:" . PHP_EOL; + echo '$result = $pubnub->downloadFile()' . PHP_EOL; + echo ' ->channel("' . $channelName . '")' . PHP_EOL; + echo ' ->fileId("' . $sendFileResult->getFileId() . '")' . PHP_EOL; + echo ' ->fileName("' . $sendFileResult->getFileName() . '")' . PHP_EOL; + echo ' ->sync();' . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error uploading file: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/message_actions.php b/examples/basic_usage/message_actions.php new file mode 100644 index 0000000..3d992d2 --- /dev/null +++ b/examples/basic_usage/message_actions.php @@ -0,0 +1,74 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-message-action-demo"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // First publish a message to react to + $channelName = "pizza_talks"; + $publishResult = $pubnub->publish() + ->channel($channelName) + ->message(["text" => "Chicago deep dish is the best pizza!"]) + ->sync(); + + // Get the timetoken of the published message + $messageTimetoken = $publishResult->getTimetoken(); + echo "Message published with timetoken: " . $messageTimetoken . PHP_EOL; + + // Create a message action (reaction) for the published message + $messageAction = new PNMessageAction([ + "type" => "reaction", + "value" => "drooling_face", + "messageTimetoken" => $messageTimetoken + ]); + + // Add the message action + $result = $pubnub->addMessageAction() + ->channel($channelName) + ->messageAction($messageAction) + ->sync(); + + // Print the result + echo "Message action added successfully!" . PHP_EOL; + echo "Type: " . $result->type . PHP_EOL; + echo "Value: " . $result->value . PHP_EOL; + echo "UUID: " . $result->uuid . PHP_EOL; + echo "Action Timetoken: " . $result->actionTimetoken . PHP_EOL; + echo "Message Timetoken: " . $result->messageTimetoken . PHP_EOL; + + // Example of how to remove this action + echo PHP_EOL . "To remove this action, use:" . PHP_EOL; + echo '$pubnub->removeMessageAction()' . PHP_EOL; + echo ' ->channel("' . $channelName . '")' . PHP_EOL; + echo ' ->messageTimetoken(' . $result->messageTimetoken . ')' . PHP_EOL; + echo ' ->actionTimetoken(' . $result->actionTimetoken . ')' . PHP_EOL; + echo ' ->sync();' . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error adding message action: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/misc.php b/examples/basic_usage/misc.php new file mode 100644 index 0000000..0b76a11 --- /dev/null +++ b/examples/basic_usage/misc.php @@ -0,0 +1,52 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-time-example-user"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Fetch the current PubNub timetoken + $result = $pubnub->time()->sync(); + + // Display the timetoken in different formats + echo "PubNub Timetoken: " . $result->getTimetoken() . PHP_EOL; + + // Calculate and display the Unix timestamp (seconds) + $unixTimestamp = floor($result->getTimetoken() / 10000000); + echo "Unix Timestamp (seconds): " . $unixTimestamp . PHP_EOL; + + // Convert to a readable date/time format + $readableDate = date('Y-m-d H:i:s', $unixTimestamp); + echo "Human Readable Date: " . $readableDate . PHP_EOL; + + // Example: Using timetoken for synchronization + echo PHP_EOL . "Example usage:" . PHP_EOL; + echo "- Use this timetoken as a reference point for synchronizing events" . PHP_EOL; + echo "- Create a channel history request starting from this time" . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error fetching timetoken: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/mobile_push.php b/examples/basic_usage/mobile_push.php new file mode 100644 index 0000000..4413442 --- /dev/null +++ b/examples/basic_usage/mobile_push.php @@ -0,0 +1,59 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-push-demo-user"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +// Define channels to enable push notifications on +$channelsForPush = ["news", "alerts", "promotions"]; + +// FCM/GCM device token (typically a long string generated by Firebase) +$deviceId = "fcm-device-registration-token-from-firebase"; + +try { + // Register the device to receive push notifications on the specified channels + $result = $pubnub->addChannelsToPush() + ->pushType(PNPushType::FCM) // Use GCM/FCM for Android devices + ->channels($channelsForPush) + ->deviceId($deviceId) + ->sync(); + + echo "Device successfully registered for push notifications!" . PHP_EOL; + echo "Device ID: " . $deviceId . PHP_EOL; + echo "Channels: " . implode(", ", $channelsForPush) . PHP_EOL; + + // Example: Verify channels were added by listing current push registrations + echo PHP_EOL . "To verify which channels this device is registered for, use:" . PHP_EOL; + echo '$result = $pubnub->listPushProvisions()' . PHP_EOL; + echo ' ->pushType(PNPushType::FCM)' . PHP_EOL; + echo ' ->deviceId("' . $deviceId . '")' . PHP_EOL; + echo ' ->sync();' . PHP_EOL; + echo 'print_r($result->getChannels());' . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error registering device for push: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/objects.php b/examples/basic_usage/objects.php new file mode 100644 index 0000000..c359712 --- /dev/null +++ b/examples/basic_usage/objects.php @@ -0,0 +1,85 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-app-context-demo"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Fetch metadata for all users with custom fields and total count + $response = $pubnub->getAllUUIDMetadata() + ->includeFields([ + "totalCount" => true, + "customFields" => true + ]) + ->limit(10) // Limit results to 10 users per page + ->sync(); + + // Display total count if available + if ($response->getTotalCount() !== null) { + echo "Total users: " . $response->getTotalCount() . PHP_EOL; + } + + // Display user data + echo "Retrieved " . count($response->getData()) . " users:" . PHP_EOL; + + foreach ($response->getData() as $index => $userData) { + echo PHP_EOL . ($index + 1) . ". User ID: " . $userData->getId() . PHP_EOL; + + if ($userData->getName()) { + echo " Name: " . $userData->getName() . PHP_EOL; + } + + if ($userData->getEmail()) { + echo " Email: " . $userData->getEmail() . PHP_EOL; + } + + // Display custom data if available + if ($userData->getCustom()) { + echo " Custom data:" . PHP_EOL; + foreach (get_object_vars($userData->getCustom()) as $key => $value) { + echo " - $key: " . (is_scalar($value) ? $value : json_encode($value)) . PHP_EOL; + } + } + } + + // Show pagination information if available + if ($response->getNext()) { + echo PHP_EOL . "For next page, use:" . PHP_EOL; + echo '$pubnub->getAllUUIDMetadata()' . PHP_EOL; + echo ' ->page(["next" => "' . $response->getNext() . '"])' . PHP_EOL; + echo ' ->sync();' . PHP_EOL; + } + + if ($response->getPrev()) { + echo PHP_EOL . "For previous page, use:" . PHP_EOL; + echo '$pubnub->getAllUUIDMetadata()' . PHP_EOL; + echo ' ->page(["prev" => "' . $response->getPrev() . '"])' . PHP_EOL; + echo ' ->sync();' . PHP_EOL; + } +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error fetching user metadata: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/presence.php b/examples/basic_usage/presence.php new file mode 100644 index 0000000..e83acc0 --- /dev/null +++ b/examples/basic_usage/presence.php @@ -0,0 +1,76 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-presence-demo-user"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Get presence information for specified channels + $result = $pubnub->hereNow() + ->channels(["my_channel", "demo"]) + ->includeUuids(true) // Include the UUIDs of connected clients + ->includeState(false) // Don't include state information + ->sync(); + + // Display total counts + echo "Total channels with presence: " . $result->getTotalChannels() . PHP_EOL; + echo "Total users online: " . $result->getTotalOccupancy() . PHP_EOL; + + // Iterate through each channel + foreach ($result->getChannels() as $channelData) { + echo PHP_EOL . "Channel: " . $channelData->getChannelName() . PHP_EOL; + echo "Occupancy: " . $channelData->getOccupancy() . " users" . PHP_EOL; + + // List all users in the channel + if ($channelData->getOccupancy() > 0) { + echo "Users present:" . PHP_EOL; + + foreach ($channelData->getOccupants() as $index => $occupant) { + echo ($index + 1) . ". UUID: " . $occupant->getUuid() . PHP_EOL; + + // Display state if available and requested + if ($occupant->getState()) { + echo " State: " . json_encode($occupant->getState()) . PHP_EOL; + } + } + } else { + echo "No users currently in this channel" . PHP_EOL; + } + } + + // Example: How to use the result in your application + echo PHP_EOL . "Example usage:" . PHP_EOL; + echo "- Track how many users are in each channel" . PHP_EOL; + echo "- Display a list of active users" . PHP_EOL; + echo "- Check if a specific user is online" . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub-specific errors + echo "Error getting presence information: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (PubNubException $exception) { + // Handle general PubNub exceptions + echo "PubNub Error: " . $exception->getMessage() . PHP_EOL; +} catch (Exception $exception) { + // Handle other exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/publish.php b/examples/basic_usage/publish.php new file mode 100644 index 0000000..c2bb7f4 --- /dev/null +++ b/examples/basic_usage/publish.php @@ -0,0 +1,70 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("php-publish-demo-user"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Create message data + $messageData = [ + "text" => "Hello from PHP SDK!", + "timestamp" => time(), + "sender" => [ + "name" => "PHP Publisher", + "id" => "php-demo" + ] + ]; + + // Publish a message to a channel + $result = $pubnub->publish() + ->channel("my_channel") // Channel to publish to + ->message($messageData) // Message content + ->shouldStore(true) // Store in history + ->ttl(15) // Time to live (hours) + ->usePost(true) // Use POST method + ->customMessageType("text-message") // Custom message type + ->sync(); // Execute synchronously + + // Display success message with timetoken + echo "Message published successfully!" . PHP_EOL; + echo "Timetoken: " . $result->getTimetoken() . PHP_EOL; + + // Convert timetoken to readable date + $timestamp = floor($result->getTimetoken() / 10000000); + $readableDate = date('Y-m-d H:i:s', $timestamp); + echo "Published at: " . $readableDate . PHP_EOL; + + // Display published message + echo PHP_EOL . "Published message: " . PHP_EOL; + echo json_encode($messageData, JSON_PRETTY_PRINT) . PHP_EOL; +} catch (PubNubServerException $exception) { + // Handle PubNub server-specific errors + echo "Error publishing message: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (PubNubException $exception) { + // Handle PubNub-specific errors + echo "PubNub Error: " . $exception->getMessage() . PHP_EOL; +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/basic_usage/storage_and_playback.php b/examples/basic_usage/storage_and_playback.php new file mode 100644 index 0000000..86cbb2e --- /dev/null +++ b/examples/basic_usage/storage_and_playback.php @@ -0,0 +1,109 @@ +setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); +$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); +$pnConfig->setUserId("fetch-messages-demo-user"); + +// Initialize PubNub instance +$pubnub = new PubNub($pnConfig); + +try { + // Fetch the last message from a channel with all additional data + $result = $pubnub->fetchMessages() + ->channels("my_channel") // Channel to fetch from + ->includeMessageActions(true) // Include reactions to messages + ->includeMeta(true) // Include metadata + ->includeMessageType(true) // Include message type + ->includeCustomMessageType(true) // Include custom message type + ->includeUuid(true) // Include sender UUID + ->sync(); // Execute synchronously + + // Process and display the results + if (!empty($result->getChannels())) { + echo "Successfully fetched message history" . PHP_EOL; + + // Display timetoken range + echo "Start timetoken: " . $result->getStartTimetoken() . PHP_EOL; + echo "End timetoken: " . $result->getEndTimetoken() . PHP_EOL . PHP_EOL; + + // Process each channel in the result + foreach ($result->getChannels() as $channelName => $messages) { + echo "Channel: " . $channelName . PHP_EOL; + echo "Number of messages: " . count($messages) . PHP_EOL; + echo "----------------------------" . PHP_EOL; + + // Process each message in the channel + foreach ($messages as $index => $item) { + echo "Message #" . ($index + 1) . ":" . PHP_EOL; + + // Convert timetoken to readable date + $timestamp = floor($item->getTimetoken() / 10000000); + $readableDate = date('Y-m-d H:i:s', $timestamp); + echo "Date: " . $readableDate . PHP_EOL; + + // Display message content + echo "Content: " . json_encode($item->getMessage(), JSON_PRETTY_PRINT) . PHP_EOL; + + // Display sender UUID if available + if ($item->getUuid()) { + echo "Sender: " . $item->getUuid() . PHP_EOL; + } + + // Display metadata if available + if ($item->getMetadata()) { + echo "Metadata: " . json_encode($item->getMetadata(), JSON_PRETTY_PRINT) . PHP_EOL; + } + + // Display message type information if available + if ($item->getMessageType()) { + echo "Message Type: " . $item->getMessageType() . PHP_EOL; + } + if ($item->getCustomMessageType()) { + echo "Custom Message Type: " . $item->getCustomMessageType() . PHP_EOL; + } + + // Display message actions (reactions) if available + if ($item->getActions() && count($item->getActions()) > 0) { + echo "Message Actions:" . PHP_EOL; + foreach ($item->getActions() as $actionType => $actions) { + echo " " . $actionType . ":" . PHP_EOL; + foreach ($actions as $actionValue => $users) { + echo " " . $actionValue . ": " . count($users) . " reactions" . PHP_EOL; + } + } + } + + echo "----------------------------" . PHP_EOL; + } + } + } else { + echo "No messages found in the channel." . PHP_EOL; + } +} catch (PubNubServerException $exception) { + // Handle PubNub server-specific errors + echo "Error fetching messages: " . $exception->getMessage() . PHP_EOL; + + if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) { + echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL; + } + + if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) { + echo "Status Code: " . $exception->getStatusCode() . PHP_EOL; + } +} catch (PubNubException $exception) { + // Handle PubNub-specific errors + echo "PubNub Error: " . $exception->getMessage() . PHP_EOL; +} catch (Exception $exception) { + // Handle general exceptions + echo "Error: " . $exception->getMessage() . PHP_EOL; +} diff --git a/examples/cli/partial_updates.php b/examples/cli/partial_updates.php index 27b3169..bb0adde 100644 --- a/examples/cli/partial_updates.php +++ b/examples/cli/partial_updates.php @@ -30,10 +30,8 @@ // Set channel metadata $pubnub->setChannelMetadata() ->channel($channel) - ->meta([ - "name" => $name, - "description" => $description, - ]) + ->setName($name) + ->setDescription($description) ->sync(); print("The channel has been created with name and description.\n"); @@ -81,11 +79,9 @@ // Writing the updated object back to the server $pubnub->setChannelMetadata() ->channel($channel) - ->meta([ - "name" => $response->getName(), - "description" => $response->getDescription(), - "custom" => $custom, - ]) + ->setName($response->getName()) + ->setDescription($response->getDescription()) + ->setCustom($custom) ->sync(); print("Object has been updated.\n"); } diff --git a/examples/cli/using_etag.php b/examples/cli/using_etag.php index 540b703..ce08c75 100644 --- a/examples/cli/using_etag.php +++ b/examples/cli/using_etag.php @@ -7,8 +7,8 @@ use PubNub\PNConfiguration; $config = new PNConfiguration(); -$config->setPublishKey('demo'); -$config->setSubscribeKey('demo'); +$config->setPublishKey(getenv('PUBLISH_KEY') ?? 'demo'); +$config->setSubscribeKey(getenv('SUBSCRIBE_KEY') ?? 'demo'); $config->setUuid("example"); $config_2 = clone $config; diff --git a/examples/pn.gif b/examples/pn.gif new file mode 100644 index 0000000..225b5f1 Binary files /dev/null and b/examples/pn.gif differ diff --git a/src/PubNub/Endpoints/Endpoint.php b/src/PubNub/Endpoints/Endpoint.php index 2179feb..16f6377 100755 --- a/src/PubNub/Endpoints/Endpoint.php +++ b/src/PubNub/Endpoints/Endpoint.php @@ -487,6 +487,7 @@ protected function requestOptions() 'connect_timeout' => $this->getConnectTimeout(), 'useragent' => 'PHP/' . PHP_VERSION, 'allow_redirects' => (bool)$this->followRedirects, + 'version' => '2', ]; } diff --git a/src/PubNub/Endpoints/FileSharing/SendFile.php b/src/PubNub/Endpoints/FileSharing/SendFile.php index 47eeeeb..8afb352 100644 --- a/src/PubNub/Endpoints/FileSharing/SendFile.php +++ b/src/PubNub/Endpoints/FileSharing/SendFile.php @@ -293,7 +293,8 @@ public function sync(): PNPublishFileMessageResult } $publishResponse = $publishRequest->sync(); - + $publishResponse->setFileId($this->fileUploadEnvelope->getFileId()); + $publishResponse->setFileName($this->fileName); return $publishResponse; } } diff --git a/src/PubNub/Models/Consumer/FileSharing/PNPublishFileMessageResult.php b/src/PubNub/Models/Consumer/FileSharing/PNPublishFileMessageResult.php index 6fbfc9b..c9bbf44 100644 --- a/src/PubNub/Models/Consumer/FileSharing/PNPublishFileMessageResult.php +++ b/src/PubNub/Models/Consumer/FileSharing/PNPublishFileMessageResult.php @@ -5,6 +5,8 @@ class PNPublishFileMessageResult { protected $timestamp; + protected ?string $fileId; + protected ?string $fileName; public function __construct($json) { @@ -20,4 +22,26 @@ public function getTimestamp() { return $this->timestamp; } + + public function getFileId(): ?string + { + return $this->fileId; + } + + public function getFileName(): ?string + { + return $this->fileName; + } + + public function setFileId(string $fileId): self + { + $this->fileId = $fileId; + return $this; + } + + public function setFileName(string $fileName): self + { + $this->fileName = $fileName; + return $this; + } } diff --git a/src/PubNub/PNConfiguration.php b/src/PubNub/PNConfiguration.php index cdb18dc..5362f31 100755 --- a/src/PubNub/PNConfiguration.php +++ b/src/PubNub/PNConfiguration.php @@ -383,6 +383,18 @@ public function setCrypto(PubNubCryptoCore $crypto): self return $this; } + /** + * @param CryptoModule $crypto + * @return $this + */ + public function setCryptoModule(CryptoModule $crypto): self + { + $this->checkLock(); + $this->crypto = $crypto; + + return $this; + } + /** * @return string */ diff --git a/src/PubNub/PubNub.php b/src/PubNub/PubNub.php index a2f118d..234148a 100644 --- a/src/PubNub/PubNub.php +++ b/src/PubNub/PubNub.php @@ -68,7 +68,7 @@ class PubNub implements LoggerAwareInterface { - protected const SDK_VERSION = "8.0.0"; + protected const SDK_VERSION = "8.0.1"; protected const SDK_NAME = "PubNub-PHP"; public static $MAX_SEQUENCE = 65535;