From be7e990875496c39f7318713d2f8d836216a2f70 Mon Sep 17 00:00:00 2001 From: Roland Gaida Date: Tue, 6 Oct 2015 15:29:35 +0200 Subject: [PATCH 1/5] Fixes missing json encoding for non-image payloads (introduced by the image uploading fix, sorry for that). Changes parameter order for method Client::sendDirectMessage(), because the attachments parameter is more likely to be used than the source_guid parameter. Adds a new method Client::getAddMembersToGroupResult() to evaluate results from a call to Client::addMembersToGroup(); this replaces the misleading named (but otherwise identical) method Client::getGroupMembers() Adds docblock comments to most methods. --- README.md | 2 +- src/AttachmentUtils.php | 72 +++++++ src/Client.php | 457 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 509 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 1d6f902..4a53fe8 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ public function disableSmsMode() ``` ### Attachments -When sending messages (bot, direct, or group), you can specify an array of attachments. A factory class exists to easily create attachments: `GroupMeApiClient\AttachmentUtils`. +When sending messages (bot, direct, or group), you can specify an array of attachments. A factory class exists to easily create attachments: `GroupMeApi\AttachmentUtils`. ```php public static function makeLocationAttachment($lat, $lng, $name='') public static function makeImageAttachment($image_url) diff --git a/src/AttachmentUtils.php b/src/AttachmentUtils.php index bb97ee0..a20ff7f 100644 --- a/src/AttachmentUtils.php +++ b/src/AttachmentUtils.php @@ -4,6 +4,15 @@ class AttachmentUtils { private function __construct() {} + /** + * GroupMe Location Attachment + * + * @param float $lat Latitude + * @param float $lng Longitude + * @param string $name Location description or name + * + * @return string[] + */ public static function makeLocationAttachment($lat, $lng, $name='') { return array( 'type' => 'location', @@ -13,6 +22,57 @@ public static function makeLocationAttachment($lat, $lng, $name='') { ); } + /** + * GroupMe Mentions Attachment + * + * $strpos needs a tuple for each user id with the first item consisting of + * the index of the start of the mention, and the second item is the length + * of the mention text + * + * @param int[] $users Array of user ids to mention + * @param int[] $strpos Text positions of user names to highlight + * + * @return array + */ + public static function makeMentionsAttachment($users, $strpos) { + return array( + 'type' => 'mentions', + 'user_ids' => $users, + 'loci' => $strpos + ); + } + + /** + * Gets text position tuples for the mentions attachment + * + * @param mixed $txt Message text including user mention(s) + * @param mixed $usernames User name(s) of mentioned user(s) + * @param mixed $mchar Mention indicator (typically "@") + * + * @return array[] Position and length of user names in message + */ + public static function getUsernamePositions($txt, $usernames, $mchar = '@') { + $loci = array(); + + foreach ($usernames as $username) { + $mention = $mchar . $username; + $pos = strpos($txt, $mention); + + if ($pos === FALSE) break; + + $loci[] = array($pos, strlen($mention)); + } + + return $loci; + } + + /** + * GroupMe Image Attachment + * + * @param string $image_url GroupMe Image Service URL + * + * @return array + */ public static function makeImageAttachment($image_url) { return array( 'type' => 'image', @@ -20,6 +80,11 @@ public static function makeImageAttachment($image_url) { ); } + /** + * Summary of makeSplitAttachment + * + * @return string[] + */ public static function makeSplitAttachment() { return array( 'type' => 'split', @@ -27,6 +92,13 @@ public static function makeSplitAttachment() { ); } + /** + * GroupMe Emoji Attachment + * + * @param array $charmap + * + * @return array + */ public static function makeEmojiAttachment(array $charmap) { return array( 'type' => 'emoji', diff --git a/src/Client.php b/src/Client.php index ca435f4..9a3a870 100644 --- a/src/Client.php +++ b/src/Client.php @@ -1,26 +1,58 @@ token = $token; } - // Image Service methods - public function uploadImage($image_file, $mime, $name) { + // IMAGE SERVICE METHODS + + /** + * Uploads an image to the GroupMe Image Service + * + * @param string $image_file Filename fo the image file + * @param string $mime Mime type of the image file (e.g. 'image/png') + * @param string $name Optional image name or description + * + * @return string[] API result + */ + public function uploadImage($image_file, $mime, $name = '') { $curl_file = new \CURLFile($image_file, $mime, $name); $payload = array('file' => $curl_file); return $this->request('POST', '/pictures', array(), $payload, true); } - // Bot methods + // BOT METHODS + + /** + * Lists your existing bots + * + * @return string[] API result + */ public function getMyBots() { return $this->get('/bots'); } - public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='') { + /** + * Creates a new bot + * + * @param string $bot_name Name of the bot + * @param int $group_id Group id where the bot will be used + * @param string $avatar_url Avatar image (GroupMe ImgService url) + * @param string $callback_url Callback url + * + * @return string[] API result with bot id on success + */ + public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='') { $bot_info = array( 'name' => $bot_name, 'group_id' => $group_id, @@ -31,6 +63,15 @@ public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='' return $this->post('/bots', $payload); } + /** + * Sends a bot message + * + * @param string $bot_id Bot id + * @param string $text Message to send + * @param array $attachments Message attachments + * + * @return string[] API result + */ public function sendBotMessage($bot_id, $text, array $attachments=array()) { $payload = array( 'bot_id' => $bot_id, @@ -40,19 +81,37 @@ public function sendBotMessage($bot_id, $text, array $attachments=array()) { return $this->post('/bots/post', $payload); } + /** + * Destroys a bot + * + * @param string $bot_id Bot id + * + * @return string[] API result + */ public function destroyBot($bot_id) { $payload = array('bot_id' => $bot_id); return $this->post('/bots/destroy', $payload); } - // Direct Message methods + // DIRECT MESSAGE METHODS + + /** + * Summary of getOtherUserIdFromConversationId + * @param mixed $conversation_id + * @return mixed + */ public function getOtherUserIdFromConversationId($conversation_id) { $my_details = $this->getMyDetails(); $my_user_id = $my_details['response']['id']; $user_ids = explode('+', $conversation_id); return $my_user_id==$user_ids[0] ? $user_ids[1] : $user_ids[0]; } - + + /** + * Summary of getConversationIdFromOtherUserId + * @param mixed $other_user_id + * @return string + */ public function getConversationIdFromOtherUserId($other_user_id) { $my_details = $this->getMyDetails(); $my_user_id = intval($my_details['response']['id']); @@ -60,6 +119,17 @@ public function getConversationIdFromOtherUserId($other_user_id) { return min($my_user_id,$o_user_id) . '+' . max($my_user_id,$o_user_id); } + /** + * Gets direct message chats + * + * Returns a paginated list of direct message chats, or conversations, + * sorted by updated_at descending + * + * @param int $page Page number + * @param int $per_page Number of chats per page + * + * @return mixed + */ public function getDirectMessageChats($page=1, $per_page=10) { $query = array( 'page' => $page, @@ -68,6 +138,14 @@ public function getDirectMessageChats($page=1, $per_page=10) { return $this->get('/chats', $query); } + /** + * Fetches direct messages between two users + * + * @param string $other_user_id The other participant + * @param int $limit Number of messages to retrieve + * + * @return mixed + */ public function getLatestDirectMessages($other_user_id, $limit=20) { $query = array( 'other_user_id' => $other_user_id, @@ -76,6 +154,14 @@ public function getLatestDirectMessages($other_user_id, $limit=20) { return $this->get('/direct_messages', $query); } + /** + * Fetches 20 messages created before the given message ID + * + * @param string $other_user_id The other participant + * @param string $message_id Message id + * + * @return mixed + */ public function getDirectMessagesBefore($other_user_id, $message_id) { $query = array( 'other_user_id' => $other_user_id, @@ -84,6 +170,14 @@ public function getDirectMessagesBefore($other_user_id, $message_id) { return $this->get('/direct_messages', $query); } + /** + * Fetches 20 messages created after the given message ID + * + * @param string $other_user_id The other participant + * @param string $message_id Message id + * + * @return mixed + */ public function getDirectMessagesSince($other_user_id, $message_id) { $query = array( 'other_user_id' => $other_user_id, @@ -92,28 +186,66 @@ public function getDirectMessagesSince($other_user_id, $message_id) { return $this->get('/direct_messages', $query); } - public function sendDirectMessage($other_user_id, $text, $source_guid=null, array $attachments=array()) { + /** + * Sends a DM to another user + * + * @param string $other_user_id The other participant + * @param string $text Message text + * @param array $attachments Message attachments + * @param string $source_guid Unique id + * + * @return mixed + */ + public function sendDirectMessage($other_user_id, $text, array $attachments=array(), + $source_guid=null) { + $message_info = array( 'recipient_id' => $other_user_id, 'text' => $text, - 'source_guid' => $source_guid ?: "D$other_user_id-". date('YmdHis-') . uniqid(), + 'source_guid' => $source_guid ?: "D$other_user_id-". + date('YmdHis-') . uniqid(), 'attachments' => $attachments ); $payload = array('direct_message' => $message_info); return $this->post('/direct_messages', $payload); } + /** + * Likes a message + * + * @param string $other_user_id The other participant + * @param string $message_id Message to like + * + * @return mixed + */ public function likeDirectMessage($other_user_id, $message_id) { $conversation_id = $this->getConversationIdFromOtherUserId($other_user_id); return $this->post("/messages/$conversation_id/$message_id/like"); } + /** + * Unlikes a message + * + * @param string $other_user_id The other participant + * @param string $message_id Message to like + * + * @return mixed + */ public function unlikeDirectMessage($other_user_id, $message_id) { $conversation_id = $this->getConversationIdFromOtherUserId($other_user_id); return $this->post("/messages/$conversation_id/$message_id/unlike"); } - // Group methods + // GROUP METHODS + + /** + * Lists the authenticated user's active groups + * + * @param int $page Fetch a particular page of results (defaults to 1) + * @param int $per_page Messages per page (defaults to 10) + * + * @return mixed + */ public function getAllGroups($page=1, $per_page=10) { $query = array( 'page' => $page, @@ -122,90 +254,271 @@ public function getAllGroups($page=1, $per_page=10) { return $this->get('/groups', $query); } + /** + * Lists the groups you have left but can rejoin + * + * @return mixed + */ public function getFormerGroups() { return $this->get('/groups/former'); } + /** + * Creates a new group + * + * @param string $name Primary name of the group (max 140 characters) + * @param string $description A subheading for the group (max 255 characters) + * @param string $image_url GroupMe Image Service URL + * @param bool $share If true, a share URL will be created + * + * @return mixed + */ public function createGroup($name, $description='', $image_url='', $share=false) { $payload = array( - 'name' =>$name, - 'description' => $description, + 'name' => substr($name, 0, (strlen($name) <= 140) ? strlen($name) : 140), + 'description' => substr($description, 0, + (strlen($description) <= 255) ? strlen($description) : 255), 'image_url' => $image_url, 'share' => boolval($share) ); return $this->post('/groups', $payload); } + /** + * Retrieves a specific group + * + * @param string $group_id Group id + * + * @return mixed + */ public function getGroupDetails($group_id) { return $this->get("/groups/$group_id"); } + /** + * Updates a group after creation + * + * $payload = array( + * 'name' => ..., + * 'share' => ..., + * 'image_url' => ..., + * 'office_mode' => ... + * ); + * + * @param mixed $group_id + * @param array $payload + * @return mixed + */ public function updateGroupDetails($group_id, array $payload) { + return $this->post("/groups/$group_id/update", $payload); } + /** + * Destroys a group + * + * @param string $group_id Group id + * + * @return mixed + */ public function destroyGroup($group_id) { return $this->post("/groups/$group_id/destroy"); } + /** + * Joins a shared group + * + * @param string $group_id Group id + * @param string $share_token Share token + * + * @return mixed + */ public function joinGroup($group_id, $share_token) { return $this->post("/groups/$group_id/join/$share_token"); } + /** + * Rejoins a group. + * + * Only works if you previously removed yourself + * + * @param string $group_id Group id + * + * @return mixed + */ public function rejoinGroup($group_id) { $payload = array('group_id' => $group_id); return $this->post('/groups/join', $payload); } + /** + * Gets a list of liked messages for a given period of time + * + * Messages are ranked in order of number of likes. + * + * @param string $group_id Group id + * @param string $period Period of: 'day', 'week', or 'month' + * + * @return mixed + */ public function getLeaderboard($group_id, $period='day') { $query = array('period' => $period); return $this->get("/groups/$group_id/likes", $query); } + /** + * Gets a list of liked messages for a day + * + * Messages are ranked in order of number of likes. + * + * @param string $group_id Group id + * + * @return mixed + */ public function getLeaderboardForDay($group_id) { return $this->getLeaderboard($group_id, 'day'); } + /** + * Gets a list of liked messages for a week + * + * Messages are ranked in order of number of likes. + * + * @param string $group_id Group id + * + * @return mixed + */ public function getLeaderboardForWeek($group_id) { return $this->getLeaderboard($group_id, 'week'); } + /** + * Gets a list of liked messages for a month + * + * Messages are ranked in order of number of likes. + * + * @param string $group_id Group id + * + * @return mixed + */ public function getLeaderboardForMonth($group_id) { return $this->getLeaderboard($group_id, 'month'); } + /** + * Fetches a list of messages you have liked + * + * @param string $group_id Group id + * + * @return mixed + */ public function getMyLikes($group_id) { return $this->get("/groups/$group_id/likes/mine"); } + /** + * Fetches a list of messages others have liked + * + * @param string $group_id Group id + * + * @return mixed + */ public function getMyHits($group_id) { return $this->get("/groups/$group_id/likes/for_me"); } + /** + * Adds members to a group + * + * To add a member, you must use one of the following + * identifiers: user_id, phone_number, or email. + * + * $new_member = array( + * string $nickname, // required + * string $user_id, + * string $phone_number, + * string $email, + * string $guid + * ); + * + * @param string $group_id Group id + * @param array $members One or more members to add + * + * @return mixed + */ public function addMembersToGroup($group_id, array $members) { $payload = array('members' => $members); return $this->post("/groups/$group_id/members/add", $payload); } + /** + * Gets the membership results from an add call + * + * @param string $group_id Group id + * @param string $guid The guid that's returned from an add request. + * + * @return mixed + */ + public function getAddMembersToGroupResult($group_id, $guid) { + return $this->get("/groups/$group_id/members/results/$guid"); + } + + /** + * Updates your nickname in a group + * + * The nickname must be between 1 and 50 characters + * + * @param string $group_id Group id + * @param string $nickname Nickname + * + * @return mixed + */ public function updateMyGroupMembership($group_id, $nickname) { + $maxNickLen = 50; + $nickname = (strlen($nickname) <= $maxNickLen) ? $nickname : substr($nickname, 0, $maxNickLen - 1); $membership_info = array('nickname' => $nickname); $payload = array('membership' => $membership_info); return $this->post("/groups/$group_id/memberships/update", $payload); } - - public function getGroupMembers($group_id, $results_id) { - return $this->get("/groups/$group_id/members/results/$results_id"); - } + /** + * Removes a member (or yourself) from a group + * + * @param string $group_id Group id + * @param string $user_id User id + * + * @return mixed + */ public function removeGroupMember($group_id, $user_id) { return $this->post("/groups/$group_id/members/$user_id/remove"); } + /** + * Retrieves messages for a group + * + * By default, messages are returned in groups of 20, ordered by + * created_at descending. This can be raised or lowered by passing + * a limit parameter, up to a maximum of 100 messages. + * + * @param int $group_id Group id + * @param int $limit Number of messages to retrieve + * + * @return mixed + */ public function getLatestGroupMessages($group_id, $limit=20) { $query = array('limit' => $limit); return $this->get("/groups/$group_id/messages", $query); } + /** + * Retrieves messages created before the given message ID + * + * @param int $group_id Group id + * @param string $message_id Message id + * @param int $limit Number of messages to retrieve + * + * @return mixed + */ public function getGroupMessagesBefore($group_id, $message_id, $limit=20) { $query = array( 'before_id' => $message_id, @@ -214,6 +527,15 @@ public function getGroupMessagesBefore($group_id, $message_id, $limit=20) { return $this->get("/groups/$group_id/messages", $query); } + /** + * Retrieves messages created immediately after the given message ID + * + * @param int $group_id Group id + * @param string $message_id Message id + * @param int $limit Number of messages to retrieve + * + * @return mixed + */ public function getGroupMessagesAfter($group_id, $message_id, $limit=20) { $query = array( 'after_id' => $message_id, @@ -222,6 +544,15 @@ public function getGroupMessagesAfter($group_id, $message_id, $limit=20) { return $this->get("/groups/$group_id/messages", $query); } + /** + * Retrieves most recent messages created after the given message ID + * + * @param int $group_id Group id + * @param string $message_id Message id + * @param int $limit Number of messages to retrieve + * + * @return mixed + */ public function getGroupMessagesSince($group_id, $message_id, $limit=20) { $query = array( 'since_id' => $message_id, @@ -230,7 +561,19 @@ public function getGroupMessagesSince($group_id, $message_id, $limit=20) { return $this->get("/groups/$group_id/messages", $query); } - public function sendGroupMessage($group_id, $text, $source_guid=null, array $attachments=array()) { + /** + * Sends a message to a group + * + * @param int $group_id Group id + * @param string $text Message text + * @param string $source_guid Unique id + * @param array $attachments Message attachments + * + * @return mixed + */ + public function sendGroupMessage($group_id, $text, $source_guid=null, + array $attachments=array()) { + $message_info = array( 'text' => $text, 'source_guid' => $source_guid ?: "G$group_id-" . date('YmdHis-') . uniqid(), @@ -240,15 +583,48 @@ public function sendGroupMessage($group_id, $text, $source_guid=null, array $att return $this->post("/groups/$group_id/messages", $payload); } - // User methods + // USER METHODS + + /** + * Gets details about the authenticated user + * + * @return mixed + */ public function getMyDetails() { return $this->get('/users/me'); } - public function updateMyDetails(array $payload) { + /** + * Updates attributes about your own account + * + * $payload = array( + * string $avatar_url URL to valid JPG/PNG/GIF image, + * string $name Name must be of the form FirstName LastName, + * string $email Email address. Must be in name@domain.com form, + * string $zip Zip code + * ) + * + * @return mixed + */ + public function updateMyDetails($payload) { return $this->post('/users/update', $payload); } - + + /** + * Enables SMS mode + * + * Enables SMS mode for N hours, where N is at most 48. + * After N hours have elapsed, user will receive push notfications + * + * If the push notification ID/token that should be suppressed during + * SMS mode is omitted, both SMS and push notifications + * will be delivered to the device. + * + * @param mixed $duration N hour duration + * @param string $registration_id Push notification ID/token + * + * @return mixed + */ public function enableSmsMode($duration, $registration_id) { $payload = array( 'duration' => $duration, @@ -257,20 +633,55 @@ public function enableSmsMode($duration, $registration_id) { return $this->post('/users/sms_mode', $payload); } + /** + * DISABLES SMS MODE + * + * @return mixed + */ public function disableSmsMode() { return $this->post('/users/sms_mode/delete'); } // Core methods + + /** + * Gets data from an endpoint + * + * @param string $endpoint API endpoint + * @param array $query Request + * + * @return mixed + */ private function get($endpoint, array $query=array()) { return $this->request('GET', $endpoint, $query); } + /** + * Posts data to an endpoint + * + * @param string $endpoint API endpoint + * @param array $payload Payload + * + * @return mixed + */ private function post($endpoint, array $payload=array()) { return $this->request('POST', $endpoint, array(), $payload); } - private function request($method, $endpoint, array $query=array(), array $payload=array(), $img_svc_url=false) { + /** + * Sends a curl post/get request + * + * @param string $method POST or GET method + * @param string $endpoint Endpoint path + * @param array $query Query + * @param array $payload Payload + * @param bool $img_svc_url Image upload? + * + * @return mixed API result + */ + private function request($method, $endpoint, array $query=array(), + array $payload=array(), $img_svc_url=false) { + if ($img_svc_url) { $base_url = 'https://image.groupme.com'; $header = 'Content-Type: multipart/form-data'; @@ -278,13 +689,17 @@ private function request($method, $endpoint, array $query=array(), array $payloa else { $base_url = 'https://api.groupme.com/v3'; $header = 'Content-Type: application/json'; + $payload = json_encode($payload); } $query['access_token'] = $this->token; $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array($header)); - curl_setopt($ch, CURLOPT_URL, $base_url . $endpoint . '?' . http_build_query($query)); + + curl_setopt($ch, CURLOPT_URL, + $base_url . $endpoint . '?' . http_build_query($query)); + curl_setopt($ch, CURLOPT_TIMEOUT, 4); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'GroupMe API Client'); From 6b7b7005117f9027c5b10d66fd2ccd07b1d6903b Mon Sep 17 00:00:00 2001 From: Roland Gaida Date: Tue, 6 Oct 2015 15:37:10 +0200 Subject: [PATCH 2/5] Updates README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4a53fe8..83de719 100644 --- a/README.md +++ b/README.md @@ -51,14 +51,14 @@ public function getLeaderboardForMonth($group_id) public function getMyLikes($group_id) public function getMyHits($group_id) public function addMembersToGroup($group_id, array $members) +public function getAddMembersToGroupResult($group_id, $results_id) public function updateMyGroupMembership($group_id, $nickname) -public function getGroupMembers($group_id, $results_id) public function removeGroupMember($group_id, $user_id) public function getLatestGroupMessages($group_id, $limit=20) public function getGroupMessagesBefore($group_id, $message_id, $limit=20) public function getGroupMessagesAfter($group_id, $message_id, $limit=20) public function getGroupMessagesSince($group_id, $message_id, $limit=20) -public function sendGroupMessage($group_id, $text, $source_guid=null, array $attachments=array()) +public function sendGroupMessage($group_id, $text, array $attachments=array(), $source_guid=null) ``` ##### User methods @@ -74,6 +74,7 @@ When sending messages (bot, direct, or group), you can specify an array of attac ```php public static function makeLocationAttachment($lat, $lng, $name='') public static function makeImageAttachment($image_url) +public static function makeMentionsAttachment($users, $strpos) public static function makeSplitAttachment() public static function makeEmojiAttachment(array $charmap) ``` From 5bc3a42d26c4cf7fe7d42dcc9a7be11a87946523 Mon Sep 17 00:00:00 2001 From: Roland Gaida Date: Wed, 7 Oct 2015 12:53:48 +0200 Subject: [PATCH 3/5] - Merges changes from original repo - Implements a simple caching system - Adds helper functions `Client::getGroupIdByName()`, `Client::getGroupNameById()` and `Client::isMemberOfGroup()` --- src/Client.php | 237 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 211 insertions(+), 26 deletions(-) diff --git a/src/Client.php b/src/Client.php index aba6be0..e90f741 100644 --- a/src/Client.php +++ b/src/Client.php @@ -3,7 +3,19 @@ namespace GroupMeApi; class Client { + + const MAX_GROUPS_PER_REQUEST = 499; + const MAX_PRI_NAME_LEN = 140; + const MAX_GRP_DESC_LEN = 255; + + const HTTP_OK = 200; + const HTTP_BAD_REQUEST = 400; + private $token; + + private $cache; + private $useCache; + private $cacheTimeout; /** * Class constructor @@ -130,7 +142,7 @@ public function getConversationIdFromOtherUserId($other_user_id) { * * @return mixed */ - public function getDirectMessageChats($page=1, $per_page=10) { + public function getDirectMessageChats($page = 1, $per_page = 10) { $query = array( 'page' => $page, 'per_page' => $per_page @@ -146,7 +158,7 @@ public function getDirectMessageChats($page=1, $per_page=10) { * * @return mixed */ - public function getLatestDirectMessages($other_user_id, $limit=20) { + public function getLatestDirectMessages($other_user_id, $limit = 20) { $query = array( 'other_user_id' => $other_user_id, 'limit' => $limit @@ -238,6 +250,63 @@ public function unlikeDirectMessage($other_user_id, $message_id) { // GROUP METHODS + /** + * Gets a group id by the group name + * + * @param string $name Group name + * + * @return mixed Group id or FALSE + */ + public function getGroupIdByName($name) { + $res = $this->getAllGroups(); + + if($res['meta']['code'] == self::HTTP_OK) + foreach($res['response'] as $group) { + if ($group['name'] == $name) return $group['id']; + } + + return FALSE; + } + + /** + * Checks if the authenticated user is a member + * of a certain group + * + * @param mixed $grp Group name or group id + * + * @return bool + */ + public function isMemberOfGroup($grp) { + $res = $this->getAllGroups(); + + if($res['meta']['code'] == self::HTTP_OK) { + foreach($res['response'] as $group) { + if ((is_numeric($grp) && $group['id'] == $grp) || + (is_string($grp) && $group['name'] == $grp)) return TRUE; + } + } + + return FALSE; + } + + /** + * Gets a group name by its id + * + * @param int $id Group id + * + * @return mixed Group name or FALSE + */ + public function getGroupNameById($id) { + $res = $this->getAllGroups(); + + if($res['meta']['code'] == self::HTTP_OK) + foreach($res['response'] as $group) { + if ($group['id'] == $id) return $group['name']; + } + + return FALSE; + } + /** * Lists the authenticated user's active groups * @@ -246,13 +315,22 @@ public function unlikeDirectMessage($other_user_id, $message_id) { * * @return mixed */ - public function getAllGroups($page=1, $per_page=10) { + public function getGroups($page = 1, $per_page = 10) { $query = array( 'page' => $page, 'per_page' => $per_page ); return $this->get('/groups', $query); } + + /** + * Lists the maximum number of the authenticated user's active groups + * + * @return mixed + */ + public function getAllGroups() { + return $this->getGroups(1, self::MAX_GROUPS_PER_REQUEST); + } /** * Lists the groups you have left but can rejoin @@ -262,7 +340,7 @@ public function getAllGroups($page=1, $per_page=10) { public function getFormerGroups() { return $this->get('/groups/former'); } - + /** * Creates a new group * @@ -275,9 +353,12 @@ public function getFormerGroups() { */ public function createGroup($name, $description='', $image_url='', $share=false) { $payload = array( - 'name' => substr($name, 0, (strlen($name) <= 140) ? strlen($name) : 140), - 'description' => substr($description, 0, - (strlen($description) <= 255) ? strlen($description) : 255), + 'name' => substr($name, 0, (strlen($name) <= + self::MAX_PRI_NAME_LEN) ? strlen($name) : self::MAX_PRI_NAME_LEN), + + 'description' => substr($description, 0, (strlen($description) <= + self::MAX_GRP_DESC_LEN) ? strlen($description) : self::MAX_GRP_DESC_LEN), + 'image_url' => $image_url, 'share' => boolval($share) ); @@ -634,7 +715,7 @@ public function enableSmsMode($duration, $registration_id) { } /** - * DISABLES SMS MODE + * Disables SMS mode * * @return mixed */ @@ -642,7 +723,7 @@ public function disableSmsMode() { return $this->post('/users/sms_mode/delete'); } - // Core methods + // CORE METHODS /** * Gets data from an endpoint @@ -689,30 +770,134 @@ private function request($method, $endpoint, array $query=array(), else { $base_url = 'https://api.groupme.com/v3'; $header = 'Content-Type: application/json'; - $payload = json_encode($payload); } $query['access_token'] = $this->token; - $ch = curl_init(); - curl_setopt($ch, CURLOPT_HTTPHEADER, array($header)); + $url = $base_url . $endpoint . '?' . http_build_query($query); - curl_setopt($ch, CURLOPT_URL, - $base_url . $endpoint . '?' . http_build_query($query)); + if ($this->isCached($url)) { + $result = $this->getFromCache($url); + } else { - curl_setopt($ch, CURLOPT_TIMEOUT, 4); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_USERAGENT, 'GroupMe API Client'); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - - if ($method == 'POST') { - $data = $img_svc_url ? $payload : json_encode($payload); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HTTPHEADER, array($header)); + curl_setopt($ch, CURLOPT_URL, $url); + + curl_setopt($ch, CURLOPT_TIMEOUT, 4); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_USERAGENT, 'GroupMe API Client'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + + if ($method == 'POST') { + $data = $img_svc_url ? $payload : json_encode($payload); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + } + + $result = $this->cache($url, curl_exec($ch)); + + curl_close($ch); } - - $result = curl_exec($ch); - curl_close($ch); + return json_decode($result, true); } + + // CACHE METHODS + + /** + * Enables or disable caching of CURL GET responses + * + * @param bool $mode If TRUE, responses will be cached + * @param int $timeout Timeout in seconds for cached content + * + */ + public function useResponseCaching($mode, $timeout = 300) { + $this->useCache = $mode; + $this->cacheTimeout = $timeout; + } + + /** + * Checks if an item is in the cache and not + * timed out + * + * @param string $key Item key + * + * @return bool Returns true, if item is cached + */ + private function isCached($key) { + if (!$this->useCache) return FALSE; + $idx = $this->getCacheIndex($key); + if (isset($this->cache[$idx])) { + return ($this->cache[$idx]['timestamp'] + + $this->cacheTimeout > time()); + } + return FALSE; + } + + /** + * Creates an index string from a given key + * + * Cache items are indexed by a hash value + * generated from the key + * + * @param string $key Item key, e.g. request url, ... + * + * @return string Index string + */ + private function getCacheIndex($key) { + return md5($key); + } + + /** + * Gets an item from the cache + * + * @param string $key Item key + * + * @return mixed + */ + private function getFromCache($key) { + if ($this->isCached($key)) { + return $this->cache[$this->getCacheIndex($key)]['data']; + } + + return FALSE; + } + + /** + * Clears the cache + */ + public function clearCache() { + $this->cache = NULL; + } + + /** + * Removes outdated items from the cache + */ + public function purgeCache() { + foreach($this->cache as $key => $item) { + if ($item['timestamp'] + $this->cacheTimeout < time()) { + $this->cache[$key] = NULL; + } + } + } + + /** + * Puts data in the cache + * + * @param string $key Item key + * @param mixed $data Item data + * + * @return mixed Returns $data + */ + private function cache($key, $data) { + if ($this->useCache) { + $this->cache[$this->getCacheIndex($key)] = + array('timestamp' => time(), 'data' => $data); + } + + return $data; + } + + } From 4babedb16921dbb9974eda405d106a46e3b12090 Mon Sep 17 00:00:00 2001 From: Roland Gaida Date: Wed, 7 Oct 2015 13:40:25 +0200 Subject: [PATCH 4/5] Updates README.md, adds funtion Client::getGroupMembers(), minor changes in requesting group details --- README.md | 9 +++++- src/Client.php | 88 ++++++++++++++++++++++++++++++++++---------------- 2 files changed, 68 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 32eddbf..298258f 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,10 @@ public function unlikeDirectMessage($other_user_id, $message_id) ##### Group methods ```php -public function getAllGroups($page=1, $per_page=10) +public function getAllGroups() +public function getGroups($page = 1, $per_page = 10) +public function getGroupByName($name) +public function getGroupById($group_id) public function getFormerGroups() public function createGroup($name, $description='', $image_url='', $share=false) public function getGroupDetails($group_id) @@ -52,12 +55,16 @@ public function getMyLikes($group_id) public function getMyHits($group_id) public function addMembersToGroup($group_id, array $members) public function getAddMembersToGroupResult($group_id, $results_id) +public function getGroupMembers($group_id) public function updateMyGroupMembership($group_id, $nickname) public function removeGroupMember($group_id, $user_id) public function getLatestGroupMessages($group_id, $limit=20) public function getGroupMessagesBefore($group_id, $message_id, $limit=20) public function getGroupMessagesAfter($group_id, $message_id, $limit=20) public function getGroupMessagesSince($group_id, $message_id, $limit=20) +public function getGroupNameById($id) +public function getGroupIdByName($name) +public function isMemberOfGroup($grp) public function sendGroupMessage($group_id, $text, array $attachments=array(), $source_guid=null) ``` diff --git a/src/Client.php b/src/Client.php index e90f741..79fb493 100644 --- a/src/Client.php +++ b/src/Client.php @@ -250,24 +250,6 @@ public function unlikeDirectMessage($other_user_id, $message_id) { // GROUP METHODS - /** - * Gets a group id by the group name - * - * @param string $name Group name - * - * @return mixed Group id or FALSE - */ - public function getGroupIdByName($name) { - $res = $this->getAllGroups(); - - if($res['meta']['code'] == self::HTTP_OK) - foreach($res['response'] as $group) { - if ($group['name'] == $name) return $group['id']; - } - - return FALSE; - } - /** * Checks if the authenticated user is a member * of a certain group @@ -289,20 +271,53 @@ public function isMemberOfGroup($grp) { return FALSE; } + function getGroupById($group_id) { + return $this->get("/groups/$group_id"); + } + + function getGroupByName($name) { + $res = $this->getAllGroups(); + + if($res['meta']['code'] == self::HTTP_OK) + foreach($res['response'] as $group) { + if ($group['name'] == $name) + return array( + 'meta' => $res['meta'], + 'response' => $group + ); + } + + return $res; + } + + /** + * Gets a group id by the group name + * + * @param string $name Group name + * + * @return mixed Group id or FALSE + */ + public function getGroupIdByName($name) { + $res = $this->getGroupByName($name); + + if($res['meta']['code'] == self::HTTP_OK) + return $res['response']['id']; + + return FALSE; + } + /** * Gets a group name by its id * - * @param int $id Group id + * @param int $group_id Group id * * @return mixed Group name or FALSE */ - public function getGroupNameById($id) { - $res = $this->getAllGroups(); + public function getGroupNameById($group_id) { + $res = $this->getGroupById($group_id); if($res['meta']['code'] == self::HTTP_OK) - foreach($res['response'] as $group) { - if ($group['id'] == $id) return $group['name']; - } + return $res['response']['name']; return FALSE; } @@ -366,14 +381,16 @@ public function createGroup($name, $description='', $image_url='', $share=false) } /** - * Retrieves a specific group + * Retrieves group details * - * @param string $group_id Group id + * @param string $group Group id or group name * * @return mixed */ - public function getGroupDetails($group_id) { - return $this->get("/groups/$group_id"); + public function getGroupDetails($group) { + if (is_numeric($group)) return $this->getGroupById($group); + if (is_string($group)) return $this->getGroupByName($group); + return array(); } /** @@ -562,6 +579,21 @@ public function updateMyGroupMembership($group_id, $nickname) { return $this->post("/groups/$group_id/memberships/update", $payload); } + /** + * Gets all members of a group + * + * @param int $group_id Group id + * + * @return array Group members or empty array + */ + public function getGroupMembers($group_id) { + $group = $this->getGroupDetails($group_id); + if (is_array($group['response']['members'])) + return $group['response']['members']; + + return array(); + } + /** * Removes a member (or yourself) from a group * From 3d302295e8dc78a4556dedb8084f5072976c8fd4 Mon Sep 17 00:00:00 2001 From: Roland Gaida Date: Wed, 7 Oct 2015 13:48:05 +0200 Subject: [PATCH 5/5] Minor changes (adds some more docblock comments) --- src/Client.php | 403 ++++++++++++++++++++++++++----------------------- 1 file changed, 215 insertions(+), 188 deletions(-) diff --git a/src/Client.php b/src/Client.php index 79fb493..8486535 100644 --- a/src/Client.php +++ b/src/Client.php @@ -3,38 +3,48 @@ namespace GroupMeApi; class Client { - + /** + * Maximum number of groups per request + */ const MAX_GROUPS_PER_REQUEST = 499; + + /** + * Maximum length of primary group names + */ const MAX_PRI_NAME_LEN = 140; + + /** + * Maximum length of group descriptions + */ const MAX_GRP_DESC_LEN = 255; const HTTP_OK = 200; const HTTP_BAD_REQUEST = 400; private $token; - + private $cache; private $useCache; private $cacheTimeout; /** * Class constructor - * + * * @param string $token GroupMe API Token */ public function __construct($token='') { $this->token = $token; } - + // IMAGE SERVICE METHODS /** * Uploads an image to the GroupMe Image Service - * + * * @param string $image_file Filename fo the image file * @param string $mime Mime type of the image file (e.g. 'image/png') * @param string $name Optional image name or description - * + * * @return string[] API result */ public function uploadImage($image_file, $mime, $name = '') { @@ -42,29 +52,29 @@ public function uploadImage($image_file, $mime, $name = '') { $payload = array('file' => $curl_file); return $this->request('POST', '/pictures', array(), $payload, true); } - + // BOT METHODS /** * Lists your existing bots - * + * * @return string[] API result */ public function getMyBots() { return $this->get('/bots'); } - + /** * Creates a new bot - * + * * @param string $bot_name Name of the bot - * @param int $group_id Group id where the bot will be used + * @param int $group_id Group id where the bot will be used * @param string $avatar_url Avatar image (GroupMe ImgService url) * @param string $callback_url Callback url - * + * * @return string[] API result with bot id on success */ - public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='') { + public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='') { $bot_info = array( 'name' => $bot_name, 'group_id' => $group_id, @@ -74,14 +84,14 @@ public function createBot($bot_name, $group_id, $avatar_url='', $callback_url='' $payload = array('bot' => $bot_info); return $this->post('/bots', $payload); } - + /** * Sends a bot message - * + * * @param string $bot_id Bot id * @param string $text Message to send * @param array $attachments Message attachments - * + * * @return string[] API result */ public function sendBotMessage($bot_id, $text, array $attachments=array()) { @@ -95,21 +105,21 @@ public function sendBotMessage($bot_id, $text, array $attachments=array()) { /** * Destroys a bot - * + * * @param string $bot_id Bot id - * + * * @return string[] API result */ public function destroyBot($bot_id) { $payload = array('bot_id' => $bot_id); return $this->post('/bots/destroy', $payload); } - + // DIRECT MESSAGE METHODS /** * Summary of getOtherUserIdFromConversationId - * @param mixed $conversation_id + * @param mixed $conversation_id * @return mixed */ public function getOtherUserIdFromConversationId($conversation_id) { @@ -121,7 +131,7 @@ public function getOtherUserIdFromConversationId($conversation_id) { /** * Summary of getConversationIdFromOtherUserId - * @param mixed $other_user_id + * @param mixed $other_user_id * @return string */ public function getConversationIdFromOtherUserId($other_user_id) { @@ -130,16 +140,16 @@ public function getConversationIdFromOtherUserId($other_user_id) { $o_user_id = intval($other_user_id); return min($my_user_id,$o_user_id) . '+' . max($my_user_id,$o_user_id); } - + /** * Gets direct message chats - * - * Returns a paginated list of direct message chats, or conversations, + * + * Returns a paginated list of direct message chats, or conversations, * sorted by updated_at descending - * + * * @param int $page Page number * @param int $per_page Number of chats per page - * + * * @return mixed */ public function getDirectMessageChats($page = 1, $per_page = 10) { @@ -149,13 +159,13 @@ public function getDirectMessageChats($page = 1, $per_page = 10) { ); return $this->get('/chats', $query); } - + /** * Fetches direct messages between two users - * + * * @param string $other_user_id The other participant * @param int $limit Number of messages to retrieve - * + * * @return mixed */ public function getLatestDirectMessages($other_user_id, $limit = 20) { @@ -165,13 +175,13 @@ public function getLatestDirectMessages($other_user_id, $limit = 20) { ); return $this->get('/direct_messages', $query); } - + /** * Fetches 20 messages created before the given message ID - * + * * @param string $other_user_id The other participant * @param string $message_id Message id - * + * * @return mixed */ public function getDirectMessagesBefore($other_user_id, $message_id) { @@ -181,13 +191,13 @@ public function getDirectMessagesBefore($other_user_id, $message_id) { ); return $this->get('/direct_messages', $query); } - + /** * Fetches 20 messages created after the given message ID - * + * * @param string $other_user_id The other participant * @param string $message_id Message id - * + * * @return mixed */ public function getDirectMessagesSince($other_user_id, $message_id) { @@ -200,12 +210,12 @@ public function getDirectMessagesSince($other_user_id, $message_id) { /** * Sends a DM to another user - * + * * @param string $other_user_id The other participant * @param string $text Message text * @param array $attachments Message attachments * @param string $source_guid Unique id - * + * * @return mixed */ public function sendDirectMessage($other_user_id, $text, array $attachments=array(), @@ -214,48 +224,48 @@ public function sendDirectMessage($other_user_id, $text, array $attachments=arra $message_info = array( 'recipient_id' => $other_user_id, 'text' => $text, - 'source_guid' => $source_guid ?: "D$other_user_id-". + 'source_guid' => $source_guid ?: "D$other_user_id-". date('YmdHis-') . uniqid(), 'attachments' => $attachments ); $payload = array('direct_message' => $message_info); return $this->post('/direct_messages', $payload); } - + /** * Likes a message - * + * * @param string $other_user_id The other participant * @param string $message_id Message to like - * + * * @return mixed */ public function likeDirectMessage($other_user_id, $message_id) { $conversation_id = $this->getConversationIdFromOtherUserId($other_user_id); return $this->post("/messages/$conversation_id/$message_id/like"); } - + /** * Unlikes a message - * + * * @param string $other_user_id The other participant * @param string $message_id Message to like - * + * * @return mixed */ public function unlikeDirectMessage($other_user_id, $message_id) { $conversation_id = $this->getConversationIdFromOtherUserId($other_user_id); return $this->post("/messages/$conversation_id/$message_id/unlike"); } - + // GROUP METHODS /** * Checks if the authenticated user is a member * of a certain group - * + * * @param mixed $grp Group name or group id - * + * * @return bool */ public function isMemberOfGroup($grp) { @@ -263,7 +273,7 @@ public function isMemberOfGroup($grp) { if($res['meta']['code'] == self::HTTP_OK) { foreach($res['response'] as $group) { - if ((is_numeric($grp) && $group['id'] == $grp) || + if ((is_numeric($grp) && $group['id'] == $grp) || (is_string($grp) && $group['name'] == $grp)) return TRUE; } } @@ -271,16 +281,33 @@ public function isMemberOfGroup($grp) { return FALSE; } + /** + * Gets a group by its id + * + * @param int $group_id + * + * @return array API response + */ function getGroupById($group_id) { return $this->get("/groups/$group_id"); } + /** + * Gets a group by its name + * + * There is no check for ambiguous names in place! + * The first match will be returned. + * + * @param mixed $name + * + * @return array API response + */ function getGroupByName($name) { $res = $this->getAllGroups(); - if($res['meta']['code'] == self::HTTP_OK) + if($res['meta']['code'] == self::HTTP_OK) foreach($res['response'] as $group) { - if ($group['name'] == $name) + if ($group['name'] == $name) return array( 'meta' => $res['meta'], 'response' => $group @@ -292,15 +319,15 @@ function getGroupByName($name) { /** * Gets a group id by the group name - * + * * @param string $name Group name - * + * * @return mixed Group id or FALSE */ public function getGroupIdByName($name) { $res = $this->getGroupByName($name); - if($res['meta']['code'] == self::HTTP_OK) + if($res['meta']['code'] == self::HTTP_OK) return $res['response']['id']; return FALSE; @@ -308,15 +335,15 @@ public function getGroupIdByName($name) { /** * Gets a group name by its id - * + * * @param int $group_id Group id - * + * * @return mixed Group name or FALSE */ public function getGroupNameById($group_id) { $res = $this->getGroupById($group_id); - if($res['meta']['code'] == self::HTTP_OK) + if($res['meta']['code'] == self::HTTP_OK) return $res['response']['name']; return FALSE; @@ -324,10 +351,10 @@ public function getGroupNameById($group_id) { /** * Lists the authenticated user's active groups - * + * * @param int $page Fetch a particular page of results (defaults to 1) * @param int $per_page Messages per page (defaults to 10) - * + * * @return mixed */ public function getGroups($page = 1, $per_page = 10) { @@ -340,16 +367,16 @@ public function getGroups($page = 1, $per_page = 10) { /** * Lists the maximum number of the authenticated user's active groups - * + * * @return mixed */ - public function getAllGroups() { + public function getAllGroups() { return $this->getGroups(1, self::MAX_GROUPS_PER_REQUEST); } - + /** * Lists the groups you have left but can rejoin - * + * * @return mixed */ public function getFormerGroups() { @@ -358,20 +385,20 @@ public function getFormerGroups() { /** * Creates a new group - * + * * @param string $name Primary name of the group (max 140 characters) * @param string $description A subheading for the group (max 255 characters) * @param string $image_url GroupMe Image Service URL * @param bool $share If true, a share URL will be created - * + * * @return mixed */ public function createGroup($name, $description='', $image_url='', $share=false) { $payload = array( - 'name' => substr($name, 0, (strlen($name) <= + 'name' => substr($name, 0, (strlen($name) <= self::MAX_PRI_NAME_LEN) ? strlen($name) : self::MAX_PRI_NAME_LEN), - 'description' => substr($description, 0, (strlen($description) <= + 'description' => substr($description, 0, (strlen($description) <= self::MAX_GRP_DESC_LEN) ? strlen($description) : self::MAX_GRP_DESC_LEN), 'image_url' => $image_url, @@ -379,12 +406,12 @@ public function createGroup($name, $description='', $image_url='', $share=false) ); return $this->post('/groups', $payload); } - + /** * Retrieves group details - * + * * @param string $group Group id or group name - * + * * @return mixed */ public function getGroupDetails($group) { @@ -392,10 +419,10 @@ public function getGroupDetails($group) { if (is_string($group)) return $this->getGroupByName($group); return array(); } - + /** * Updates a group after creation - * + * * $payload = array( * 'name' => ..., * 'share' => ..., @@ -403,20 +430,20 @@ public function getGroupDetails($group) { * 'office_mode' => ... * ); * - * @param mixed $group_id - * @param array $payload + * @param mixed $group_id + * @param array $payload * @return mixed */ public function updateGroupDetails($group_id, array $payload) { - + return $this->post("/groups/$group_id/update", $payload); } - + /** * Destroys a group - * + * * @param string $group_id Group id - * + * * @return mixed */ public function destroyGroup($group_id) { @@ -425,10 +452,10 @@ public function destroyGroup($group_id) { /** * Joins a shared group - * + * * @param string $group_id Group id * @param string $share_token Share token - * + * * @return mixed */ public function joinGroup($group_id, $share_token) { @@ -436,67 +463,67 @@ public function joinGroup($group_id, $share_token) { } /** - * Rejoins a group. - * + * Rejoins a group. + * * Only works if you previously removed yourself - * + * * @param string $group_id Group id - * + * * @return mixed */ public function rejoinGroup($group_id) { $payload = array('group_id' => $group_id); return $this->post('/groups/join', $payload); } - + /** * Gets a list of liked messages for a given period of time - * + * * Messages are ranked in order of number of likes. - * + * * @param string $group_id Group id - * @param string $period Period of: 'day', 'week', or 'month' - * + * @param string $period Period of: 'day', 'week', or 'month' + * * @return mixed */ public function getLeaderboard($group_id, $period='day') { $query = array('period' => $period); return $this->get("/groups/$group_id/likes", $query); } - + /** * Gets a list of liked messages for a day - * + * * Messages are ranked in order of number of likes. - * + * * @param string $group_id Group id - * + * * @return mixed */ public function getLeaderboardForDay($group_id) { return $this->getLeaderboard($group_id, 'day'); } - + /** * Gets a list of liked messages for a week - * + * * Messages are ranked in order of number of likes. - * + * * @param string $group_id Group id - * + * * @return mixed */ public function getLeaderboardForWeek($group_id) { return $this->getLeaderboard($group_id, 'week'); } - + /** * Gets a list of liked messages for a month - * + * * Messages are ranked in order of number of likes. - * + * * @param string $group_id Group id - * + * * @return mixed */ public function getLeaderboardForMonth($group_id) { @@ -505,9 +532,9 @@ public function getLeaderboardForMonth($group_id) { /** * Fetches a list of messages you have liked - * + * * @param string $group_id Group id - * + * * @return mixed */ public function getMyLikes($group_id) { @@ -516,21 +543,21 @@ public function getMyLikes($group_id) { /** * Fetches a list of messages others have liked - * + * * @param string $group_id Group id - * + * * @return mixed */ public function getMyHits($group_id) { return $this->get("/groups/$group_id/likes/for_me"); } - + /** * Adds members to a group - * - * To add a member, you must use one of the following - * identifiers: user_id, phone_number, or email. - * + * + * To add a member, you must use one of the following + * identifiers: user_id, phone_number, or email. + * * $new_member = array( * string $nickname, // required * string $user_id, @@ -538,10 +565,10 @@ public function getMyHits($group_id) { * string $email, * string $guid * ); - * + * * @param string $group_id Group id * @param array $members One or more members to add - * + * * @return mixed */ public function addMembersToGroup($group_id, array $members) { @@ -551,10 +578,10 @@ public function addMembersToGroup($group_id, array $members) { /** * Gets the membership results from an add call - * + * * @param string $group_id Group id - * @param string $guid The guid that's returned from an add request. - * + * @param string $guid The guid that's returned from an add request. + * * @return mixed */ public function getAddMembersToGroupResult($group_id, $guid) { @@ -563,12 +590,12 @@ public function getAddMembersToGroupResult($group_id, $guid) { /** * Updates your nickname in a group - * + * * The nickname must be between 1 and 50 characters - * + * * @param string $group_id Group id * @param string $nickname Nickname - * + * * @return mixed */ public function updateMyGroupMembership($group_id, $nickname) { @@ -578,58 +605,58 @@ public function updateMyGroupMembership($group_id, $nickname) { $payload = array('membership' => $membership_info); return $this->post("/groups/$group_id/memberships/update", $payload); } - + /** * Gets all members of a group - * + * * @param int $group_id Group id - * + * * @return array Group members or empty array */ public function getGroupMembers($group_id) { $group = $this->getGroupDetails($group_id); if (is_array($group['response']['members'])) - return $group['response']['members']; + return $group['response']['members']; - return array(); + return array(); } /** * Removes a member (or yourself) from a group - * + * * @param string $group_id Group id * @param string $user_id User id - * + * * @return mixed */ public function removeGroupMember($group_id, $user_id) { return $this->post("/groups/$group_id/members/$user_id/remove"); } - + /** * Retrieves messages for a group - * - * By default, messages are returned in groups of 20, ordered by - * created_at descending. This can be raised or lowered by passing + * + * By default, messages are returned in groups of 20, ordered by + * created_at descending. This can be raised or lowered by passing * a limit parameter, up to a maximum of 100 messages. * * @param int $group_id Group id * @param int $limit Number of messages to retrieve - * + * * @return mixed */ public function getLatestGroupMessages($group_id, $limit=20) { $query = array('limit' => $limit); return $this->get("/groups/$group_id/messages", $query); } - + /** * Retrieves messages created before the given message ID - * + * * @param int $group_id Group id * @param string $message_id Message id * @param int $limit Number of messages to retrieve - * + * * @return mixed */ public function getGroupMessagesBefore($group_id, $message_id, $limit=20) { @@ -639,14 +666,14 @@ public function getGroupMessagesBefore($group_id, $message_id, $limit=20) { ); return $this->get("/groups/$group_id/messages", $query); } - + /** * Retrieves messages created immediately after the given message ID - * + * * @param int $group_id Group id * @param string $message_id Message id * @param int $limit Number of messages to retrieve - * + * * @return mixed */ public function getGroupMessagesAfter($group_id, $message_id, $limit=20) { @@ -656,14 +683,14 @@ public function getGroupMessagesAfter($group_id, $message_id, $limit=20) { ); return $this->get("/groups/$group_id/messages", $query); } - + /** - * Retrieves most recent messages created after the given message ID - * + * Retrieves most recent messages created after the given message ID + * * @param int $group_id Group id * @param string $message_id Message id * @param int $limit Number of messages to retrieve - * + * * @return mixed */ public function getGroupMessagesSince($group_id, $message_id, $limit=20) { @@ -676,15 +703,15 @@ public function getGroupMessagesSince($group_id, $message_id, $limit=20) { /** * Sends a message to a group - * + * * @param int $group_id Group id * @param string $text Message text * @param string $source_guid Unique id * @param array $attachments Message attachments - * + * * @return mixed */ - public function sendGroupMessage($group_id, $text, $source_guid=null, + public function sendGroupMessage($group_id, $text, $source_guid=null, array $attachments=array()) { $message_info = array( @@ -695,28 +722,28 @@ public function sendGroupMessage($group_id, $text, $source_guid=null, $payload = array('message' => $message_info); return $this->post("/groups/$group_id/messages", $payload); } - + // USER METHODS /** * Gets details about the authenticated user - * + * * @return mixed */ public function getMyDetails() { return $this->get('/users/me'); } - + /** * Updates attributes about your own account - * + * * $payload = array( * string $avatar_url URL to valid JPG/PNG/GIF image, * string $name Name must be of the form FirstName LastName, * string $email Email address. Must be in name@domain.com form, * string $zip Zip code * ) - * + * * @return mixed */ public function updateMyDetails($payload) { @@ -724,19 +751,19 @@ public function updateMyDetails($payload) { } /** - * Enables SMS mode - * - * Enables SMS mode for N hours, where N is at most 48. + * Enables SMS mode + * + * Enables SMS mode for N hours, where N is at most 48. * After N hours have elapsed, user will receive push notfications * - * If the push notification ID/token that should be suppressed during - * SMS mode is omitted, both SMS and push notifications - * will be delivered to the device. - * + * If the push notification ID/token that should be suppressed during + * SMS mode is omitted, both SMS and push notifications + * will be delivered to the device. + * * @param mixed $duration N hour duration * @param string $registration_id Push notification ID/token - * - * @return mixed + * + * @return mixed */ public function enableSmsMode($duration, $registration_id) { $payload = array( @@ -748,51 +775,51 @@ public function enableSmsMode($duration, $registration_id) { /** * Disables SMS mode - * + * * @return mixed */ public function disableSmsMode() { return $this->post('/users/sms_mode/delete'); } - + // CORE METHODS /** * Gets data from an endpoint - * + * * @param string $endpoint API endpoint * @param array $query Request - * + * * @return mixed */ private function get($endpoint, array $query=array()) { return $this->request('GET', $endpoint, $query); } - + /** * Posts data to an endpoint - * + * * @param string $endpoint API endpoint * @param array $payload Payload - * + * * @return mixed */ private function post($endpoint, array $payload=array()) { return $this->request('POST', $endpoint, array(), $payload); } - + /** * Sends a curl post/get request - * + * * @param string $method POST or GET method * @param string $endpoint Endpoint path * @param array $query Query * @param array $payload Payload * @param bool $img_svc_url Image upload? - * + * * @return mixed API result */ - private function request($method, $endpoint, array $query=array(), + private function request($method, $endpoint, array $query=array(), array $payload=array(), $img_svc_url=false) { if ($img_svc_url) { @@ -805,7 +832,7 @@ private function request($method, $endpoint, array $query=array(), } $query['access_token'] = $this->token; - + $url = $base_url . $endpoint . '?' . http_build_query($query); if ($this->isCached($url)) { @@ -821,12 +848,12 @@ private function request($method, $endpoint, array $query=array(), curl_setopt($ch, CURLOPT_USERAGENT, 'GroupMe API Client'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - + if ($method == 'POST') { $data = $img_svc_url ? $payload : json_encode($payload); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } - + $result = $this->cache($url, curl_exec($ch)); curl_close($ch); @@ -839,10 +866,10 @@ private function request($method, $endpoint, array $query=array(), /** * Enables or disable caching of CURL GET responses - * + * * @param bool $mode If TRUE, responses will be cached * @param int $timeout Timeout in seconds for cached content - * + * */ public function useResponseCaching($mode, $timeout = 300) { $this->useCache = $mode; @@ -852,29 +879,29 @@ public function useResponseCaching($mode, $timeout = 300) { /** * Checks if an item is in the cache and not * timed out - * + * * @param string $key Item key - * + * * @return bool Returns true, if item is cached */ private function isCached($key) { if (!$this->useCache) return FALSE; $idx = $this->getCacheIndex($key); if (isset($this->cache[$idx])) { - return ($this->cache[$idx]['timestamp'] + - $this->cacheTimeout > time()); + return ($this->cache[$idx]['timestamp'] + + $this->cacheTimeout > time()); } return FALSE; } /** * Creates an index string from a given key - * - * Cache items are indexed by a hash value + * + * Cache items are indexed by a hash value * generated from the key - * + * * @param string $key Item key, e.g. request url, ... - * + * * @return string Index string */ private function getCacheIndex($key) { @@ -883,9 +910,9 @@ private function getCacheIndex($key) { /** * Gets an item from the cache - * + * * @param string $key Item key - * + * * @return mixed */ private function getFromCache($key) { @@ -915,21 +942,21 @@ public function purgeCache() { } /** - * Puts data in the cache - * + * Puts data in the cache if caching is + * enabled + * * @param string $key Item key * @param mixed $data Item data - * + * * @return mixed Returns $data */ private function cache($key, $data) { if ($this->useCache) { - $this->cache[$this->getCacheIndex($key)] = + $this->cache[$this->getCacheIndex($key)] = array('timestamp' => time(), 'data' => $data); } return $data; } - -} +} \ No newline at end of file