diff --git a/EVENTS.txt b/EVENTS.txt index eb848bb888..4614ef3da5 100644 --- a/EVENTS.txt +++ b/EVENTS.txt @@ -1116,6 +1116,156 @@ EndGroupProfileElements: Start showing stuff about the group on its profile page - $action: action being executed (for output and params) - $group: group for the page +StartShowProfileTagContent: When showing a people tag page +- $action: action being executed (for output and params) + +EndShowProfileTagContent: After showing the contents of a people tag page +- $action: action being executed (for output and params) + +StartShowTaggedProfilesMiniList: at the start of mini list of tagged profiles +- $action: action being executed (for output and params) + +EndShowTaggedProfilesMiniList: at the end of mini list of tagged profiles +- $action: action being executed (for output and params) + +StartShowProfileTagSubscribersMiniList: at the start of mini list of people tag subscribers +- $action: action being executed (for output and params) + +EndShowProfileTagSubscribersMiniList: at the end of mini list of people tag subscribers +- $action: action being executed (for output and params) + +StartTagProfileAction: When starting to show profile tagging page +- $action: action being executed (for output and params) +- $profile: profile being tagged + +EndTagProfileAction: After showing profile tagging page +- $action: action being executed (for output and params) +- $profile: profile being tagged + +StartProfileCompletionSearch: When starting a profile search for autocompletion +- $action: action being executed (for output and params) +- &$profile: result Profile objects +- $search_engine: the search engine + +EndProfileCompletionSearch: After search results for profile autocompletion have been found +- $action: profilec completion action +- &$profile: current result Profile objects +- $search_engine: The search engine object + +StartShowTagProfileForm: When showing people tagging form +- $action: action being executed (for output and params) +- $profile: profile being tagged + +EndShowTagProfileForm: After showing people tagging form +- $action: action being executed (for output and params) +- $profile: profile being tagged + +StartSavePeopletags: When starting to save people tags +- $action: action being executed (for output and params) +- $tagstring: string input, a list of tags + +EndSavePeopletags: After saving people tags +- $action: action being executed (for output and params) +- $tagstring: string input, a list of tags + +StartProfiletagGetUri: when generating the Uri for a people tag +- $profile_list: the people tag, a Profile_list object +- &$uri: the URI + +EndProfiletagGetUri: after generating the uri for a people tag +- $profile_list: the people tag, a Profile_list object +- &$uri: the URI + +StartUserPeopletagHomeUrl: when generating the homepage url for a people tag +- $profile_list: the people tag, a Profile_list object +- &$url: the URL + +EndUserPeopletagHomeUrl: after generating the homepage url for a people tag +- $profile_list: the people tag, a Profile_list object +- &$url: the URL + +StartProfiletagPermalink: when generating the permalink url for a people tag +- $profile_list: the people tag, a Profile_list object +- &$url: the URL + +EndProfiletagPermalink: after generating the permalink url for a people tag +- $profile_list: the people tag, a Profile_list object +- &$url: the URL + +StartTagProfile: when tagging a profile +- $tagger: profile tagging +- $tagged: profile being tagged +- $tag: the tag + +EndTagProfile: after tagging a profile +- $newtag: the newly created Profile_tag object + +StartUntagProfile: when deleting a people tag +- $ptag: the Profile_tag object being deleted + +EndUntagProfile: after deleting a people tag +- $orig: a copy of the deleted Profile_tag object + +StartSubscribePeopletag: when subscribing to a people tag +- $peopletag: Profile_list object being subscribed to +- $profile: subscriber's profile + +EndSubscribePeopletag: after subscribing to a people tag +- $profile_list: the people tag, a Profile_list object: Profile_list object being subscribed to +- $profile: subscriber's profile + +StartUnsubscribePeopletag: when unsubscribing to a people tag +- $profile_list: the people tag, a Profile_list object: Profile_list object being subscribed to +- $profile: subscriber's profile + +EndUnsubscribePeopletag: after unsubscribing to a people tag +- $peopletag: Profile_list object being subscribed to +- $profile: subscriber's profile + +StartActivityObjectFromPeopletag: while starting to create an ActivityObject from a people tag +- $profile_list: the people tag, a Profile_list object +- &$object: activity object + +EndActivityObjectFromPeopletag: after making an ActivityObject from a people tag +- $profile_list: the people tag, a Profile_list object +- &$object: activity object + +StartPeopletagGroupNav: Showing the people tag nav menu +- $menu: the menu widget; use $menu->action for output + +EndPeopletagGroupNav: after showing the people tag nav menu +- $menu: the menu widget; use $menu->action for output + +StartShowPeopletagItem: when showing a people tag +- $widget: PeopletagListItem widget + +EndShowPeopletagItem: after showing a people tag +- $widget: PeopletagListItem widget + +StartSubscribePeopletagForm: when showing people tag subscription form +- $action: action being executed (for output and params) +- $peopletag: people tag being subscribed to + +EndSubscribePeopletagForm: after showing the people tag subscription form +- $action: action being executed (for output and params) +- $peopletag: people tag being subscribed to + +StartShowPeopletags: when showing a textual list of people tags +- $widget: PeopletagsWidget; use $widget->out for output +- $tagger: profile of the tagger +- $tagged: profile tagged + +EndShowPeopletags: after showing a textual list of people tags +- $widget: PeopletagsWidget; use $widget->out for output +- $tagger: profile of the tagger +- $tagged: profile tagged + +StartProfileListItemTags: when showing people tags in a profile list item widget +- $widget: ProfileListItem widget + +EndProfileListItemTags: after showing people tags in a profile list item widget +- $widget: ProfileListItem widget + StartActivityObjectOutputAtom: Called at start of Atom XML output generation for ActivityObject chunks, just inside the . Cancel the event to take over its output completely (you're responsible for calling the matching End event if so) - $obj: ActivityObject - $out: XMLOutputter to append custom output @@ -1160,7 +1310,7 @@ StartShowGroupProfileBlock: When showing the profile block for a group - $out: XMLOutputter to append custom output - $profile: the profile being shown -EndShowGroupProfileBlock: After showing showing the profile block for a group +EndShowGroupProfileBlock: After showing the profile block for a group - $out: XMLOutputter to append custom output - $group: the group being shown @@ -1183,3 +1333,4 @@ EndShowThreadedNoticeSub: when showing a reply to a notice - $nli: parent noticelistitem - $parent: parent notice - $child: child notice + diff --git a/actions/addpeopletag.php b/actions/addpeopletag.php new file mode 100644 index 0000000000..3176a116c9 --- /dev/null +++ b/actions/addpeopletag.php @@ -0,0 +1,172 @@ +. + * + * PHP version 5 + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/togglepeopletag.php'; + +/** + * + * Action to tag a profile with a single tag. + * + * Takes parameters: + * + * - tagged: the ID of the profile being tagged + * - token: session token to prevent CSRF attacks + * - ajax: boolean; whether to return Ajax or full-browser results + * - peopletag_id: the ID of the tag being used + * + * Only works if the current user is logged in. + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +class AddpeopletagAction extends Action +{ + var $user; + var $tagged; + var $peopletag; + + /** + * Check pre-requisites and instantiate attributes + * + * @param Array $args array of arguments (URL, GET, POST) + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + // Only for logged-in users + + $this->user = common_current_user(); + + if (empty($this->user)) { + $this->clientError(_('Not logged in.')); + return false; + } + + // Profile to subscribe to + + $tagged_id = $this->arg('tagged'); + + $this->tagged = Profile::staticGet('id', $tagged_id); + + if (empty($this->tagged)) { + $this->clientError(_('No such profile.')); + return false; + } + + $id = $this->arg('peopletag_id'); + $this->peopletag = Profile_list::staticGet('id', $id); + + if (empty($this->peopletag)) { + $this->clientError(_('No such peopletag.')); + return false; + } + + // OMB 0.1 doesn't have a mechanism for local-server- + // originated tag. + + $omb01 = Remote_profile::staticGet('id', $tagged_id); + + if (!empty($omb01)) { + $this->clientError(_('You cannot tag an OMB 0.1'. + ' remote profile with this action.')); + return false; + } + + return true; + } + + /** + * Handle request + * + * Does the tagging and returns results. + * + * @param Array $args unused. + * + * @return void + */ + + function handle($args) + { + + // Throws exception on error + $ptag = Profile_tag::setTag($this->user->id, $this->tagged->id, + $this->peopletag->tag); + + if (!$ptag) { + $user = User::staticGet('id', $id); + if ($user) { + $this->clientError( + sprintf(_('There was an unexpected error while tagging %s'), + $user->nickname)); + } else { + $this->clientError(sprintf(_('There was a problem tagging %s.' . + 'The remote server is probably not responding correctly, ' . + 'please try retrying later.'), $this->profile->profileurl)); + } + return false; + } + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, _('Subscribed')); + $this->elementEnd('head'); + $this->elementStart('body'); + $unsubscribe = new UntagButton($this, $this->tagged, $this->peopletag); + $unsubscribe->show(); + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + $url = common_local_url('subscriptions', + array('nickname' => $this->user->nickname)); + common_redirect($url, 303); + } + } +} diff --git a/actions/apilist.php b/actions/apilist.php new file mode 100644 index 0000000000..7a9ce70c5c --- /dev/null +++ b/actions/apilist.php @@ -0,0 +1,275 @@ +. + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apibareauth.php'; + +class ApiListAction extends ApiBareAuthAction +{ + /** + * The list in question in the current request + */ + + var $list = null; + + /** + * Is this an update request? + */ + + var $update = false; + + /** + * Is this a delete request? + */ + + var $delete = false; + + /** + * Set the flags for handling the request. Show list if this is a GET + * request, update it if it is POST, delete list if method is DELETE + * or if method is POST and an argument _method is set to DELETE. Act + * like we don't know if the current user has no access to the list. + * + * Takes parameters: + * - user: the user id or nickname + * - id: the id of the tag or the tag itself + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + $this->delete = ($_SERVER['REQUEST_METHOD'] == 'DELETE' || + ($this->trimmed('_method') == 'DELETE' && + $_SERVER['REQUEST_METHOD'] == 'POST')); + + // update list if method is POST or PUT and $this->delete is not true + $this->update = (!$this->delete && + in_array($_SERVER['REQUEST_METHOD'], array('POST', 'PUT'))); + + $this->user = $this->getTargetUser($this->arg('user')); + $this->list = $this->getTargetList($this->arg('user'), $this->arg('id')); + + if (empty($this->list)) { + $this->clientError(_('Not found'), 404, $this->format); + return false; + } + + return true; + } + + /** + * Handle the request + * + * @return boolean success flag + */ + + function handle($args) + { + parent::handle($args); + + if($this->delete) { + $this->handleDelete(); + return true; + } + + if($this->update) { + $this->handlePut(); + return true; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($this->list); + break; + case 'json': + $this->showSingleJsonList($this->list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } + + /** + * require authentication if it is a write action or user is ambiguous + * + */ + + function requiresAuth() + { + return parent::requiresAuth() || + $this->create || $this->delete; + } + + /** + * Update a list + * + * @return boolean success + */ + + function handlePut() + { + if($this->auth_user->id != $this->list->tagger) { + $this->clientError( + _('You can not update lists that don\'t belong to you.'), + 401, + $this->format + ); + } + + $new_list = clone($this->list); + $new_list->tag = common_canonical_tag($this->arg('name')); + $new_list->description = common_canonical_tag($this->arg('description')); + $new_list->private = ($this->arg('mode') === 'private') ? true : false; + + $result = $new_list->update($this->list); + + if(!$result) { + $this->clientError( + _('An error occured.'), + 503, + $this->format + ); + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($new_list); + break; + case 'json': + $this->showSingleJsonList($new_list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } + + /** + * Delete a list + * + * @return boolean success + */ + + function handleDelete() + { + if($this->auth_user->id != $this->list->tagger) { + $this->clientError( + _('You can not delete lists that don\'t belong to you.'), + 401, + $this->format + ); + } + + $record = clone($this->list); + $this->list->delete(); + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($record); + break; + case 'json': + $this->showSingleJsonList($record); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } + + /** + * Indicate that this resource is not read-only. + * + * @return boolean is_read-only=false + */ + + function isReadOnly($args) + { + return false; + } + + /** + * When was the list (people tag) last updated? + * + * @return String time_last_modified + */ + + function lastModified() + { + if(!empty($this->list)) { + return strtotime($this->list->modified); + } + return null; + } + + /** + * An entity tag for this list + * + * Returns an Etag based on the action name, language, user ID and + * timestamps of the first and last list the user has joined + * + * @return string etag + */ + + function etag() + { + if (!empty($this->list)) { + + return '"' . implode( + ':', + array($this->arg('action'), + common_language(), + $this->user->id, + strtotime($this->list->created), + strtotime($this->list->modified)) + ) + . '"'; + } + + return null; + } + +} diff --git a/actions/apilistmember.php b/actions/apilistmember.php new file mode 100644 index 0000000000..18d6ea370b --- /dev/null +++ b/actions/apilistmember.php @@ -0,0 +1,124 @@ +. + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apibareauth.php'; + +/** + * Action handler for Twitter list_memeber methods + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + * @see ApiBareAuthAction + */ + +class ApiListMemberAction extends ApiBareAuthAction +{ + /** + * Set the flags for handling the request. Show the profile if this + * is a GET request AND the profile is a member of the list, add a member + * if it is a POST, remove the profile from the list if method is DELETE + * or if method is POST and an argument _method is set to DELETE. Act + * like we don't know if the current user has no access to the list. + * + * Takes parameters: + * - user: the user id or nickname + * - list_id: the id of the tag or the tag itself + * - id: the id of the member being looked for/added/removed + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + $this->user = $this->getTargetUser($this->arg('id')); + $this->list = $this->getTargetList($this->arg('user'), $this->arg('list_id')); + + if (empty($this->list)) { + $this->clientError(_('Not found'), 404, $this->format); + return false; + } + + if (empty($this->user)) { + $this->clientError(_('No such user'), 404, $this->format); + return false; + } + return true; + } + + /** + * Handle the request + * + * @return boolean success flag + */ + + function handle($args) + { + parent::handle($args); + + $arr = array('tagger' => $this->list->tagger, + 'tag' => $this->list->tag, + 'tagged' => $this->user->id); + $ptag = Profile_tag::pkeyGet($arr); + + if(empty($ptag)) { + $this->clientError( + _('The specified user is not a member of this list'), + 400, + $this->format + ); + } + + $user = $this->twitterUserArray($this->user->getProfile(), true); + + switch($this->format) { + case 'xml': + $this->showTwitterXmlUser($user, 'user', true); + break; + case 'json': + $this->showSingleJsonUser($user); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + return true; + } +} diff --git a/actions/apilistmembers.php b/actions/apilistmembers.php new file mode 100644 index 0000000000..c6e92fa612 --- /dev/null +++ b/actions/apilistmembers.php @@ -0,0 +1,173 @@ +. + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apilistusers.php'; + +class ApiListMembersAction extends ApiListUsersAction +{ + /** + * Add a user to a list (tag someone) + * + * @return boolean success + */ + + function handlePost() + { + if($this->auth_user->id != $this->list->tagger) { + $this->clientError( + _('You aren\'t allowed to add members to this list'), + 401, + $this->format + ); + return false; + } + + if($this->user === false) { + $this->clientError( + _('You must specify a member'), + 400, + $this->format + ); + return false; + } + + $result = Profile_tag::setTag($this->auth_user->id, + $this->user->id, $this->list->tag); + + if(empty($result)) { + $this->clientError( + _('An error occured.'), + 500, + $this->format + ); + return false; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($this->list); + break; + case 'json': + $this->showSingleJsonList($this->list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + return false; + break; + } + } + + /** + * Remove a user from a list (untag someone) + * + * @return boolean success + */ + + function handleDelete() + { + if($this->auth_user->id != $this->list->tagger) { + $this->clientError( + _('You aren\'t allowed to remove members from this list'), + 401, + $this->format + ); + return false; + } + + if($this->user === false) { + $this->clientError( + _('You must specify a member'), + 400, + $this->format + ); + return false; + } + + $args = array('tagger' => $this->auth_user->id, + 'tagged' => $this->user->id, + 'tag' => $this->list->tag); + $ptag = Profile_tag::pkeyGet($args); + + if(empty($ptag)) { + $this->clientError( + _('The user you are trying to remove from the list is not a member'), + 400, + $this->format + ); + return false; + } + + $result = $ptag->delete(); + + if(empty($result)) { + $this->clientError( + _('An error occured.'), + 500, + $this->format + ); + return false; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($this->list); + break; + case 'json': + $this->showSingleJsonList($this->list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + return false; + break; + } + return true; + } + + /** + * List the members of a list (people tagged) + */ + + function getUsers() + { + $fn = array($this->list, 'getTagged'); + list($this->users, $this->next_cursor, $this->prev_cursor) = + Profile_list::getAtCursor($fn, array(), $this->cursor, 20); + } +} diff --git a/actions/apilistmemberships.php b/actions/apilistmemberships.php new file mode 100644 index 0000000000..635f970e87 --- /dev/null +++ b/actions/apilistmemberships.php @@ -0,0 +1,136 @@ +. + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apibareauth.php'; + +/** + * Action handler for API method to list lists a user belongs to. + * (people tags for a user) + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + * @see ApiBareAuthAction + */ + +class ApiListMembershipsAction extends ApiBareAuthAction +{ + var $lists = array(); + var $cursor = -1; + var $next_cursor = 0; + var $prev_cursor = 0; + + /** + * Prepare for running the action + * Take arguments for running:s + * + * @param array $args $_REQUEST args + * + * @return boolean success flag + * + */ + + function prepare($args) + { + parent::prepare($args); + + $this->cursor = (int) $this->arg('cursor', -1); + $this->user = $this->getTargetUser($this->arg('user')); + + if (empty($this->user)) { + $this->clientError(_('No such user.'), 404, $this->format); + return; + } + + $this->getLists(); + + return true; + } + + /** + * Handle the request + * + * Show the lists + * + * @param array $args $_REQUEST data (unused) + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + switch($this->format) { + case 'xml': + $this->showXmlLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + case 'json': + $this->showJsonLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + default: + $this->clientError( + _('API method not found.'), + 400, + $this->format + ); + break; + } + } + + /** + * Return true if read only. + * + * MAY override + * + * @param array $args other arguments + * + * @return boolean is read only action? + */ + + function isReadOnly($args) + { + return true; + } + + function getLists() + { + $profile = $this->user->getProfile(); + $fn = array($profile, 'getOtherTags'); + + # 20 lists + list($this->lists, $this->next_cursor, $this->prev_cursor) = + Profile_list::getAtCursor($fn, array($this->auth_user), $this->cursor, 20); + } +} diff --git a/actions/apilists.php b/actions/apilists.php new file mode 100644 index 0000000000..f520e32972 --- /dev/null +++ b/actions/apilists.php @@ -0,0 +1,244 @@ +. + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apibareauth.php'; + +/** + * Action handler for Twitter list_memeber methods + * + * @category API + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + * @see ApiBareAuthAction + */ + +class ApiListsAction extends ApiBareAuthAction +{ + var $lists = null; + var $cursor = 0; + var $next_cursor = 0; + var $prev_cursor = 0; + var $create = false; + + /** + * Set the flags for handling the request. List lists created by user if this + * is a GET request, create a new list if it is a POST request. + * + * Takes parameters: + * - user: the user id or nickname + * Parameters for POST request + * - name: name of the new list (the people tag itself) + * - mode: (optional) mode for the new list private/public + * - description: (optional) description for the list + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + $this->create = ($_SERVER['REQUEST_METHOD'] == 'POST'); + + if (!$this->create) { + + $this->user = $this->getTargetUser($this->arg('user')); + + if (empty($this->user)) { + $this->clientError(_('No such user.'), 404, $this->format); + return false; + } + $this->getLists(); + } + + return true; + } + + /** + * require authentication if it is a write action or user is ambiguous + * + */ + + function requiresAuth() + { + return parent::requiresAuth() || + $this->create || $this->delete; + } + + /** + * Handle request: + * Show the lists the user has created if the request method is GET + * Create a new list by diferring to handlePost() if it is POST. + */ + + function handle($args) + { + parent::handle($args); + + if($this->create) { + return $this->handlePost(); + } + + switch($this->format) { + case 'xml': + $this->showXmlLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + case 'json': + $this->showJsonLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } + + /** + * Create a new list + * + * @return boolean success + */ + + function handlePost() + { + $name=$this->arg('name'); + if(empty($name)) { + // mimick twitter + print _("A list's name can't be blank."); + exit(1); + } + + // twitter creates a new list by appending a number to the end + // if the list by the given name already exists + // it makes more sense to return the existing list instead + + $private = null; + if ($this->arg('mode') === 'public') { + $private = false; + } else if ($this->arg('mode') === 'private') { + $private = true; + } + + $list = Profile_list::ensureTag($this->auth_user->id, + $this->arg('name'), + $this->arg('description'), + $private); + if (empty($list)) { + return false; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($list); + break; + case 'json': + $this->showSingleJsonList($list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + return true; + } + + /** + * Get lists + */ + + function getLists() + { + $cursor = (int) $this->arg('cursor', -1); + + // twitter fixes count at 20 + // there is no argument named count + $count = 20; + $profile = $this->user->getProfile(); + $fn = array($profile, 'getOwnedTags'); + + list($this->lists, + $this->next_cursor, + $this->prev_cursor) = Profile_list::getAtCursor($fn, array($this->auth_user), $cursor, $count); + } + + function isReadOnly($args) + { + return false; + } + + function lastModified() + { + if (!$this->create && !empty($this->lists) && (count($this->lists) > 0)) { + return strtotime($this->lists[0]->created); + } + + return null; + } + + /** + * An entity tag for this list of lists + * + * Returns an Etag based on the action name, language, user ID and + * timestamps of the first and last list the user has joined + * + * @return string etag + */ + + function etag() + { + if (!$this->create && !empty($this->lists) && (count($this->lists) > 0)) { + + $last = count($this->lists) - 1; + + return '"' . implode( + ':', + array($this->arg('action'), + common_language(), + $this->user->id, + strtotime($this->lists[0]->created), + strtotime($this->lists[$last]->created)) + ) + . '"'; + } + + return null; + } + +} diff --git a/actions/apilistsubscriber.php b/actions/apilistsubscriber.php new file mode 100644 index 0000000000..d6816b9b91 --- /dev/null +++ b/actions/apilistsubscriber.php @@ -0,0 +1,91 @@ +. + * + * @category API + * @package StatusNet + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apiauth.php'; + +class ApiListSubscriberAction extends ApiBareAuthAction +{ + var $list = null; + + function prepare($args) + { + parent::prepare($args); + + $this->user = $this->getTargetUser($this->arg('id')); + $this->list = $this->getTargetList($this->arg('user'), $this->arg('list_id')); + + if (empty($this->list)) { + $this->clientError(_('Not found'), 404, $this->format); + return false; + } + + if (empty($this->user)) { + $this->clientError(_('No such user'), 404, $this->format); + return false; + } + return true; + } + + function handle($args) + { + parent::handle($args); + + $arr = array('profile_tag_id' => $this->list->id, + 'profile_id' => $this->user->id); + $sub = Profile_tag_subscription::pkeyGet($arr); + + if(empty($sub)) { + $this->clientError( + _('The specified user is not a subscriber of this list'), + 400, + $this->format + ); + } + + $user = $this->twitterUserArray($this->user->getProfile(), true); + + switch($this->format) { + case 'xml': + $this->showTwitterXmlUser($user, 'user', true); + break; + case 'json': + $this->showSingleJsonUser($user); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } +} diff --git a/actions/apilistsubscribers.php b/actions/apilistsubscribers.php new file mode 100644 index 0000000000..e8468a195d --- /dev/null +++ b/actions/apilistsubscribers.php @@ -0,0 +1,125 @@ +. + * + * @category API + * @package StatusNet + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apilistusers.php'; + +class ApiListSubscribersAction extends ApiListUsersAction +{ + /** + * Subscribe to list + * + * @return boolean success + */ + + function handlePost() + { + $result = Profile_tag_subscription::add($this->list, + $this->auth_user); + + if(empty($result)) { + $this->clientError( + _('An error occured.'), + 500, + $this->format + ); + return false; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($this->list); + break; + case 'json': + $this->showSingleJsonList($this->list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + return false; + break; + } + } + + function handleDelete() + { + $args = array('profile_tag_id' => $this->list->id, + 'profile_id' => $this->auth_user->id); + $ptag = Profile_tag_subscription::pkeyGet($args); + + if(empty($ptag)) { + $this->clientError( + _('You are not subscribed to this list'), + 400, + $this->format + ); + return false; + } + + Profile_tag_subscription::remove($this->list, $this->auth_user); + + if(empty($result)) { + $this->clientError( + _('An error occured.'), + 500, + $this->format + ); + return false; + } + + switch($this->format) { + case 'xml': + $this->showSingleXmlList($this->list); + break; + case 'json': + $this->showSingleJsonList($this->list); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + return false; + break; + } + return true; + } + + function getUsers() + { + $fn = array($this->list, 'getSubscribers'); + list($this->users, $this->next_cursor, $this->prev_cursor) = + Profile_list::getAtCursor($fn, array(), $this->cursor, 20); + } +} diff --git a/actions/apilistsubscriptions.php b/actions/apilistsubscriptions.php new file mode 100644 index 0000000000..764360e149 --- /dev/null +++ b/actions/apilistsubscriptions.php @@ -0,0 +1,126 @@ +. + * + * @category API + * @package StatusNet + * @copyright 2009 StatusNet, Inc. + * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apibareauth.php'; + +class ApiListSubscriptionsAction extends ApiBareAuthAction +{ + var $lists = array(); + var $cursor = -1; + var $next_cursor = 0; + var $prev_cursor = 0; + + /** + * Take arguments for running + * + * @param array $args $_REQUEST args + * + * @return boolean success flag + * + */ + + function prepare($args) + { + parent::prepare($args); + + $this->cursor = (int) $this->arg('cursor', -1); + $this->user = $this->getTargetUser($this->arg('user')); + $this->getLists(); + + return true; + } + + /** + * Handle the request + * + * Show the lists + * + * @param array $args $_REQUEST data (unused) + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + if (empty($this->user)) { + $this->clientError(_('No such user.'), 404, $this->format); + return; + } + + switch($this->format) { + case 'xml': + $this->showXmlLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + case 'json': + $this->showJsonLists($this->lists, $this->next_cursor, $this->prev_cursor); + break; + default: + $this->clientError( + _('API method not found.'), + 400, + $this->format + ); + break; + } + } + + /** + * Return true if read only. + * + * MAY override + * + * @param array $args other arguments + * + * @return boolean is read only action? + */ + + function isReadOnly($args) + { + return true; + } + + function getLists() + { + if(empty($this->user)) { + return; + } + + $profile = $this->user->getProfile(); + $fn = array($profile, 'getTagSubscriptions'); + # 20 lists + list($this->lists, $this->next_cursor, $this->prev_cursor) = + Profile_list::getAtCursor($fn, array(), $this->cursor, 20); + } +} diff --git a/actions/apitimelinelist.php b/actions/apitimelinelist.php new file mode 100644 index 0000000000..f28eb59d53 --- /dev/null +++ b/actions/apitimelinelist.php @@ -0,0 +1,266 @@ +. + * + * @category API + * @package StatusNet + * @author Craig Andrews + * @author Evan Prodromou + * @author Jeffery To + * @author Zach Copley + * @copyright 2009 StatusNet, Inc. + * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/apiprivateauth.php'; +require_once INSTALLDIR . '/lib/atomlistnoticefeed.php'; + +/** + * Returns the most recent notices (default 20) posted to the list specified by ID + * + * @category API + * @package StatusNet + * @author Craig Andrews + * @author Evan Prodromou + * @author Jeffery To + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class ApiTimelineListAction extends ApiPrivateAuthAction +{ + + var $list = null; + var $notices = array(); + var $next_cursor = 0; + var $prev_cursor = 0; + var $cursor = -1; + + /** + * Take arguments for running + * + * @param array $args $_REQUEST args + * + * @return boolean success flag + * + */ + + function prepare($args) + { + parent::prepare($args); + + $this->cursor = (int) $this->arg('cursor', -1); + $this->list = $this->getTargetList($this->arg('user'), $this->arg('id')); + + return true; + } + + /** + * Handle the request + * + * Just show the notices + * + * @param array $args $_REQUEST data (unused) + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + if (empty($this->list)) { + $this->clientError(_('List not found.'), 404, $this->format); + return false; + } + + $this->getNotices(); + $this->showTimeline(); + } + + /** + * Show the timeline of notices + * + * @return void + */ + + function showTimeline() + { + // We'll pull common formatting out of this for other formats + $atom = new AtomListNoticeFeed($this->list, $this->auth_user); + + $self = $this->getSelfUri(); + + switch($this->format) { + case 'xml': + $this->initDocument('xml'); + $this->elementStart('statuses_list', + array('xmlns:statusnet' => 'http://status.net/schema/api/1/')); + $this->elementStart('statuses', array('type' => 'array')); + + foreach ($this->notices as $n) { + $twitter_status = $this->twitterStatusArray($n); + $this->showTwitterXmlStatus($twitter_status); + } + + $this->elementEnd('statuses'); + $this->element('next_cursor', null, $this->next_cursor); + $this->element('previous_cursor', null, $this->prev_cursor); + $this->elementEnd('statuses_list'); + $this->endDocument('xml'); + break; + case 'rss': + $this->showRssTimeline( + $this->notices, + $atom->title, + $this->list->getUri(), + $atom->subtitle, + null, + $atom->logo, + $self + ); + break; + case 'atom': + + header('Content-Type: application/atom+xml; charset=utf-8'); + + try { + $atom->setId($self); + $atom->setSelfLink($self); + $atom->addEntryFromNotices($this->notices); + $this->raw($atom->getString()); + } catch (Atom10FeedException $e) { + $this->serverError( + 'Could not generate feed for list - ' . $e->getMessage() + ); + return; + } + + break; + case 'json': + $this->initDocument('json'); + + $statuses = array(); + foreach ($this->notices as $n) { + $twitter_status = $this->twitterStatusArray($n); + array_push($statuses, $twitter_status); + } + + $statuses_list = array('statuses' => $statuses, + 'next_cursor' => $this->next_cusror, + 'next_cursor_str' => strval($this->next_cusror), + 'previous_cursor' => $this->prev_cusror, + 'previous_cursor_str' => strval($this->prev_cusror) + ); + $this->showJsonObjects($statuses_list); + + $this->initDocument('json'); + break; + default: + $this->clientError( + _('API method not found.'), + 404, + $this->format + ); + break; + } + } + + /** + * Get notices + * + * @return array notices + */ + + function getNotices() + { + $fn = array($this->list, 'getNotices'); + list($this->notices, $this->next_cursor, $this->prev_cursor) = + Profile_list::getAtCursor($fn, array(), $this->cursor, 20); + if (!$this->notices) { + $this->notices = array(); + } + } + + /** + * Is this action read only? + * + * @param array $args other arguments + * + * @return boolean true + */ + + function isReadOnly($args) + { + return true; + } + + /** + * When was this feed last modified? + * + * @return string datestamp of the latest notice in the stream + */ + + function lastModified() + { + if (!empty($this->notices) && (count($this->notices) > 0)) { + return strtotime($this->notices[0]->created); + } + + return null; + } + + /** + * An entity tag for this stream + * + * Returns an Etag based on the action name, language, list ID and + * timestamps of the first and last notice in the timeline + * + * @return string etag + */ + + function etag() + { + if (!empty($this->notices) && (count($this->notices) > 0)) { + + $last = count($this->notices) - 1; + + return '"' . implode( + ':', + array($this->arg('action'), + common_language(), + $this->list->id, + strtotime($this->notices[0]->created), + strtotime($this->notices[$last]->created)) + ) + . '"'; + } + + return null; + } + +} diff --git a/actions/editpeopletag.php b/actions/editpeopletag.php new file mode 100644 index 0000000000..2bb03470d9 --- /dev/null +++ b/actions/editpeopletag.php @@ -0,0 +1,311 @@ +. + * + * @category Group + * @package StatusNet + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +/** + * Add a new group + * + * This is the form for adding a new group + * + * @category Group + * @package StatusNet + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class EditpeopletagAction extends OwnerDesignAction +{ + + var $msg, $confirm, $confirm_args=array(); + + function title() + { + if ($_SERVER['REQUEST_METHOD'] == 'POST' && $this->boolean('delete')) { + return sprintf(_('Delete %s people tag'), $this->peopletag->tag); + } + return sprintf(_('Edit people tag %s'), $this->peopletag->tag); + } + + /** + * Prepare to run + */ + + function prepare($args) + { + parent::prepare($args); + + if (!common_logged_in()) { + $this->clientError(_('Not logged in.')); + return false; + } + + $id = $this->arg('id'); + $tagger_arg = $this->arg('tagger'); + $tag_arg = $this->arg('tag'); + + $tagger = common_canonical_nickname($tagger_arg); + $tag = common_canonical_tag($tag_arg); + + $current = common_current_user(); + + // Permanent redirect on non-canonical tag + + if ($tagger_arg != $tagger || $tag_arg != $tag) { + $args = array('tagger' => $tagger, 'tag' => $tag); + common_redirect(common_local_url('editpeopletag', $args), 301); + return false; + } + + $user = null; + if ($id) { + $this->peopletag = Profile_list::staticGet('id', $id); + if (!empty($this->peopletag)) { + $user = User::staticGet('id', $this->peopletag->tagger); + } + } else { + if (!$tagger) { + $this->clientError(_('No tagger or ID.'), 404); + return false; + } + + $user = User::staticGet('nickname', $tagger); + $this->peopletag = Profile_list::pkeyGet(array('tagger' => $user->id, 'tag' => $tag)); + } + + if (!$this->peopletag) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + if (!$user) { + // This should not be happening + $this->clientError(_('Not a local user.'), 404); + return false; + } + + if ($current->id != $user->id) { + $this->clientError(_('You must be the creator of the tag to edit it.'), 404); + return false; + } + + $this->tagger = $user->getProfile(); + + return true; + } + + /** + * Handle the request + * + * On GET, show the form. On POST, try to save the group. + * + * @param array $args unused + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->trySave(); + } else { + $this->showForm(); + } + } + + function showConfirm($msg=null, $fwd=null) + { + $this->confirm = $msg; + $this->confirm_args = $fwd; + $this->showPage(); + } + + function showConfirmForm() + { + $this->elementStart('form', array('id' => 'form_peopletag_edit_confirm', + 'class' => 'form_settings', + 'method' => 'post', + 'action' => common_local_url('editpeopletag', + array('tagger' => $this->tagger->nickname, + 'tag' => $this->peopletag->tag)))); + $this->elementStart('fieldset'); + $this->hidden('token', common_session_token()); + $this->hidden('id', $this->arg('id')); + + foreach ($this->confirm_args as $key => $val) { + $this->hidden($key, $val); + } + + $this->submit('form_action-no', + _m('BUTTON','No'), + 'submit form_action-primary', + 'cancel'); + $this->submit('form_action-yes', + _m('BUTTON','Yes'), + 'submit form_action-secondary', + 'confirm'); + $this->elementEnd('fieldset'); + $this->elementEnd('form'); + } + + function showForm($msg=null) + { + $this->msg = $msg; + $this->showPage(); + } + + function showObjectNav() + { + $nav = new PeopletagGroupNav($this, $this->peopletag); + $nav->show(); + } + + function showContent() + { + if ($this->confirm) { + $this->showConfirmForm(); + return; + } + + $form = new PeopletagEditForm($this, $this->peopletag); + $form->show(); + + $form->showProfileList(); + } + + function showPageNotice() + { + if ($this->msg) { + $this->element('p', 'error', $this->msg); + } else if ($this->confirm) { + $this->element('p', 'instructions', $this->confirm); + } else { + $this->element('p', 'instructions', + _('Use this form to edit the people tag.')); + } + } + + function showScripts() + { + parent::showScripts(); + $this->autofocus('tag'); + } + + function trySave() + { + $tag = common_canonical_tag($this->trimmed('tag')); + $description = $this->trimmed('description'); + $private = $this->boolean('private'); + $delete = $this->arg('delete'); + $confirm = $this->arg('confirm'); + $cancel = $this->arg('cancel'); + + if ($delete && $cancel) { + $this->showForm(_('Delete aborted.')); + return; + } + + $set_private = $private && $this->peopletag->private != $private; + + if ($delete && !$confirm) { + $this->showConfirm(_('Deleting this tag will permanantly remove ' . + 'all its subscription and membership records. ' . + 'Do you still want to continue?'), array('delete' => 1)); + return; + } else if (common_valid_tag($tag)) { + $this->showForm(_('Invalid tag.')); + return; + } else if ($tag != $this->peopletag->tag && $this->tagExists($tag)) { + $this->showForm(sprintf(_('You already have a tag named %s.'), $tag)); + return; + } else if (Profile_list::descriptionTooLong($description)) { + $this->showForm(sprintf(_('description is too long (max %d chars).'), Profile_list::maxDescription())); + return; + } else if ($set_private && !$confirm && !$cancel) { + $fwd = array('tag' => $tag, + 'description' => $description, + 'private' => (int) $private); + + $this->showConfirm(_('Setting a public tag as private will ' . + 'permanently remove all the existing ' . + 'subscriptions to it. Do you still want to continue?'), $fwd); + return; + } + + $this->peopletag->query('BEGIN'); + + $orig = clone($this->peopletag); + + $this->peopletag->tag = $tag; + $this->peopletag->description = $description; + if (!$set_private || $confirm) { + $this->peopletag->private = $private; + } + + $result = $this->peopletag->update($orig); + + if (!$result) { + common_log_db_error($this->group, 'UPDATE', __FILE__); + $this->serverError(_('Could not update peopletag.')); + } + + $this->peopletag->query('COMMIT'); + + if ($set_private && $confirm) { + Profile_tag_subscription::cleanup($this->peopletag); + } + + if ($delete) { + // This might take quite a bit of time. + $this->peopletag->delete(); + // send home. + common_redirect(common_local_url('all', + array('nickname' => $this->tagger->nickname)), + 303); + } + + if ($tag != $orig->tag) { + common_redirect(common_local_url('editpeopletag', + array('tagger' => $this->tagger->nickname, + 'tag' => $tag)), + 303); + } else { + $this->showForm(_('Options saved.')); + } + } + + function tagExists($tag) + { + $args = array('tagger' => $this->tagger->id, 'tag' => $tag); + $ptag = Profile_list::pkeyGet($args); + + return !empty($ptag); + } +} diff --git a/actions/peopletag.php b/actions/peopletag.php index 2adc24ea66..d549586f13 100644 --- a/actions/peopletag.php +++ b/actions/peopletag.php @@ -2,7 +2,7 @@ /** * StatusNet, the distributed open-source microblogging tool * - * Action for showing profiles self-tagged with a given tag + * People tags by a user * * PHP version 5 * @@ -16,13 +16,16 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * + * PHP version 5 + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * - * @category Action + * @category Personal * @package StatusNet * @author Evan Prodromou * @author Zach Copley + * @author Shashi Gowda * @copyright 2009 StatusNet, Inc. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @link http://status.net/ @@ -32,150 +35,125 @@ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } -/** - * This class outputs a paginated list of profiles self-tagged with a given tag - * - * @category Output - * @package StatusNet - * @author Evan Prodromou - * @author Zach Copley - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 - * @link http://status.net/ - * - * @see Action - */ +require_once INSTALLDIR.'/lib/peopletaglist.php'; +// cache 3 pages +define('PEOPLETAG_CACHE_WINDOW', PEOPLETAGS_PER_PAGE*3 + 1); + class PeopletagAction extends Action { - - var $tag = null; var $page = null; + var $tag = null; - /** - * For initializing members of the class. - * - * @param array $argarray misc. arguments - * - * @return boolean true - */ - function prepare($argarray) + function isReadOnly($args) { - parent::prepare($argarray); + return true; + } - $this->tag = $this->trimmed('tag'); - - if (!common_valid_profile_tag($this->tag)) { - // TRANS: Client error displayed when trying to tag a profile with an invalid tag. - // TRANS: %s is the invalid tag. - $this->clientError(sprintf(_('Not a valid people tag: %s.'), - $this->tag)); - return; + function title() + { + if ($this->page == 1) { + return sprintf(_("Public people tag %s"), $this->tag); + } else { + return sprintf(_("Public people tag %s, page %d"), $this->tag, $this->page); } + } - $this->page = ($this->arg('page')) ? $this->arg('page') : 1; + function prepare($args) + { + parent::prepare($args); + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - common_set_returnto($this->selfUrl()); + $tag_arg = $this->arg('tag'); + $tag = common_canonical_tag($tag_arg); + + // Permanent redirect on non-canonical nickname + + if ($tag_arg != $tag) { + $args = array('tag' => $nickname); + if ($this->page && $this->page != 1) { + $args['page'] = $this->page; + } + common_redirect(common_local_url('peopletag', $args), 301); + return false; + } + $this->tag = $tag; return true; } - /** - * Handler method - * - * @param array $argarray is ignored since it's now passed in in prepare() - * - * @return boolean is read only action? - */ - function handle($argarray) + function handle($args) { - parent::handle($argarray); + parent::handle($args); $this->showPage(); } - /** - * Whips up a query to get a list of profiles based on the provided - * people tag and page, initalizes a ProfileList widget, and displays - * it to the user. - * - * @return nothing - */ + function showLocalNav() + { + $nav = new PublicGroupNav($this); + $nav->show(); + } + + function showAnonymousMessage() + { + $notice = + _('People tags are how you sort similar ' . + 'people on %%site.name%%, a [micro-blogging]' . + '(http://en.wikipedia.org/wiki/Micro-blogging) service ' . + 'based on the Free Software [StatusNet](http://status.net/) tool. ' . + 'You can then easily keep track of what they ' . + 'are doing by subscribing to the tag\'s timeline.' ); + $this->elementStart('div', array('id' => 'anon_notice')); + $this->raw(common_markup_to_html($notice)); + $this->elementEnd('div'); + } + function showContent() { + $offset = ($this->page-1) * PEOPLETAGS_PER_PAGE; + $limit = PEOPLETAGS_PER_PAGE + 1; - $profile = new Profile(); + $ptags = new Profile_list(); + $ptags->tag = $this->tag; - $offset = ($this->page - 1) * PROFILES_PER_PAGE; - $limit = PROFILES_PER_PAGE + 1; + $user = common_current_user(); - if (common_config('db', 'type') == 'pgsql') { - $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; + if (empty($user)) { + $ckey = sprintf('profile_list:tag:%s', $this->tag); + $ptags->private = false; + $ptags->orderBy('profile_list.modified DESC'); + + $c = Cache::instance(); + if ($offset+$limit <= PEOPLETAG_CACHE_WINDOW && !empty($c)) { + $cached_ptags = Profile_list::getCached($ckey, $offset, $limit); + if ($cached_ptags === false) { + $ptags->limit(0, PEOPLETAG_CACHE_WINDOW); + $ptags->find(); + + Profile_list::setCache($ckey, $ptags, $offset, $limit); + } else { + $ptags = clone($cached_ptags); + } + } else { + $ptags->limit($offset, $limit); + $ptags->find(); + } } else { - $lim = ' LIMIT ' . $offset . ', ' . $limit; + $ptags->whereAdd('(profile_list.private = false OR (' . + ' profile_list.tagger =' . $user->id . + ' AND profile_list.private = true) )'); + + $ptags->orderBy('profile_list.modified DESC'); + $ptags->find(); } - // XXX: memcached this + $pl = new PeopletagList($ptags, $this); + $cnt = $pl->show(); - $qry = 'SELECT profile.* ' . - 'FROM profile JOIN profile_tag ' . - 'ON profile.id = profile_tag.tagger ' . - 'WHERE profile_tag.tagger = profile_tag.tagged ' . - "AND tag = '%s' " . - 'ORDER BY profile_tag.modified DESC%s'; - - $profile->query(sprintf($qry, $this->tag, $lim)); - - $ptl = new PeopleTagList($profile, $this); // pass the ammunition - $cnt = $ptl->show(); - - $this->pagination($this->page > 1, - $cnt > PROFILES_PER_PAGE, - $this->page, - 'peopletag', - array('tag' => $this->tag)); + $this->pagination($this->page > 1, $cnt > PEOPLETAGS_PER_PAGE, + $this->page, 'peopletag', array('tag' => $this->tag)); } - /** - * Returns the page title - * - * @return string page title - */ - function title() + function showSections() { - // TRANS: Page title for users with a certain self-tag. - // TRANS: %1$s is the tag, %2$s is the page number. - return sprintf(_('Users self-tagged with %1$s - page %2$d'), - $this->tag, $this->page); - } -} - -class PeopleTagList extends ProfileList -{ - function newListItem($profile) - { - return new PeopleTagListItem($profile, $this->action); - } -} - -class PeopleTagListItem extends ProfileListItem -{ - function linkAttributes() - { - $aAttrs = parent::linkAttributes(); - - if (common_config('nofollow', 'peopletag')) { - $aAttrs['rel'] .= ' nofollow'; - } - - return $aAttrs; - } - - function homepageAttributes() - { - $aAttrs = parent::linkAttributes(); - - if (common_config('nofollow', 'peopletag')) { - $aAttrs['rel'] = 'nofollow'; - } - - return $aAttrs; } } diff --git a/actions/peopletagautocomplete.php b/actions/peopletagautocomplete.php new file mode 100644 index 0000000000..04b9baefbe --- /dev/null +++ b/actions/peopletagautocomplete.php @@ -0,0 +1,127 @@ +. + * + * PHP version 5 + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +class PeopletagautocompleteAction extends Action +{ + var $user; + var $tags; + var $last_mod; + + /** + * Check pre-requisites and instantiate attributes + * + * @param Array $args array of arguments (URL, GET, POST) + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + // Only for logged-in users + + $this->user = common_current_user(); + + if (empty($this->user)) { + $this->clientError(_('Not logged in.')); + return false; + } + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + $profile = $this->user->getProfile(); + $tags = $profile->getOwnedTags(common_current_user()); + + $this->tags = array(); + while ($tags->fetch()) { + + if (empty($this->last_mod)) { + $this->last_mod = $tags->modified; + } + + $arr = array(); + $arr['tag'] = $tags->tag; + $arr['mode'] = $tags->private ? 'private' : 'public'; + // $arr['url'] = $tags->homeUrl(); + $arr['freq'] = $tags->taggedCount(); + + $this->tags[] = $arr; + } + + $tags->free(); + + return true; + } + + /** + * Last modified time + * + * Helps in browser-caching + * + * @return String time + */ + + function lastModified() + { + return strtotime($this->last_mod); + } + + /** + * Handle request + * + * Print the JSON autocomplete data + * + * @param Array $args unused. + * + * @return void + */ + + function handle($args) + { + //common_log(LOG_DEBUG, 'Autocomplete data: ' . json_encode($this->tags)); + if ($this->tags) { + print(json_encode($this->tags)); + exit(0); + } + return false; + } +} diff --git a/actions/peopletagged.php b/actions/peopletagged.php new file mode 100644 index 0000000000..5038d1e213 --- /dev/null +++ b/actions/peopletagged.php @@ -0,0 +1,223 @@ +. + * + * @category Group + * @package StatusNet + * @author Shashi Gowda + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once(INSTALLDIR.'/lib/profilelist.php'); + +/** + * List of people tagged by the user with a tag + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class PeopletaggedAction extends OwnerDesignAction +{ + var $page = null; + var $peopletag = null; + var $tagger = null; + + function isReadOnly($args) + { + return true; + } + + function prepare($args) + { + parent::prepare($args); + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + $tagger_arg = $this->arg('tagger'); + $tag_arg = $this->arg('tag'); + $tagger = common_canonical_nickname($tagger_arg); + $tag = common_canonical_tag($tag_arg); + + // Permanent redirect on non-canonical nickname + + if ($tagger_arg != $tagger || $tag_arg != $tag) { + $args = array('tagger' => $nickname, 'tag' => $tag); + if ($this->page != 1) { + $args['page'] = $this->page; + } + common_redirect(common_local_url('peopletagged', $args), 301); + return false; + } + + if (!$tagger) { + $this->clientError(_('No tagger.'), 404); + return false; + } + + $user = User::staticGet('nickname', $tagger); + + if (!$user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->tagger = $user->getProfile(); + $this->peopletag = Profile_list::pkeyGet(array('tagger' => $user->id, 'tag' => $tag)); + + if (!$this->peopletag) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + return true; + } + + function title() + { + if ($this->page == 1) { + return sprintf(_('People tagged %s by %s'), + $this->peopletag->tag, $this->tagger->nickname); + } else { + return sprintf(_('People tagged %s by %s, page %d'), + $this->peopletag->tag, $this->user->nickname, + $this->page); + } + } + + function handle($args) + { + parent::handle($args); + $this->showPage(); + } + + function showPageNotice() + { + } + + function showLocalNav() + { + $nav = new PeopletagGroupNav($this, $this->peopletag); + $nav->show(); + } + + function showContent() + { + $offset = ($this->page-1) * PROFILES_PER_PAGE; + $limit = PROFILES_PER_PAGE + 1; + + $cnt = 0; + + $subs = $this->peopletag->getTagged($offset, $limit); + + if ($subs) { + $subscriber_list = new PeopletagMemberList($subs, $this->peopletag, $this); + $cnt = $subscriber_list->show(); + } + + $subs->free(); + + $this->pagination($this->page > 1, $cnt > PROFILES_PER_PAGE, + $this->page, 'peopletagged', + array('tagger' => $this->tagger->nickname, + 'tag' => $this->peopletag->tag)); + } +} + +class PeopletagMemberList extends ProfileList +{ + var $peopletag = null; + + function __construct($profile, $peopletag, $action) + { + parent::__construct($profile, $action); + + $this->peopletag = $peopletag; + } + + function newListItem($profile) + { + return new PeopletagMemberListItem($profile, $this->peopletag, $this->action); + } +} + +class PeopletagMemberListItem extends ProfileListItem +{ + var $peopletag = null; + + function __construct($profile, $peopletag, $action) + { + parent::__construct($profile, $action); + + $this->peopletag = $peopletag; + } + + function showFullName() + { + parent::showFullName(); + if ($this->profile->id == $this->peopletag->tagger) { + $this->out->text(' '); + $this->out->element('span', 'role', _('Creator')); + } + } + + function showActions() + { + $this->startActions(); + if (Event::handle('StartProfileListItemActionElements', array($this))) { + $this->showSubscribeButton(); + // TODO: Untag button + Event::handle('EndProfileListItemActionElements', array($this)); + } + $this->endActions(); + } + + function linkAttributes() + { + // tagging people is healthy page-rank flow. + return parent::linkAttributes(); + } + + /** + * Fetch necessary return-to arguments for the profile forms + * to return to this list when they're done. + * + * @return array + */ + protected function returnToArgs() + { + $args = array('action' => 'peopletagged', + 'tag' => $this->peopletag->tag, + 'tagger' => $this->profile->nickname); + $page = $this->out->arg('page'); + if ($page) { + $args['param-page'] = $page; + } + return $args; + } +} diff --git a/actions/peopletagsbyuser.php b/actions/peopletagsbyuser.php new file mode 100644 index 0000000000..e0e0ccc57d --- /dev/null +++ b/actions/peopletagsbyuser.php @@ -0,0 +1,253 @@ +. + * + * @category Personal + * @package StatusNet + * @author Shashi Gowda + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once INSTALLDIR.'/lib/peopletaglist.php'; + +class PeopletagsbyuserAction extends OwnerDesignAction +{ + var $page = null; + var $tagger = null; + var $tags = null; + + function isReadOnly($args) + { + return true; + } + + function title() + { + if ($this->page == 1) { + if ($this->isOwner()) { + if ($this->arg('private')) { + return _('Private people tags by you'); + } else if ($this->arg('public')) { + return _('Public people tags by you'); + } + return _('People tags by you'); + } + return sprintf(_("People tags by %s"), $this->tagger->nickname); + } else { + return sprintf(_("People tags by %s, page %d"), $this->tagger->nickname, $this->page); + } + } + + function prepare($args) + { + parent::prepare($args); + + if ($this->arg('public') && $this->arg('private')) { + $this->args['public'] = $this->args['private'] = false; + } + + $nickname_arg = $this->arg('nickname'); + $nickname = common_canonical_nickname($nickname_arg); + + // Permanent redirect on non-canonical nickname + + if ($nickname_arg != $nickname) { + $args = $this->getSelfUrlArgs(); + if ($this->arg('page') && $this->arg('page') != 1) { + $args['page'] = $this->arg['page']; + } + common_redirect(common_local_url('peopletagsbyuser', $args), 301); + return false; + } + + $this->user = User::staticGet('nickname', $nickname); + + if (!$this->user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->tagger = $this->user->getProfile(); + + if (!$this->tagger) { + $this->serverError(_('User has no profile.')); + return false; + } + + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + + $offset = ($this->page-1) * PEOPLETAGS_PER_PAGE; + $limit = PEOPLETAGS_PER_PAGE + 1; + + $user = common_current_user(); + if ($this->arg('public')) { + $this->tags = $this->tagger->getOwnedTags(false, $offset, $limit); + } else if ($this->arg('private')) { + if (empty($user)) { + $this->clientError(_('Not logged in'), 403); + } + + if ($this->isOwner()) { + $this->tags = $this->tagger->getPrivateTags($offset, $limit); + } else { + $this->clientError(_('You cannot view others\' private people tags'), 403); + } + } else { + $this->tags = $this->tagger->getOwnedTags(common_current_user(), $offset, $limit); + } + return true; + } + + function handle($args) + { + parent::handle($args); + + # Post from the tag dropdown; redirect to a GET + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + common_redirect(common_local_url('peopletagsbyuser', $this->getSelfUrlArgs()), 303); + return; + } + + $this->showPage(); + } + + function showModeSelector() + { + $this->elementStart('dl', array('id'=>'filter_tags')); + $this->element('dt', null, _('Mode')); + $this->elementStart('dd'); + $this->elementStart('ul'); + $this->elementStart('li', array('id' => 'filter_tags_for', + 'class' => 'child_1')); + $this->element('a', + array('href' => + common_local_url('peopletagsforuser', + array('nickname' => $this->user->nickname))), + sprintf(_('People tags for %s'), $this->tagger->nickname)); + $this->elementEnd('li'); + + if ($this->isOwner()) { + $this->elementStart('li', array('id'=>'filter_tags_item')); + $this->elementStart('form', array('name' => 'modeselector', + 'id' => 'form_filter_bymode', + 'action' => common_local_url('peopletagsbyuser', + array('nickname' => $this->tagger->nickname)), + 'method' => 'post')); + $this->elementStart('fieldset'); + $this->element('legend', null, _('Select tag to filter')); + + $priv = $this->arg('private'); + $pub = $this->arg('public'); + + if (!$priv && !$pub) { + $priv = $pub = true; + } + $this->checkbox('private', _m('Private'), $priv, + _m('Show private tags')); + $this->checkbox('public', _m('Public'), $pub, + _m('Show public tags')); + $this->hidden('nickname', $this->user->nickname); + $this->submit('submit', _('Go')); + $this->elementEnd('fieldset'); + $this->elementEnd('form'); + $this->elementEnd('li'); + } + $this->elementEnd('ul'); + $this->elementEnd('dd'); + $this->elementEnd('dl'); + } + + function showAnonymousMessage() + { + $notice = + sprintf(_('These are people tags created by **%s**. ' . + 'People tags are how you sort similar ' . + 'people on %%%%site.name%%%%, a [micro-blogging]' . + '(http://en.wikipedia.org/wiki/Micro-blogging) service ' . + 'based on the Free Software [StatusNet](http://status.net/) tool. ' . + 'You can easily keep track of what they ' . + 'are doing by subscribing to the tag\'s timeline.' ), $this->tagger->nickname); + $this->elementStart('div', array('id' => 'anon_notice')); + $this->raw(common_markup_to_html($notice)); + $this->elementEnd('div'); + } + + function showPageNotice() + { + $this->elementStart('div', 'instructions'); + $this->showModeSelector(); + $this->elementEnd('div'); + } + + function showContent() + { + #TODO: controls here. + + $pl = new PeopletagList($this->tags, $this); + $cnt = $pl->show(); + + if ($cnt == 0) { + $this->showEmptyListMessage(); + } + $this->pagination($this->page > 1, $cnt > PEOPLETAGS_PER_PAGE, + $this->page, 'peopletagsbyuser', $this->getSelfUrlArgs()); + } + + function getSelfUrlArgs() + { + $args = array(); + if ($this->arg('private')) { + $args['private'] = 1; + } else if ($this->arg('public')) { + $args['public'] = 1; + } + $args['nickname'] = $this->trimmed('nickname'); + + return $args; + } + + function isOwner() + { + $user = common_current_user(); + return !empty($user) && $user->id == $this->tagger->id; + } + + function showEmptyListMessage() + { + $message = sprintf(_('%s has not created any [people tags](%%%%doc.tags%%%%) yet.'), $this->tagger->nickname); + $this->elementStart('div', 'guide'); + $this->raw(common_markup_to_html($message)); + $this->elementEnd('div'); + } + + function showSections() + { + #TODO: tags with most subscribers + #TODO: tags with most "members" + } +} diff --git a/actions/peopletagsforuser.php b/actions/peopletagsforuser.php new file mode 100644 index 0000000000..73fb225612 --- /dev/null +++ b/actions/peopletagsforuser.php @@ -0,0 +1,164 @@ +. + * + * @category Personal + * @package StatusNet + * @author Shashi Gowda + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once INSTALLDIR.'/lib/peopletaglist.php'; + +class PeopletagsforuserAction extends OwnerDesignAction +{ + var $page = null; + var $tagged = null; + + function isReadOnly($args) + { + return true; + } + + function title() + { + if ($this->page == 1) { + return sprintf(_("People tags for %s"), $this->tagged->nickname); + } else { + return sprintf(_("People tags for %s, page %d"), $this->tagged->nickname, $this->page); + } + } + + function prepare($args) + { + parent::prepare($args); + + $nickname_arg = $this->arg('nickname'); + $nickname = common_canonical_nickname($nickname_arg); + + // Permanent redirect on non-canonical nickname + + if ($nickname_arg != $nickname) { + $args = array('nickname' => $nickname); + if ($this->arg('page') && $this->arg('page') != 1) { + $args['page'] = $this->arg['page']; + } + common_redirect(common_local_url('peopletagsforuser', $args), 301); + return false; + } + + $this->user = User::staticGet('nickname', $nickname); + + if (!$this->user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->tagged = $this->user->getProfile(); + + if (!$this->tagged) { + $this->serverError(_('User has no profile.')); + return false; + } + + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + return true; + } + + function handle($args) + { + parent::handle($args); + $this->showPage(); + } + + function showAnonymousMessage() + { + $notice = + sprintf(_('These are people tags for **%s**. ' . + 'People tags are how you sort similar ' . + 'people on %%%%site.name%%%%, a [micro-blogging]' . + '(http://en.wikipedia.org/wiki/Micro-blogging) service ' . + 'based on the Free Software [StatusNet](http://status.net/) tool. ' . + 'You can easily keep track of what they ' . + 'are doing by subscribing to the tag\'s timeline.' ), $this->tagged->nickname); + $this->elementStart('div', array('id' => 'anon_notice')); + $this->raw(common_markup_to_html($notice)); + $this->elementEnd('div'); + } + + function showPageNotice() + { + $this->elementStart('dl', 'filter_tags'); + $this->elementStart('dd', array('id' => 'filter_tags_for', + 'class' => 'child_1')); + + $user = common_current_user(); + $text = ($this->tagged->id == @$user->id) ? _('People tags by you') : + sprintf(_('People tags by %s'), $this->tagged->nickname); + $this->element('a', + array('href' => + common_local_url('peopletagsbyuser', + array('nickname' => $this->tagged->nickname))), + $text); + $this->elementEnd('dd'); + $this->elementEnd('dl'); + } + + + function showContent() + { + #TODO: controls here. + + $offset = ($this->page-1) * PEOPLETAGS_PER_PAGE; + $limit = PEOPLETAGS_PER_PAGE + 1; + + $ptags = $this->tagged->getOtherTags(common_current_user(), $offset, $limit); + + $pl = new PeopletagList($ptags, $this); + $cnt = $pl->show(); + + if ($cnt == 0) { + $this->showEmptyListMessage(); + } + $this->pagination($this->page > 1, $cnt > PEOPLETAGS_PER_PAGE, + $this->page, 'peopletagsforuser', array('nickname' => $this->tagged->id)); + } + + function showEmptyListMessage() + { + $message = sprintf(_('%s has not been [tagged](%%%%doc.tags%%%%) by anyone yet.'), $this->tagged->nickname); + $this->elementStart('div', 'guide'); + $this->raw(common_markup_to_html($message)); + $this->elementEnd('div'); + } + + function showSections() + { + #TODO: tags with most subscribers + #TODO: tags with most "members" + } +} diff --git a/actions/peopletagsubscribers.php b/actions/peopletagsubscribers.php new file mode 100644 index 0000000000..1f2feeca29 --- /dev/null +++ b/actions/peopletagsubscribers.php @@ -0,0 +1,238 @@ +. + * + * @category Group + * @package StatusNet + * @author Evan Prodromou + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once(INSTALLDIR.'/lib/profilelist.php'); + +/** + * List of peopletag subscribers + * + * @category Peopletag + * @package StatusNet + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class PeopletagsubscribersAction extends OwnerDesignAction +{ + var $page = null; + var $peopletag = null; + var $tagger = null; + + function isReadOnly($args) + { + return true; + } + + function prepare($args) + { + parent::prepare($args); + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + $tagger_arg = $this->arg('tagger'); + $tag_arg = $this->arg('tag'); + $tagger = common_canonical_nickname($tagger_arg); + $tag = common_canonical_tag($tag_arg); + + // Permanent redirect on non-canonical nickname + + if ($tagger_arg != $tagger || $tag_arg != $tag) { + $args = array('tagger' => $nickname, 'tag' => $tag); + if ($this->page != 1) { + $args['page'] = $this->page; + } + common_redirect(common_local_url('peopletagged', $args), 301); + return false; + } + + if (!$tagger) { + $this->clientError(_('No tagger.'), 404); + return false; + } + + $user = User::staticGet('nickname', $tagger); + + if (!$user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->tagger = $user->getProfile(); + $this->peopletag = Profile_list::pkeyGet(array('tagger' => $user->id, 'tag' => $tag)); + + if (!$this->peopletag) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + return true; + } + + function title() + { + if ($this->page == 1) { + return sprintf(_('Subscribers of people tagged %s by %s'), + $this->peopletag->tag, $this->tagger->nickname); + } else { + return sprintf(_('Subscribers of people tagged %s by %s, page %d'), + $this->peopletag->tag, $this->tagger->nickname, + $this->page); + } + } + + function handle($args) + { + parent::handle($args); + $this->showPage(); + } + + function showPageNotice() + { + } + + function showLocalNav() + { + $nav = new PeopletagGroupNav($this); + $nav->show(); + } + + function showContent() + { + $offset = ($this->page-1) * PROFILES_PER_PAGE; + $limit = PROFILES_PER_PAGE + 1; + + $cnt = 0; + + $subs = $this->peopletag->getSubscribers($offset, $limit); + + if ($subs) { + $subscriber_list = new PeopletagSubscriberList($subs, $this->peopletag, $this); + $cnt = $subscriber_list->show(); + } + + $subs->free(); + + $this->pagination($this->page > 1, $cnt > PROFILES_PER_PAGE, + $this->page, 'peopletagsubscribers', + array('tagger' => $this->tagger->nickname, + 'tag' => $this->peopletag->tag)); + } +} + +class PeopletagSubscriberList extends ProfileList +{ + var $peopletag = null; + + function __construct($profile, $peopletag, $action) + { + parent::__construct($profile, $action); + + $this->peopletag = $peopletag; + } + + function newListItem($profile) + { + return new PeopletagSubscriberListItem($profile, $this->peopletag, $this->action); + } +} + +class PeopletagSubscriberListItem extends ProfileListItem +{ + var $peopletag = null; + + function __construct($profile, $peopletag, $action) + { + parent::__construct($profile, $action); + + $this->peopletag = $peopletag; + } + + function showFullName() + { + parent::showFullName(); + if ($this->profile->id == $this->peopletag->tagger) { + $this->out->text(' '); + $this->out->element('span', 'role', _('Creator')); + } + } + + function showActions() + { + $this->startActions(); + if (Event::handle('StartProfileListItemActionElements', array($this))) { + $this->showSubscribeButton(); + Event::handle('EndProfileListItemActionElements', array($this)); + } + $this->endActions(); + } + + function linkAttributes() + { + $aAttrs = parent::linkAttributes(); + + if (common_config('nofollow', 'members')) { + $aAttrs['rel'] .= ' nofollow'; + } + + return $aAttrs; + } + + function homepageAttributes() + { + $aAttrs = parent::linkAttributes(); + + if (common_config('nofollow', 'members')) { + $aAttrs['rel'] = 'nofollow'; + } + + return $aAttrs; + } + + /** + * Fetch necessary return-to arguments for the profile forms + * to return to this list when they're done. + * + * @return array + */ + protected function returnToArgs() + { + $args = array('action' => 'peopletagsubscribers', + 'tag' => $this->peopletag->tag, + 'tagger' => $this->profile->nickname); + $page = $this->out->arg('page'); + if ($page) { + $args['param-page'] = $page; + } + return $args; + } +} diff --git a/actions/peopletagsubscriptions.php b/actions/peopletagsubscriptions.php new file mode 100644 index 0000000000..90f232e774 --- /dev/null +++ b/actions/peopletagsubscriptions.php @@ -0,0 +1,132 @@ +. + * + * @category Personal + * @package StatusNet + * @author Shashi Gowda + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once INSTALLDIR.'/lib/peopletaglist.php'; + +class PeopletagsubscriptionsAction extends OwnerDesignAction +{ + var $page = null; + var $profile = null; + + function isReadOnly($args) + { + return true; + } + + function title() + { + if ($this->page == 1) { + return sprintf(_("People tags subscriptions by %s"), $this->profile->nickname); + } else { + return sprintf(_("People tags subscriptions by %s, page %d"), $this->profile->nickname, $this->page); + } + } + + function prepare($args) + { + parent::prepare($args); + + $nickname_arg = $this->arg('nickname'); + $nickname = common_canonical_nickname($nickname_arg); + + // Permanent redirect on non-canonical nickname + + if ($nickname_arg != $nickname) { + $args = array('nickname' => $nickname); + if ($this->arg('page') && $this->arg('page') != 1) { + $args['page'] = $this->arg['page']; + } + common_redirect(common_local_url('peopletagsbyuser', $args), 301); + return false; + } + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->profile = $user->getProfile(); + + if (!$this->profile) { + $this->serverError(_('User has no profile.')); + return false; + } + + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + return true; + } + + function handle($args) + { + parent::handle($args); + $this->showPage(); + } + + function showAnonymousMessage() + { + $notice = + sprintf(_('These are people tags subscribed to by **%s**. ' . + 'People tags are how you sort similar ' . + 'people on %%%%site.name%%%%, a [micro-blogging]' . + '(http://en.wikipedia.org/wiki/Micro-blogging) service ' . + 'based on the Free Software [StatusNet](http://status.net/) tool. ' . + 'You can easily keep track of what they ' . + 'are doing by subscribing to the tag\'s timeline.' ), $this->profile->nickname); + $this->elementStart('div', array('id' => 'anon_notice')); + $this->raw(common_markup_to_html($notice)); + $this->elementEnd('div'); + } + + function showContent() + { + $offset = ($this->page-1) * PEOPLETAGS_PER_PAGE; + $limit = PEOPLETAGS_PER_PAGE + 1; + + $ptags = $this->profile->getTagSubscriptions($offset, $limit); + + $pl = new PeopletagList($ptags, $this); + $cnt = $pl->show(); + + $this->pagination($this->page > 1, $cnt > PEOPLETAGS_PER_PAGE, + $this->page, 'peopletagsubscriptions', array('nickname' => $this->profile->id)); + } + + function showSections() + { + #TODO: tags with most subscribers + #TODO: tags with most "members" + } +} diff --git a/actions/profilecompletion.php b/actions/profilecompletion.php new file mode 100644 index 0000000000..8208f3bd37 --- /dev/null +++ b/actions/profilecompletion.php @@ -0,0 +1,214 @@ +. + * + * PHP version 5 + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/peopletageditform.php'; + +/** + * Subscription action + * + * Subscribing to a profile. Does not work for OMB 0.1 remote subscriptions, + * but may work for other remote subscription protocols, like OStatus. + * + * Takes parameters: + * + * - subscribeto: a profile ID + * - token: session token to prevent CSRF attacks + * - ajax: boolean; whether to return Ajax or full-browser results + * + * Only works if the current user is logged in. + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +class ProfilecompletionAction extends Action +{ + var $user; + var $peopletag; + var $field; + var $msg; + + /** + * Check pre-requisites and instantiate attributes + * + * @param Array $args array of arguments (URL, GET, POST) + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + // Only for logged-in users + + $this->user = common_current_user(); + + if (empty($this->user)) { + $this->clientError(_('Not logged in.')); + return false; + } + + $id = $this->arg('peopletag_id'); + $this->peopletag = Profile_list::staticGet('id', $id); + + if (empty($this->peopletag)) { + $this->clientError(_('No such peopletag.')); + return false; + } + + $field = $this->arg('field'); + if (!in_array($field, array('fulltext', 'nickname', 'fullname', 'description', 'location', 'uri'))) { + $this->clientError(sprintf(_('Unidentified field %s'), htmlspecialchars($field)), 404); + return false; + } + $this->field = $field; + + return true; + } + + /** + * Handle request + * + * Does the subscription and returns results. + * + * @param Array $args unused. + * + * @return void + */ + + function handle($args) + { + $this->msg = null; + + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, _('Search results')); + $this->elementEnd('head'); + $this->elementStart('body'); + $profiles = $this->getResults(); + + if ($this->msg !== null) { + $this->element('p', 'error', $this->msg); + } else { + if (count($profiles) > 0) { + $this->elementStart('ul', array('id' => 'profile_search_results', 'class' => 'profile-lister')); + foreach ($profiles as $profile) { + $this->showProfileItem($profile); + } + $this->elementEnd('ul'); + } else { + $this->element('p', 'error', _('No results.')); + } + } + $this->elementEnd('body'); + $this->elementEnd('html'); + } + + function getResults() + { + $profiles = array(); + $q = $this->arg('q'); + $q = strtolower($q); + if (strlen($q) < 3) { + $this->msg = _('The search string must be atleast 3 characters long'); + } + $page = $this->arg('page'); + $page = (int) (empty($page) ? 1 : $page); + + $profile = new Profile(); + $search_engine = $profile->getSearchEngine('profile'); + + if (Event::handle('StartProfileCompletionSearch', array($this, &$profile, $search_engine))) { + $search_engine->set_sort_mode('chron'); + $search_engine->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1); + + if (false === $search_engine->query($q)) { + $cnt = 0; + } + else { + $cnt = $profile->find(); + } + Event::handle('EndProfileCompletionSearch', $this, &$profile, $search_engine); + } + + while ($profile->fetch()) { + $profiles[] = clone($profile); + } + return $this->filter($profiles); + } + + function filter($profiles) + { + $current = $this->user->getProfile(); + $filtered_profiles = array(); + foreach ($profiles as $profile) { + if ($current->canTag($profile)) { + $filtered_profiles[] = $profile; + } + } + return $filtered_profiles; + } + + function showProfileItem($profile) + { + $this->elementStart('li', 'entity_removable_profile'); + $item = new TaggedProfileItem($this, $profile); + $item->show(); + $this->elementStart('span', 'entity_actions'); + + if ($profile->isTagged($this->peopletag)) { + $untag = new UntagButton($this, $profile, $this->peopletag); + $untag->show(); + } else { + $tag = new TagButton($this, $profile, $this->peopletag); + $tag->show(); + } + + $this->elementEnd('span'); + $this->elementEnd('li'); + } +} diff --git a/actions/profilesettings.php b/actions/profilesettings.php index fbaddaa5f9..f380fe4d6d 100644 --- a/actions/profilesettings.php +++ b/actions/profilesettings.php @@ -298,18 +298,24 @@ class ProfilesettingsAction extends SettingsAction return; } - if ($tagstring) { - $tags = array_map('common_canonical_tag', preg_split('/[\s,]+/', $tagstring)); - } else { - $tags = array(); - } + $tags = array(); + $tag_priv = array(); + if (is_string($tagstring) && strlen($tagstring) > 0) { - foreach ($tags as $tag) { - if (!common_valid_profile_tag($tag)) { - // TRANS: Validation error in form for profile settings. - // TRANS: %s is an invalid tag. - $this->showForm(sprintf(_('Invalid tag: "%s".'), $tag)); - return; + $tags = preg_split('/[\s,]+/', $tagstring); + + foreach ($tags as &$tag) { + $private = @$tag[0] === '.'; + + $tag = common_canonical_tag($tag); + if (!common_valid_profile_tag($tag)) { + // TRANS: Validation error in form for profile settings. + // TRANS: %s is an invalid tag. + $this->showForm(sprintf(_('Invalid tag: "%s"'), $tag)); + return; + } + + $tag_priv[$tag] = $private; } } @@ -444,7 +450,7 @@ class ProfilesettingsAction extends SettingsAction } // Set the user tags - $result = $user->setSelfTags($tags); + $result = $user->setSelfTags($tags, $tag_priv); if (!$result) { // TRANS: Server error thrown when user profile settings tags could not be saved. diff --git a/actions/profiletagbyid.php b/actions/profiletagbyid.php new file mode 100644 index 0000000000..7de5737e9a --- /dev/null +++ b/actions/profiletagbyid.php @@ -0,0 +1,92 @@ +. + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +class ProfiletagbyidAction extends Action +{ + /** peopletag we're viewing. */ + var $peopletag = null; + + /** + * Is this page read-only? + * + * @return boolean true + */ + + function isReadOnly($args) + { + return true; + } + + function prepare($args) + { + parent::prepare($args); + + $id = $this->arg('id'); + $tagger_id = $this->arg('tagger_id'); + + if (!$id) { + $this->clientError(_('No ID.')); + return false; + } + + common_debug("Peopletag id $id by user id $tagger_id"); + + $this->peopletag = Profile_list::staticGet('id', $id); + + if (!$this->peopletag) { + $this->clientError(_('No such people tag.'), 404); + return false; + } + + $user = User::staticGet('id', $tagger_id); + if (!$user) { + // remote peopletag, permanently redirect + common_redirect($this->peopletag->permalink(), 301); + } + + return true; + } + + /** + * Handle the request + * + * Shows a profile for the group, some controls, and a list of + * group notices. + * + * @return void + */ + + function handle($args) + { + common_redirect($this->peopletag->homeUrl(), 303); + } +} diff --git a/actions/public.php b/actions/public.php index b029407250..d2b0373dc6 100644 --- a/actions/public.php +++ b/actions/public.php @@ -223,6 +223,8 @@ class PublicAction extends Action $pop->show(); $gbp = new GroupsByMembersSection($this); $gbp->show(); + $ptp = new PeopletagsBySubsSection($this); + $ptp->show(); $feat = new FeaturedUsersSection($this); $feat->show(); } diff --git a/actions/publicpeopletagcloud.php b/actions/publicpeopletagcloud.php new file mode 100644 index 0000000000..dc252fe4c8 --- /dev/null +++ b/actions/publicpeopletagcloud.php @@ -0,0 +1,173 @@ +. + * + * @category Public + * @package StatusNet + * @author Mike Cochrane + * @author Evan Prodromou + * @copyright 2008 Mike Cochrane + * @copyright 2008-2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +define('TAGS_PER_PAGE', 100); + +/** + * Public tag cloud for notices + * + * @category Personal + * @package StatusNet + * @author Mike Cochrane + * @author Evan Prodromou + * @copyright 2008 Mike Cochrane + * @copyright 2008-2009 StatusNet, Inc. + * @link http://status.net/ + */ + +class PublicpeopletagcloudAction extends Action +{ + function isReadOnly($args) + { + return true; + } + + function title() + { + return _('Public people tag cloud'); + } + + function showPageNotice() + { + $this->element('p', 'instructions', + sprintf(_('These are most used people tags on %s '), + common_config('site', 'name'))); + } + + function showEmptyList() + { + $message = _('No one has [tagged](%%doc.tags%%) anyone yet.') . ' '; + + if (common_logged_in()) { + $message .= _('Be the first to tag someone!'); + } + else { + $message .= _('Why not [register an account](%%action.register%%) and be the first to tag someone!'); + } + + $this->elementStart('div', 'guide'); + $this->raw(common_markup_to_html($message)); + $this->elementEnd('div'); + } + + function showLocalNav() + { + $nav = new PublicGroupNav($this); + $nav->show(); + } + + function handle($args) + { + parent::handle($args); + $this->showPage(); + } + + function showContent() + { + // XXX: cache this + + $tags = new Profile_tag(); + $plist = new Profile_list(); + $plist->private = false; + + $tags->joinAdd($plist); + $tags->selectAdd(); + $tags->selectAdd('profile_tag.tag'); + $tags->selectAdd('count(profile_tag.tag) as weight'); + $tags->groupBy('profile_tag.tag'); + $tags->orderBy('weight DESC'); + + $tags->limit(TAGS_PER_PAGE); + + $cnt = $tags->find(); + + if ($cnt > 0) { + $this->elementStart('div', array('id' => 'tagcloud', + 'class' => 'section')); + + $tw = array(); + $sum = 0; + while ($tags->fetch()) { + $tw[$tags->tag] = $tags->weight; + $sum += $tags->weight; + } + + ksort($tw); + + $this->elementStart('dl'); + $this->element('dt', null, _('People tag cloud')); + $this->elementStart('dd'); + $this->elementStart('ul', 'tags xoxo tag-cloud'); + foreach ($tw as $tag => $weight) { + if ($sum) { + $weightedSum = $weight/$sum; + } else { + $weightedSum = 0.5; + } + $this->showTag($tag, $weight, $weightedSum); + } + $this->elementEnd('ul'); + $this->elementEnd('dd'); + $this->elementEnd('dl'); + $this->elementEnd('div'); + } else { + $this->showEmptyList(); + } + } + + function showTag($tag, $weight, $relative) + { + if ($relative > 0.1) { + $rel = 'tag-cloud-7'; + } else if ($relative > 0.05) { + $rel = 'tag-cloud-6'; + } else if ($relative > 0.02) { + $rel = 'tag-cloud-5'; + } else if ($relative > 0.01) { + $rel = 'tag-cloud-4'; + } else if ($relative > 0.005) { + $rel = 'tag-cloud-3'; + } else if ($relative > 0.002) { + $rel = 'tag-cloud-2'; + } else { + $rel = 'tag-cloud-1'; + } + + $this->elementStart('li', $rel); + + $count = ($weight == 1) ? '1 person tagged' : '%d people tagged'; + $this->element('a', array('href' => common_local_url('peopletag', array('tag' => $tag)), + 'title' => sprintf(_($count), $weight)), $tag); + $this->elementEnd('li'); + } +} diff --git a/actions/removepeopletag.php b/actions/removepeopletag.php new file mode 100644 index 0000000000..aa8ae2b6ad --- /dev/null +++ b/actions/removepeopletag.php @@ -0,0 +1,173 @@ +. + * + * PHP version 5 + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + exit(1); +} + +require_once INSTALLDIR . '/lib/togglepeopletag.php'; + +/** + * Subscription action + * + * Subscribing to a profile. Does not work for OMB 0.1 remote subscriptions, + * but may work for other remote subscription protocols, like OStatus. + * + * Takes parameters: + * + * - subscribeto: a profile ID + * - token: session token to prevent CSRF attacks + * - ajax: boolean; whether to return Ajax or full-browser results + * + * Only works if the current user is logged in. + * + * @category Action + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPLv3 + * @link http://status.net/ + */ + +class RemovepeopletagAction extends Action +{ + var $user; + var $tagged; + var $peopletag; + + /** + * Check pre-requisites and instantiate attributes + * + * @param Array $args array of arguments (URL, GET, POST) + * + * @return boolean success flag + */ + + function prepare($args) + { + parent::prepare($args); + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + // Only for logged-in users + + $this->user = common_current_user(); + + if (empty($this->user)) { + $this->clientError(_('Not logged in.')); + return false; + } + + // Profile to subscribe to + + $tagged_id = $this->arg('tagged'); + + $this->tagged = Profile::staticGet('id', $tagged_id); + + if (empty($this->tagged)) { + $this->clientError(_('No such profile.')); + return false; + } + + $id = $this->arg('peopletag_id'); + $this->peopletag = Profile_list::staticGet('id', $id); + + if (empty($this->peopletag)) { + $this->clientError(_('No such peopletag.')); + return false; + } + + // OMB 0.1 doesn't have a mechanism for local-server- + // originated tag. + + $omb01 = Remote_profile::staticGet('id', $tagged_id); + + if (!empty($omb01)) { + $this->clientError(_('You cannot tag or untag an OMB 0.1'. + ' remote profile with this action.')); + return false; + } + + return true; + } + + /** + * Handle request + * + * Does the subscription and returns results. + * + * @param Array $args unused. + * + * @return void + */ + + function handle($args) + { + // Throws exception on error + + $ptag = Profile_tag::unTag($this->user->id, $this->tagged->id, + $this->peopletag->tag); + + if (!$ptag) { + $user = User::staticGet('id', $this->tagged->id); + if ($user) { + $this->clientError( + sprintf(_('There was an unexpected error while tagging %s'), + $user->nickname)); + } else { + $this->clientError(sprintf(_('There was a problem tagging %s.' . + 'The remote server is probably not responding correctly, ' . + 'please try retrying later.'), $this->profile->profileurl)); + } + return false; + } + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, _('Untagged')); + $this->elementEnd('head'); + $this->elementStart('body'); + $unsubscribe = new TagButton($this, $this->tagged, $this->peopletag); + $unsubscribe->show(); + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + $url = common_local_url('subscriptions', + array('nickname' => $this->user->nickname)); + common_redirect($url, 303); + } + } +} diff --git a/actions/selftag.php b/actions/selftag.php new file mode 100644 index 0000000000..b0b4981f10 --- /dev/null +++ b/actions/selftag.php @@ -0,0 +1,205 @@ +. + * + * @category Action + * @package StatusNet + * @author Evan Prodromou + * @author Zach Copley + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +/** + * This class outputs a paginated list of profiles self-tagged with a given tag + * + * @category Output + * @package StatusNet + * @author Evan Prodromou + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + * + * @see Action + */ +class SelftagAction extends Action +{ + + var $tag = null; + var $page = null; + + /** + * For initializing members of the class. + * + * @param array $argarray misc. arguments + * + * @return boolean true + */ + function prepare($argarray) + { + parent::prepare($argarray); + + $this->tag = $this->trimmed('tag'); + + if (!common_valid_profile_tag($this->tag)) { + // TRANS: Client error displayed when trying to tag a profile with an invalid tag. + // TRANS: %s is the invalid tag. + $this->clientError(sprintf(_('Not a valid people tag: %s.'), + $this->tag)); + return; + } + + $this->page = ($this->arg('page')) ? $this->arg('page') : 1; + + common_set_returnto($this->selfUrl()); + + return true; + } + + /** + * Handler method + * + * @param array $argarray is ignored since it's now passed in in prepare() + * + * @return boolean is read only action? + */ + function handle($argarray) + { + parent::handle($argarray); + $this->showPage(); + } + + /** + * Whips up a query to get a list of profiles based on the provided + * people tag and page, initalizes a ProfileList widget, and displays + * it to the user. + * + * @return nothing + */ + function showContent() + { + + $profile = new Profile(); + + $offset = ($this->page - 1) * PROFILES_PER_PAGE; + $limit = PROFILES_PER_PAGE + 1; + + if (common_config('db', 'type') == 'pgsql') { + $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $lim = ' LIMIT ' . $offset . ', ' . $limit; + } + + // XXX: memcached this + + $qry = 'SELECT profile.* ' . + 'FROM profile JOIN ( profile_tag, profile_list ) ' . + 'ON profile.id = profile_tag.tagger ' . + 'AND profile_tag.tagger = profile_list.tagger ' . + 'AND profile_list.tag = profile_tag.tag ' . + 'WHERE profile_tag.tagger = profile_tag.tagged ' . + "AND profile_tag.tag = '%s' "; + + $user = common_current_user(); + if (empty($user)) { + $qry .= 'AND profile_list.private = false '; + } else { + $qry .= 'AND (profile_list.tagger = ' . $user->id . + ' OR profile_list.private = false) '; + } + + $qry .= 'ORDER BY profile_tag.modified DESC%s'; + + $profile->query(sprintf($qry, $this->tag, $lim)); + + $ptl = new SelfTagProfileList($profile, $this); // pass the ammunition + $cnt = $ptl->show(); + + $this->pagination($this->page > 1, + $cnt > PROFILES_PER_PAGE, + $this->page, + 'selftag', + array('tag' => $this->tag)); + } + + /** + * Returns the page title + * + * @return string page title + */ + function title() + { + return sprintf(_('Users self-tagged with %1$s - page %2$d'), + $this->tag, $this->page); + } + +} + +class SelfTagProfileList extends ProfileList +{ + function newListItem($profile) + { + return new SelfTagProfileListItem($profile, $this->action); + } +} + +class SelfTagProfileListItem extends ProfileListItem +{ + function linkAttributes() + { + $aAttrs = parent::linkAttributes(); + + if (common_config('nofollow', 'selftag')) { + $aAttrs['rel'] .= ' nofollow'; + } + + return $aAttrs; + } + + function homepageAttributes() + { + $aAttrs = parent::linkAttributes(); + + if (common_config('nofollow', 'selftag')) { + $aAttrs['rel'] = 'nofollow'; + } + + return $aAttrs; + } + + function showTags() + { + $selftags = new SelfTagsWidget($this->out, $this->profile, $this->profile); + $selftags->show(); + + $user = common_current_user(); + + if (!empty($user) && $user->id != $this->profile->id && + $user->getProfile()->canTag($this->profile)) { + $yourtags = new PeopleTagsWidget($this->out, $user, $this->profile); + $yourtags->show(); + } + } +} diff --git a/actions/showprofiletag.php b/actions/showprofiletag.php new file mode 100644 index 0000000000..d9f9e9c12e --- /dev/null +++ b/actions/showprofiletag.php @@ -0,0 +1,354 @@ +. + * + * @category Actions + * @package Actions + * @license GNU Affero General Public License http://www.gnu.org/licenses/ + * @link http://status.net + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +require_once INSTALLDIR.'/lib/profileminilist.php'; +require_once INSTALLDIR.'/lib/peopletaglist.php'; +require_once INSTALLDIR.'/lib/noticelist.php'; +require_once INSTALLDIR.'/lib/feedlist.php'; + +class ShowprofiletagAction extends Action +{ + var $notice, $tagger, $peopletag; + + function isReadOnly($args) + { + return true; + } + + function prepare($args) + { + parent::prepare($args); + + $tagger_arg = $this->arg('tagger'); + $tag_arg = $this->arg('tag'); + $tagger = common_canonical_nickname($tagger_arg); + $tag = common_canonical_tag($tag_arg); + + // Permanent redirect on non-canonical nickname + + if ($tagger_arg != $tagger || $tag_arg != $tag) { + $args = array('tagger' => $nickname, 'tag' => $tag); + if ($this->page != 1) { + $args['page'] = $this->page; + } + common_redirect(common_local_url('showprofiletag', $args), 301); + return false; + } + + if (!$tagger) { + $this->clientError(_('No tagger.'), 404); + return false; + } + + $user = User::staticGet('nickname', $tagger); + + if (!$user) { + $this->clientError(_('No such user.'), 404); + return false; + } + + $this->tagger = $user->getProfile(); + $this->peopletag = Profile_list::pkeyGet(array('tagger' => $user->id, 'tag' => $tag)); + + $current = common_current_user(); + $can_see = !empty($this->peopletag) && (!$this->peopletag->private || + ($this->peopletag->private && $this->peopletag->tagger === $current->id)); + + if (!$can_see) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + $this->notice = $this->peopletag->getNotices(($this->page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + + if ($this->page > 1 && $this->notice->N == 0) { + // TRANS: Server error when page not found (404) + $this->serverError(_('No such page.'), $code = 404); + } + + return true; + } + + function handle($args) + { + parent::handle($args); + + if (!$this->peopletag) { + $this->clientError(_('No such user.')); + return; + } + + $this->showPage(); + } + + function title() + { + if ($this->page > 1) { + + if($this->peopletag->private) { + return sprintf(_('Private timeline for people tagged %s by you, page %d'), + $this->peopletag->tag, $this->page); + } + + $current = common_current_user(); + if (!empty($current) && $current->id == $this->peopletag->tagger) { + return sprintf(_('Timeline for people tagged %s by you, page %d'), + $this->peopletag->tag, $this->page); + } + + // TRANS: Page title. %1$s is user nickname, %2$d is page number + return sprintf(_('Timeline for people tagged %1$s by %2$s, page %3$d'), + $this->peopletag->tag, + $this->tagger->nickname, + $this->page + ); + } else { + + if($this->peopletag->private) { + return sprintf(_('Private timeline of people tagged %s by you'), + $this->peopletag->tag, $this->page); + } + + $current = common_current_user(); + if (!empty($current) && $current->id == $this->peopletag->tagger) { + return sprintf(_('Timeline for people tagged %s by you'), + $this->peopletag->tag, $this->page); + } + + // TRANS: Page title. %1$s is user nickname, %2$d is page number + return sprintf(_('Timeline for people tagged %1$s by %2$s'), + $this->peopletag->tag, + $this->tagger->nickname, + $this->page + ); + } + } + + function getFeeds() + { + #XXX: make these actually work + return array(new Feed(Feed::RSS2, + common_local_url( + 'ApiTimelineList', array( + 'user' => $this->tagger->id, + 'id' => $this->peopletag->id, + 'format' => 'rss' + ) + ), + // TRANS: %1$s is user nickname + sprintf(_('Feed for friends of %s (RSS 2.0)'), $this->tagger->nickname)), + new Feed(Feed::ATOM, + common_local_url( + 'ApiTimelineList', array( + 'user' => $this->tagger->id, + 'id' => $this->peopletag->id, + 'format' => 'atom' + ) + ), + // TRANS: %1$s is user nickname + sprintf(_('Feed for people tagged %s by %s (Atom)'), + $this->peopletag->tag, $this->tagger->nickname + ) + ) + ); + } + + function showObjectNav() + { + $nav = new PeopletagGroupNav($this); + $nav->show(); + } + + function showEmptyListMessage() + { + // TRANS: %1$s is user nickname + $message = sprintf(_('This is the timeline for people tagged %s by %s but no one has posted anything yet.'), $this->peopletag->tag, $this->tagger->nickname) . ' '; + + if (common_logged_in()) { + $current_user = common_current_user(); + if ($this->tagger->id == $current_user->id) { + $message .= _('Try tagging more people.'); + } + } else { + $message .= _('Why not [register an account](%%%%action.register%%%%) and start following this timeline.'); + } + + $this->elementStart('div', 'guide'); + $this->raw(common_markup_to_html($message)); + $this->elementEnd('div'); + } + + function showContent() + { + $this->showPeopletag(); + $this->showNotices(); + } + + function showPeopletag() + { + $cur = common_current_user(); + $tag = new Peopletag($this->peopletag, $cur, $this); + $tag->show(); + } + + function showNotices() + { + if (Event::handle('StartShowProfileTagContent', array($this))) { + $nl = new NoticeList($this->notice, $this); + + $cnt = $nl->show(); + + if (0 == $cnt) { + $this->showEmptyListMessage(); + } + + $this->pagination( + $this->page > 1, $cnt > NOTICES_PER_PAGE, + $this->page, 'showprofiletag', array('tag' => $this->peopletag->tag, + 'tagger' => $this->tagger->nickname) + ); + + Event::handle('EndShowProfileTagContent', array($this)); + } + } + + function showSections() + { + $this->showTagged(); + if (!$this->peopletag->private) { + $this->showSubscribers(); + } + # $this->showStatistics(); + } + + function showPageTitle() + { + $this->element('h1', null, $this->title()); + } + + function showTagged() + { + $profile = $this->peopletag->getTagged(0, PROFILES_PER_MINILIST + 1); + + $this->elementStart('div', array('id' => 'entity_tagged', + 'class' => 'section')); + if (Event::handle('StartShowTaggedProfilesMiniList', array($this))) { + + $title = ''; + + $current = common_current_user(); + if(!empty($current) && $this->peopletag->tagger == $current->id) { + $title = sprintf(_('People tagged %s by you'), $this->peopletag->tag); + } else { + $title = sprintf(_('People tagged %1$s by %2$s'), + $this->peopletag->tag, + $this->tagger->nickname); + } + + $this->element('h2', null, $title); + + $cnt = 0; + + if (!empty($profile)) { + $pml = new ProfileMiniList($profile, $this); + $cnt = $pml->show(); + if ($cnt == 0) { + $this->element('p', null, _('(None)')); + } + } + + if ($cnt > PROFILES_PER_MINILIST) { + $this->elementStart('p'); + $this->element('a', array('href' => common_local_url('taggedprofiles', + array('nickname' => $this->tagger->nickname, + 'profiletag' => $this->peopletag->tag)), + 'class' => 'more'), + _('Show all')); + $this->elementEnd('p'); + } + + Event::handle('EndShowTaggedProfilesMiniList', array($this)); + } + $this->elementEnd('div'); + } + + function showSubscribers() + { + $profile = $this->peopletag->getSubscribers(0, PROFILES_PER_MINILIST + 1); + + $this->elementStart('div', array('id' => 'entity_subscribers', + 'class' => 'section')); + if (Event::handle('StartShowProfileTagSubscribersMiniList', array($this))) { + $this->element('h2', null, _('Subscribers')); + + $cnt = 0; + + if (!empty($profile)) { + $pml = new ProfileMiniList($profile, $this); + $cnt = $pml->show(); + if ($cnt == 0) { + $this->element('p', null, _('(None)')); + } + } + + if ($cnt > PROFILES_PER_MINILIST) { + $this->elementStart('p'); + $this->element('a', array('href' => common_local_url('profiletagsubscribers', + array('nickname' => $this->tagger->nickname, + 'profiletag' => $this->peopletag->tag)), + 'class' => 'more'), + _('All subscribers')); + $this->elementEnd('p'); + } + + Event::handle('EndShowProfileTagSubscribersMiniList', array($this)); + } + $this->elementEnd('div'); + } +} + +class Peopletag extends PeopletagListItem +{ + function showStart() + { + $mode = $this->peopletag->private ? 'private' : 'public'; + $this->out->elementStart('div', array('class' => 'hentry peopletag peopletag-profile mode-'.$mode, + 'id' => 'peopletag-' . $this->peopletag->id)); + } + + function showEnd() + { + $this->out->elementEnd('div'); + } + + function showAvatar() + { + parent::showAvatar(AVATAR_PROFILE_SIZE); + } +} diff --git a/actions/subscribepeopletag.php b/actions/subscribepeopletag.php new file mode 100644 index 0000000000..e38ecb2d3e --- /dev/null +++ b/actions/subscribepeopletag.php @@ -0,0 +1,144 @@ +. + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +/** + * Subscribe to a peopletag + * + * This is the action for subscribing to a peopletag. It works more or less like the join action + * for groups. + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class SubscribepeopletagAction extends Action +{ + var $peopletag = null; + var $tagger = null; + + /** + * Prepare to run + */ + + function prepare($args) + { + parent::prepare($args); + + if (!common_logged_in()) { + $this->clientError(_('You must be logged in to unsubscribe to a peopletag.')); + return false; + } + // Only allow POST requests + + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->clientError(_('This action only accepts POST requests.')); + return false; + } + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + $tagger_arg = $this->trimmed('tagger'); + $tag_arg = $this->trimmed('tag'); + + $id = intval($this->arg('id')); + if ($id) { + $this->peopletag = Profile_list::staticGet('id', $id); + } else { + $this->clientError(_('No ID given.'), 404); + return false; + } + + if (!$this->peopletag || $this->peopletag->private) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + $this->tagger = Profile::staticGet('id', $this->peopletag->tagger); + + return true; + } + + /** + * Handle the request + * + * On POST, add the current user to the group + * + * @param array $args unused + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + $cur = common_current_user(); + + try { + Profile_tag_subscription::add($this->peopletag, $cur); + } catch (Exception $e) { + $this->serverError(sprintf(_('Could not subscribe user %1$s to peopletag %2$s.'), + $cur->nickname, $this->peopletag->tag) . ' ' . $e->getMessage()); + } + + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, sprintf(_('%1$s subscribed to peopletag %2$s by %3$s'), + $cur->nickname, + $this->peopletag->tag, + $this->tagger->nickname)); + $this->elementEnd('head'); + $this->elementStart('body'); + $lf = new UnsubscribePeopletagForm($this, $this->peopletag); + $lf->show(); + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + common_redirect(common_local_url('peopletagsubscribers', + array('tagger' => $this->tagger->nickname, + 'tag' =>$this->peopletag->tag)), + 303); + } + } +} diff --git a/actions/tagother.php b/actions/tagother.php deleted file mode 100644 index be1aae20eb..0000000000 --- a/actions/tagother.php +++ /dev/null @@ -1,237 +0,0 @@ -. - */ - -if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } - -require_once(INSTALLDIR.'/lib/settingsaction.php'); - -// @todo FIXME: documentation missing. -class TagotherAction extends Action -{ - var $profile = null; - var $error = null; - - function prepare($args) - { - parent::prepare($args); - if (!common_logged_in()) { - // TRANS: Error message displayed when trying to perform an action that requires a logged in user. - $this->clientError(_('Not logged in.'), 403); - return false; - } - - $id = $this->trimmed('id'); - if (!$id) { - // TRANS: Client error displayed on user tag page when trying to add tags without providing a user ID. - $this->clientError(_('No ID argument.')); - return false; - } - - $this->profile = Profile::staticGet('id', $id); - - if (!$this->profile) { - // TRANS: Client error displayed on user tag page when trying to add tags providing a non-existing user ID. - $this->clientError(_('No profile with that ID.')); - return false; - } - - return true; - } - - function handle($args) - { - parent::handle($args); - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->saveTags(); - } else { - $this->showForm($profile); - } - } - - function title() - { - // TRANS: Title for "tag other users" page. - // TRANS: %s is the user nickname. - return sprintf(_('Tag %s'), $this->profile->nickname); - } - - function showForm($error=null) - { - $this->error = $error; - $this->showPage(); - } - - function showContent() - { - $this->elementStart('div', 'entity_profile vcard author'); - // TRANS: Header for user details on "tag other users" page. - $this->element('h2', null, _('User profile')); - - $avatar = $this->profile->getAvatar(AVATAR_PROFILE_SIZE); - $this->element('img', array('src' => ($avatar) ? $avatar->displayUrl() : Avatar::defaultImage(AVATAR_PROFILE_SIZE), - 'class' => 'photo avatar entity_depiction', - 'width' => AVATAR_PROFILE_SIZE, - 'height' => AVATAR_PROFILE_SIZE, - 'alt' => - ($this->profile->fullname) ? $this->profile->fullname : - $this->profile->nickname)); - - $this->element('a', array('href' => $this->profile->profileurl, - 'class' => 'entity_nickname nickname'), - $this->profile->nickname); - - if ($this->profile->fullname) { - $this->element('div', 'fn entity_fn', $this->profile->fullname); - } - - if ($this->profile->location) { - $this->element('div', 'label entity_location', $this->profile->location); - } - - if ($this->profile->homepage) { - $this->element('a', array('href' => $this->profile->homepage, - 'rel' => 'me', - 'class' => 'url entity_url'), - $this->profile->homepage); - } - - if ($this->profile->bio) { - $this->element('div', 'note entity_note', $this->profile->bio); - } - - $this->elementEnd('div'); - - $this->elementStart('form', array('method' => 'post', - 'id' => 'form_tag_user', - 'class' => 'form_settings', - 'name' => 'tagother', - 'action' => common_local_url('tagother', array('id' => $this->profile->id)))); - - $this->elementStart('fieldset'); - // TRANS: Fieldset legend on "tag other users" page. - $this->element('legend', null, _('Tag user')); - $this->hidden('token', common_session_token()); - $this->hidden('id', $this->profile->id); - - $user = common_current_user(); - - $this->elementStart('ul', 'form_data'); - $this->elementStart('li'); - // TRANS: Field label for inputting tags on "tag other users" page. - $this->input('tags', _('Tags'), - ($this->arg('tags')) ? $this->arg('tags') : implode(' ', Profile_tag::getTags($user->id, $this->profile->id)), - // TRANS: Title for input field for inputting tags on "tag other users" page. - _('Tags for this user (letters, numbers, -, ., and _), separated by commas or spaces.')); - $this->elementEnd('li'); - $this->elementEnd('ul'); - // TRANS: Button text for saving tags for other users. - $this->submit('save', _m('BUTTON','Save')); - $this->elementEnd('fieldset'); - $this->elementEnd('form'); - } - - function saveTags() - { - $id = $this->trimmed('id'); - $tagstring = $this->trimmed('tags'); - $token = $this->trimmed('token'); - - if (!$token || $token != common_session_token()) { - // TRANS: Client error displayed when the session token does not match or is not given. - $this->showForm(_('There was a problem with your session token. '. - 'Try again, please.')); - return; - } - - if (is_string($tagstring) && strlen($tagstring) > 0) { - - $tags = array_map('common_canonical_tag', - preg_split('/[\s,]+/', $tagstring)); - - foreach ($tags as $tag) { - if (!common_valid_profile_tag($tag)) { - // TRANS: Form validation error when entering an invalid tag. - // TRANS: %s is the invalid tag. - $this->showForm(sprintf(_('Invalid tag: "%s".'), $tag)); - return; - } - } - } else { - $tags = array(); - } - - $user = common_current_user(); - - if (!Subscription::pkeyGet(array('subscriber' => $user->id, - 'subscribed' => $this->profile->id)) && - !Subscription::pkeyGet(array('subscriber' => $this->profile->id, - 'subscribed' => $user->id))) - { - // TRANS: Client error on "tag other users" page when tagging a user is not possible because of missing mutual subscriptions. - $this->clientError(_('You can only tag people you are subscribed to or who are subscribed to you.')); - return; - } - - $result = Profile_tag::setTags($user->id, $this->profile->id, $tags); - - if (!$result) { - // TRANS: Client error on "tag other users" page when saving tags fails server side. - $this->clientError(_('Could not save tags.')); - return; - } - - $action = $user->isSubscribed($this->profile) ? 'subscriptions' : 'subscribers'; - - if ($this->boolean('ajax')) { - $this->startHTML('text/xml;charset=utf-8'); - $this->elementStart('head'); - // TRANS: Title of "tag other users" page. - $this->element('title', null, _m('TITLE','Tags')); - $this->elementEnd('head'); - $this->elementStart('body'); - $this->elementStart('p', 'subtags'); - foreach ($tags as $tag) { - $this->element('a', array('href' => common_local_url($action, - array('nickname' => $user->nickname, - 'tag' => $tag))), - $tag); - } - $this->elementEnd('p'); - $this->elementEnd('body'); - $this->elementEnd('html'); - } else { - common_redirect(common_local_url($action, array('nickname' => - $user->nickname)), - 303); - } - } - - function showPageNotice() - { - if ($this->error) { - $this->element('p', 'error', $this->error); - } else { - $this->elementStart('div', 'instructions'); - $this->element('p', null, - // TRANS: Page notice on "tag other users" page. - _('Use this form to add tags to your subscribers or subscriptions.')); - $this->elementEnd('div'); - } - } -} diff --git a/actions/tagprofile.php b/actions/tagprofile.php new file mode 100644 index 0000000000..8c0e039dd6 --- /dev/null +++ b/actions/tagprofile.php @@ -0,0 +1,249 @@ +. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +require_once INSTALLDIR . '/lib/settingsaction.php'; +require_once INSTALLDIR . '/lib/peopletags.php'; + +class TagprofileAction extends Action +{ + var $profile = null; + var $error = null; + + function prepare($args) + { + parent::prepare($args); + if (!common_logged_in()) { + common_set_returnto($_SERVER['REQUEST_URI']); + if (Event::handle('RedirectToLogin', array($this, null))) { + common_redirect(common_local_url('login'), 303); + } + } + + $id = $this->trimmed('id'); + if (!$id) { + $this->profile = false; + } else { + $this->profile = Profile::staticGet('id', $id); + + if (!$this->profile) { + $this->clientError(_('No profile with that ID.')); + return false; + } + } + + $current = common_current_user()->getProfile(); + if ($this->profile && !$current->canTag($this->profile)) { + $this->clientError(_('You cannot tag this user.')); + } + return true; + } + + function handle($args) + { + parent::handle($args); + if (Event::handle('StartTagProfileAction', array($this, $this->profile))) { + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->saveTags(); + } else { + $this->showForm(); + } + Event::handle('EndTagProfileAction', array($this, $this->profile)); + } + } + + function title() + { + if (!$this->profile) { + return _('Tag a profile'); + } + return sprintf(_('Tag %s'), $this->profile->nickname); + } + + function showForm($error=null) + { + $this->error = $error; + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, _('Error')); + $this->elementEnd('head'); + $this->elementStart('body'); + $this->element('p', 'error', $error); + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + $this->showPage(); + } + } + + function showContent() + { + if (Event::handle('StartShowTagProfileForm', array($this, $this->profile)) && $this->profile) { + $this->elementStart('div', 'entity_profile vcard author'); + $this->element('h2', null, _('User profile')); + + $avatar = $this->profile->getAvatar(AVATAR_PROFILE_SIZE); + $this->element('img', array('src' => ($avatar) ? $avatar->displayUrl() : Avatar::defaultImage(AVATAR_PROFILE_SIZE), + 'class' => 'photo avatar entity_depiction', + 'width' => AVATAR_PROFILE_SIZE, + 'height' => AVATAR_PROFILE_SIZE, + 'alt' => + ($this->profile->fullname) ? $this->profile->fullname : + $this->profile->nickname)); + + $this->element('a', array('href' => $this->profile->profileurl, + 'class' => 'entity_nickname nickname'), + $this->profile->nickname); + if ($this->profile->fullname) { + $this->element('div', 'fn entity_fn', $this->profile->fullname); + } + + if ($this->profile->location) { + $this->element('div', 'label entity_location', $this->profile->location); + } + + if ($this->profile->homepage) { + $this->element('a', array('href' => $this->profile->homepage, + 'rel' => 'me', + 'class' => 'url entity_url'), + $this->profile->homepage); + } + + if ($this->profile->bio) { + $this->element('div', 'note entity_note', $this->profile->bio); + } + + $this->elementEnd('div'); + + $this->elementStart('form', array('method' => 'post', + 'id' => 'form_tag_user', + 'class' => 'form_settings', + 'name' => 'tagprofile', + 'action' => common_local_url('tagprofile', array('id' => $this->profile->id)))); + + $this->elementStart('fieldset'); + $this->element('legend', null, _('Tag user')); + $this->hidden('token', common_session_token()); + $this->hidden('id', $this->profile->id); + + $user = common_current_user(); + + $this->elementStart('ul', 'form_data'); + $this->elementStart('li'); + + $tags = Profile_tag::getTagsArray($user->id, $this->profile->id, $user->id); + $this->input('tags', _('Tags'), + ($this->arg('tags')) ? $this->arg('tags') : implode(' ', $tags), + _('Tags for this user (letters, numbers, -, ., and _), comma- or space- separated')); + $this->elementEnd('li'); + $this->elementEnd('ul'); + $this->submit('save', _('Save')); + $this->elementEnd('fieldset'); + $this->elementEnd('form'); + + Event::handle('EndShowTagProfileForm', array($this, $this->profile)); + } + } + + function saveTags() + { + $id = $this->trimmed('id'); + $tagstring = $this->trimmed('tags'); + $token = $this->trimmed('token'); + + if (Event::handle('StartSavePeopletags', array($this, $tagstring))) { + if (!$token || $token != common_session_token()) { + $this->showForm(_('There was a problem with your session token. '. + 'Try again, please.')); + return; + } + + $tags = array(); + $tag_priv = array(); + + if (is_string($tagstring) && strlen($tagstring) > 0) { + + $tags = preg_split('/[\s,]+/', $tagstring); + + foreach ($tags as &$tag) { + $private = @$tag[0] === '.'; + + $tag = common_canonical_tag($tag); + if (!common_valid_profile_tag($tag)) { + $this->showForm(sprintf(_('Invalid tag: "%s"'), $tag)); + return; + } + + $tag_priv[$tag] = $private; + } + } + + $user = common_current_user(); + + try { + $result = Profile_tag::setTags($user->id, $this->profile->id, $tags, $tag_priv); + if (!$result) { + throw new Exception('The tags could not be saved.'); + } + } catch (Exception $e) { + $this->showForm($e->getMessage()); + return false; + } + + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, _('Tags')); + $this->elementEnd('head'); + $this->elementStart('body'); + + if ($user->id == $this->profile->id) { + $widget = new SelftagsWidget($this, $user, $this->profile); + $widget->show(); + } else { + $widget = new PeopletagsWidget($this, $user, $this->profile); + $widget->show(); + } + + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + $this->error = 'Tags saved.'; + $this->showForm(); + } + + Event::handle('EndSavePeopletags', array($this, $tagstring)); + } + } + + function showPageNotice() + { + if ($this->error) { + $this->element('p', 'error', $this->error); + } else { + $this->elementStart('div', 'instructions'); + $this->element('p', null, + _('Use this form to add tags to your subscribers or subscriptions.')); + $this->elementEnd('div'); + } + } +} + diff --git a/actions/unsubscribepeopletag.php b/actions/unsubscribepeopletag.php new file mode 100644 index 0000000000..a912cc10f9 --- /dev/null +++ b/actions/unsubscribepeopletag.php @@ -0,0 +1,142 @@ +. + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +/** + * Unsubscribe to a peopletag + * + * This is the action for subscribing to a peopletag. It works more or less like the join action + * for groups. + * + * @category Peopletag + * @package StatusNet + * @author Shashi Gowda + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +class UnsubscribepeopletagAction extends Action +{ + var $peopletag = null; + var $tagger = null; + + /** + * Prepare to run + */ + + function prepare($args) + { + parent::prepare($args); + + if (!common_logged_in()) { + $this->clientError(_('You must be logged in to unsubscribe to a peopletag.')); + return false; + } + // Only allow POST requests + + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->clientError(_('This action only accepts POST requests.')); + return false; + } + + // CSRF protection + + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->clientError(_('There was a problem with your session token.'. + ' Try again, please.')); + return false; + } + + $tagger_arg = $this->trimmed('tagger'); + $tag_arg = $this->trimmed('tag'); + + $id = intval($this->arg('id')); + if ($id) { + $this->peopletag = Profile_list::staticGet('id', $id); + } else { + $this->clientError(_('No ID given.'), 404); + return false; + } + + if (!$this->peopletag || $this->peopletag->private) { + $this->clientError(_('No such peopletag.'), 404); + return false; + } + + $this->tagger = Profile::staticGet('id', $this->peopletag->tagger); + + return true; + } + + /** + * Handle the request + * + * On POST, add the current user to the group + * + * @param array $args unused + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + $cur = common_current_user(); + + Profile_tag_subscription::remove($this->peopletag, $cur); + + if ($this->boolean('ajax')) { + $this->startHTML('text/xml;charset=utf-8'); + $this->elementStart('head'); + $this->element('title', null, sprintf(_('%1$s unsubscribed to peopletag %2$s by %3$s'), + $cur->nickname, + $this->peopletag->tag, + $this->tagger->nickname)); + $this->elementEnd('head'); + $this->elementStart('body'); + $lf = new SubscribePeopletagForm($this, $this->peopletag); + $lf->show(); + $this->elementEnd('body'); + $this->elementEnd('html'); + } else { + if (common_get_returnto()) { + common_redirect(common_get_returnto(), 303); + return true; + } + common_redirect(common_local_url('peopletagsbyuser', + array('nickname' => $this->tagger->nickname)), + 303); + } + } +} diff --git a/classes/Notice.php b/classes/Notice.php index cf1cfc526b..73d27c8154 100644 --- a/classes/Notice.php +++ b/classes/Notice.php @@ -545,6 +545,12 @@ class Notice extends Memcached_DataObject $notice->saveKnownGroups($groups); + if (isset($peopletags)) { + $notice->saveProfileTags($peopletags); + } else { + $notice->saveProfileTags(); + } + if (isset($urls)) { $notice->saveKnownUrls($urls); } else { @@ -851,6 +857,7 @@ class Notice extends Memcached_DataObject } $users = $this->getSubscribedUsers(); + $ptags = $this->getProfileTags(); // FIXME: kind of ignoring 'transitional'... // we'll probably stop supporting inboxless mode @@ -874,27 +881,39 @@ class Notice extends Memcached_DataObject } } + foreach ($ptags as $ptag) { + $users = $ptag->getUserSubscribers(); + foreach ($users as $id) { + if (!array_key_exists($id, $ni)) { + $user = User::staticGet('id', $id); + if (!$user->hasBlocked($profile)) { + $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG; + } + } + } + } + foreach ($recipients as $recipient) { if (!array_key_exists($recipient, $ni)) { $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY; } - } - // Exclude any deleted, non-local, or blocking recipients. - $profile = $this->getProfile(); - $originalProfile = null; - if ($this->repeat_of) { - // Check blocks against the original notice's poster as well. - $original = Notice::staticGet('id', $this->repeat_of); - if ($original) { - $originalProfile = $original->getProfile(); + // Exclude any deleted, non-local, or blocking recipients. + $profile = $this->getProfile(); + $originalProfile = null; + if ($this->repeat_of) { + // Check blocks against the original notice's poster as well. + $original = Notice::staticGet('id', $this->repeat_of); + if ($original) { + $originalProfile = $original->getProfile(); + } } - } - foreach ($ni as $id => $source) { - $user = User::staticGet('id', $id); - if (empty($user) || $user->hasBlocked($profile) || - ($originalProfile && $user->hasBlocked($originalProfile))) { - unset($ni[$id]); + foreach ($ni as $id => $source) { + $user = User::staticGet('id', $id); + if (empty($user) || $user->hasBlocked($profile) || + ($originalProfile && $user->hasBlocked($originalProfile))) { + unset($ni[$id]); + } } } @@ -974,6 +993,39 @@ class Notice extends Memcached_DataObject return $ids; } + function getProfileTags() + { + // Don't save ptags for repeats, for now. + + if (!empty($this->repeat_of)) { + return array(); + } + + // XXX: cache me + + $ptags = array(); + + $ptagi = new Profile_tag_inbox(); + + $ptagi->selectAdd(); + $ptagi->selectAdd('profile_tag_id'); + + $ptagi->notice_id = $this->id; + + if ($ptagi->find()) { + while ($ptagi->fetch()) { + $profile_list = Profile_list::staticGet('id', $ptagi->profile_tag_id); + if ($profile_list) { + $ptags[] = $profile_list; + } + } + } + + $ptagi->free(); + + return $ptags; + } + /** * Record this notice to the given group inboxes for delivery. * Overrides the regular parsing of !group markup. @@ -1086,6 +1138,69 @@ class Notice extends Memcached_DataObject return true; } + /** + * record targets into profile_tag_inbox. + * @return array of Profile_list objects + */ + function saveProfileTags($known=array()) + { + // Don't save ptags for repeats, for now + + if (!empty($this->repeat_of)) { + return array(); + } + + if (is_array($known)) { + $ptags = $known; + } else { + $ptags = array(); + } + + $ptag = new Profile_tag(); + $ptag->tagged = $this->profile_id; + + if($ptag->find()) { + while($ptag->fetch()) { + $plist = Profile_list::getByTaggerAndTag($ptag->tagger, $ptag->tag); + $ptags[] = clone($plist); + } + } + + foreach ($ptags as $target) { + $this->addToProfileTagInbox($target); + } + + return $ptags; + } + + function addToProfileTagInbox($plist) + { + $ptagi = Profile_tag_inbox::pkeyGet(array('profile_tag_id' => $plist->id, + 'notice_id' => $this->id)); + + if (empty($ptagi)) { + + $ptagi = new Profile_tag_inbox(); + + $ptagi->query('BEGIN'); + $ptagi->profile_tag_id = $plist->id; + $ptagi->notice_id = $this->id; + $ptagi->created = $this->created; + + $result = $ptagi->insert(); + if (!$result) { + common_log_db_error($ptagi, 'INSERT', __FILE__); + throw new ServerException(_('Problem saving profile_tag inbox.')); + } + + $ptagi->query('COMMIT'); + + self::blow('profile_tag:notice_ids:%d', $ptagi->profile_tag_id); + } + + return true; + } + /** * Save reply records indicating that this notice needs to be * delivered to the local users with the given URIs. diff --git a/classes/Profile.php b/classes/Profile.php index 7340af952d..fb51658aab 100644 --- a/classes/Profile.php +++ b/classes/Profile.php @@ -272,6 +272,183 @@ class Profile extends Memcached_DataObject return new ArrayWrapper($groups); } + function isTagged($peopletag) + { + $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger, + 'tagged' => $this->id, + 'tag' => $peopletag->tag)); + return !empty($tag); + } + + function canTag($tagged) + { + if (empty($tagged)) { + return false; + } + + if ($tagged->id == $this->id) { + return true; + } + + $all = common_config('peopletag', 'allow_tagging', 'all'); + $local = common_config('peopletag', 'allow_tagging', 'local'); + $remote = common_config('peopletag', 'allow_tagging', 'remote'); + $subs = common_config('peopletag', 'allow_tagging', 'subs'); + + if ($all) { + return true; + } + + $tagged_user = $tagged->getUser(); + if (!empty($tagged_user)) { + if ($local) { + return true; + } + } else if ($subs) { + return (Subscription::exists($this, $tagged) || + Subscription::exists($tagged, $this)); + } else if ($remote) { + return true; + } + return false; + } + + function getOwnedTags($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0) + { + $tags = new Profile_list(); + $tags->tagger = $this->id; + + if (($auth_user instanceof User || $auth_user instanceof Profile) && + $auth_user->id === $this->id) { + // no condition, get both private and public tags + } else { + $tags->private = false; + } + + $tags->selectAdd('id as "cursor"'); + + if ($since_id>0) { + $tags->whereAdd('id > '.$since_id); + } + + if ($max_id>0) { + $tags->whereAdd('id <= '.$max_id); + } + + if($offset>=0 && !is_null($limit)) { + $tags->limit($offset, $limit); + } + + $tags->orderBy('id DESC'); + $tags->find(); + + return $tags; + } + + function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0) + { + $lists = new Profile_list(); + + $tags = new Profile_tag(); + $tags->tagged = $this->id; + + $lists->joinAdd($tags); + #@fixme: postgres (round(date_part('epoch', my_date))) + $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"'); + + if ($auth_user instanceof User || $auth_user instanceof Profile) { + $lists->whereAdd('( ( profile_list.private = false ) ' . + 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' . + 'profile_list.private = true ) )'); + } else { + $lists->private = false; + } + + if ($since_id>0) { + $lists->whereAdd('cursor > '.$since_id); + } + + if ($max_id>0) { + $lists->whereAdd('cursor <= '.$max_id); + } + + if($offset>=0 && !is_null($limit)) { + $lists->limit($offset, $limit); + } + + $lists->orderBy('profile_tag.modified DESC'); + $lists->find(); + + return $lists; + } + + function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0) + { + $tags = new Profile_list(); + $tags->private = true; + $tags->tagger = $this->id; + + if ($since_id>0) { + $tags->whereAdd('id > '.$since_id); + } + + if ($max_id>0) { + $tags->whereAdd('id <= '.$max_id); + } + + if($offset>=0 && !is_null($limit)) { + $tags->limit($offset, $limit); + } + + $tags->orderBy('id DESC'); + $tags->find(); + + return $tags; + } + + function hasLocalTags() + { + $tags = new Profile_tag(); + + $tags->joinAdd(array('tagger', 'user:id')); + $tags->whereAdd('tagged = '.$this->id); + $tags->whereAdd('tagger != '.$this->id); + + $tags->limit(0, 1); + $tags->fetch(); + + return ($tags->N == 0) ? false : true; + } + + function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0) + { + $lists = new Profile_list(); + $subs = new Profile_tag_subscription(); + + $lists->joinAdd($subs); + #@fixme: postgres (round(date_part('epoch', my_date))) + $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"'); + + $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id); + + if ($since_id>0) { + $lists->whereAdd('cursor > '.$since_id); + } + + if ($max_id>0) { + $lists->whereAdd('cursor <= '.$max_id); + } + + if($offset>=0 && !is_null($limit)) { + $lists->limit($offset, $limit); + } + + $lists->orderBy('"cursor" DESC'); + $lists->find(); + + return $lists; + } + /** * Request to join the given group. * May throw exceptions on failure. @@ -358,6 +535,31 @@ class Profile extends Memcached_DataObject return new ArrayWrapper($profiles); } + function getTaggedSubscribers($tag) + { + $qry = + 'SELECT profile.* ' . + 'FROM profile JOIN (subscription, profile_tag, profile_list) ' . + 'ON profile.id = subscription.subscriber ' . + 'AND profile.id = profile_tag.tagged ' . + 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' . + 'WHERE subscription.subscribed = %d ' . + 'AND subscription.subscribed != subscription.subscriber ' . + 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' . + 'AND profile_list.private = false ' . + 'ORDER BY subscription.created DESC'; + + $profile = new Profile(); + $tagged = array(); + + $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag)); + + while ($profile->fetch()) { + $tagged[] = clone($profile); + } + return $tagged; + } + /** * Get pending subscribers, who have not yet been approved. * diff --git a/classes/Profile_list.php b/classes/Profile_list.php new file mode 100644 index 0000000000..0bdf12e0e3 --- /dev/null +++ b/classes/Profile_list.php @@ -0,0 +1,926 @@ +. + * + * @category Notices + * @package StatusNet + * @author Shashi Gowda + * @license GNU Affero General Public License http://www.gnu.org/licenses/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +/** + * Table Definition for profile_list + */ +require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; + +class Profile_list extends Memcached_DataObject +{ + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'profile_list'; // table name + public $id; // int(4) primary_key not_null + public $tagger; // int(4) + public $tag; // varchar(64) + public $description; // text + public $private; // tinyint(1) + public $created; // datetime not_null default_0000-00-00%2000%3A00%3A00 + public $modified; // timestamp not_null default_CURRENT_TIMESTAMP + public $uri; // varchar(255) unique_key + public $mainpage; // varchar(255) + public $tagged_count; // smallint + public $subscriber_count; // smallint + + /* Static get */ + function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('Profile_list',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE + + /** + * return a profile_list record, given its tag and tagger. + * + * @param array $kv ideally array('tag' => $tag, 'tagger' => $tagger) + * + * @return Profile_list a Profile_list object with the given tag and tagger. + */ + + function pkeyGet($kv) + { + return Memcached_DataObject::pkeyGet('Profile_list', $kv); + } + + /** + * get the tagger of this profile_list object + * + * @return Profile the tagger + */ + + function getTagger() + { + return Profile::staticGet('id', $this->tagger); + } + + /** + * return a string to identify this + * profile_list in the user interface etc. + * + * @return String + */ + + function getBestName() + { + return $this->tag; + } + + /** + * return a uri string for this profile_list + * + * @return String uri + */ + + function getUri() + { + $uri = null; + if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) { + if (!empty($this->uri)) { + $uri = $this->uri; + } else { + $uri = common_local_url('profiletagbyid', + array('id' => $this->id, 'tagger_id' => $this->tagger)); + } + } + Event::handle('EndProfiletagGetUri', array($this, &$uri)); + return $uri; + } + + /** + * return a url to the homepage of this item + * + * @return String home url + */ + + function homeUrl() + { + $url = null; + if (Event::handle('StartUserPeopletagHomeUrl', array($this, &$url))) { + // normally stored in mainpage, but older ones may be null + if (!empty($this->mainpage)) { + $url = $this->mainpage; + } else { + $url = common_local_url('showprofiletag', + array('tagger' => $this->getTagger()->nickname, + 'tag' => $this->tag)); + } + } + Event::handle('EndUserPeopletagHomeUrl', array($this, &$url)); + return $url; + } + + /** + * return an immutable url for this object + * + * @return String permalink + */ + + function permalink() + { + $url = null; + if (Event::handle('StartProfiletagPermalink', array($this, &$url))) { + $url = common_local_url('profiletagbyid', + array('id' => $this->id)); + } + Event::handle('EndProfiletagPermalink', array($this, &$url)); + return $url; + } + + /** + * Query notices by users associated with this tag, + * but first check the cache before hitting the DB. + * + * @param integer $offset offset + * @param integer $limit maximum no of results + * @param integer $since_id=null since this id + * @param integer $max_id=null maximum id in result + * + * @return Notice the query + */ + + function getNotices($offset, $limit, $since_id=null, $max_id=null) + { + $stream = new PeopletagNoticeStream($this); + + return $stream->getNotices($offset, $limit, $since_id, $max_id); + } + + /** + * Query notices by users associated with this tag from the database. + * + * @param integer $offset offset + * @param integer $limit maximum no of results + * @param integer $since_id=null since this id + * @param integer $max_id=null maximum id in result + * + * @return array array of notice ids. + */ + + function _streamDirect($offset, $limit, $since_id, $max_id) + { + $inbox = new Profile_tag_inbox(); + + $inbox->profile_tag_id = $this->id; + + $inbox->selectAdd(); + $inbox->selectAdd('notice_id'); + + if ($since_id != 0) { + $inbox->whereAdd('notice_id > ' . $since_id); + } + + if ($max_id != 0) { + $inbox->whereAdd('notice_id <= ' . $max_id); + } + + $inbox->orderBy('notice_id DESC'); + + if (!is_null($offset)) { + $inbox->limit($offset, $limit); + } + + $ids = array(); + + if ($inbox->find()) { + while ($inbox->fetch()) { + $ids[] = $inbox->notice_id; + } + } + + return $ids; + } + + /** + * Get subscribers (local and remote) to this people tag + * Order by reverse chronology + * + * @param integer $offset offset + * @param integer $limit maximum no of results + * @param integer $since_id=null since unix timestamp + * @param integer $upto=null maximum unix timestamp when subscription was made + * + * @return Profile results + */ + + function getSubscribers($offset=0, $limit=null, $since=0, $upto=0) + { + $subs = new Profile(); + $sub = new Profile_tag_subscription(); + $sub->profile_tag_id = $this->id; + + $subs->joinAdd($sub); + $subs->selectAdd('unix_timestamp(profile_tag_subscription.' . + 'created) as "cursor"'); + + if ($since != 0) { + $subs->whereAdd('cursor > ' . $since); + } + + if ($upto != 0) { + $subs->whereAdd('cursor <= ' . $upto); + } + + if ($limit != null) { + $subs->limit($offset, $limit); + } + + $subs->orderBy('profile_tag_subscription.created DESC'); + $subs->find(); + + return $subs; + } + + /** + * Get all and only local subscribers to this people tag + * used for distributing notices to user inboxes. + * + * @return array ids of users + */ + + function getUserSubscribers() + { + // XXX: cache this + + $user = new User(); + if(common_config('db','quote_identifiers')) + $user_table = '"user"'; + else $user_table = 'user'; + + $qry = + 'SELECT id ' . + 'FROM '. $user_table .' JOIN profile_tag_subscription '. + 'ON '. $user_table .'.id = profile_tag_subscription.profile_id ' . + 'WHERE profile_tag_subscription.profile_tag_id = %d '; + + $user->query(sprintf($qry, $this->id)); + + $ids = array(); + + while ($user->fetch()) { + $ids[] = $user->id; + } + + $user->free(); + + return $ids; + } + + /** + * Check to see if a given profile has + * subscribed to this people tag's timeline + * + * @param mixed $id User or Profile object or integer id + * + * @return boolean subscription status + */ + + function hasSubscriber($id) + { + if (!is_numeric($id)) { + $id = $id->id; + } + + $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id, + 'profile_id' => $id)); + return !empty($sub); + } + + /** + * Get profiles tagged with this people tag, + * include modified timestamp as a "cursor" field + * order by descending order of modified time + * + * @param integer $offset offset + * @param integer $limit maximum no of results + * @param integer $since_id=null since unix timestamp + * @param integer $upto=null maximum unix timestamp when subscription was made + * + * @return Profile results + */ + + function getTagged($offset=0, $limit=null, $since=0, $upto=0) + { + $tagged = new Profile(); + $tagged->joinAdd(array('id', 'profile_tag:tagged')); + + #@fixme: postgres + $tagged->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"'); + $tagged->whereAdd('profile_tag.tagger = '.$this->tagger); + $tagged->whereAdd("profile_tag.tag = '{$this->tag}'"); + + if ($since != 0) { + $tagged->whereAdd('cursor > ' . $since); + } + + if ($upto != 0) { + $tagged->whereAdd('cursor <= ' . $upto); + } + + if ($limit != null) { + $tagged->limit($offset, $limit); + } + + $tagged->orderBy('profile_tag.modified DESC'); + $tagged->find(); + + return $tagged; + } + + /** + * Gracefully delete one or many people tags + * along with their members and subscriptions data + * + * @return boolean success + */ + + function delete() + { + // force delete one item at a time. + if (empty($this->id)) { + $this->find(); + while ($this->fetch()) { + $this->delete(); + } + } + + Profile_tag::cleanup($this); + Profile_tag_subscription::cleanup($this); + + return parent::delete(); + } + + /** + * Update a people tag gracefully + * also change "tag" fields in profile_tag table + * + * @param Profile_list $orig Object's original form + * + * @return boolean success + */ + + function update($orig=null) + { + $result = true; + + if (!is_object($orig) && !$orig instanceof Profile_list) { + parent::update($orig); + } + + // if original tag was different + // check to see if the new tag already exists + // if not, rename the tag correctly + if($orig->tag != $this->tag || $orig->tagger != $this->tagger) { + $existing = Profile_list::getByTaggerAndTag($this->tagger, $this->tag); + if(!empty($existing)) { + throw new ServerException(_('The tag you are trying to rename ' . + 'to already exists.')); + } + // move the tag + // XXX: allow OStatus plugin to send out profile tag + $result = Profile_tag::moveTag($orig, $this); + } + parent::update($orig); + return $result; + } + + /** + * return an xml string representing this people tag + * as the author of an atom feed + * + * @return string atom author element + */ + + function asAtomAuthor() + { + $xs = new XMLStringer(true); + + $tagger = $this->getTagger(); + $xs->elementStart('author'); + $xs->element('name', null, '@' . $tagger->nickname . '/' . $this->tag); + $xs->element('uri', null, $this->permalink()); + $xs->elementEnd('author'); + + return $xs->getString(); + } + + /** + * return an xml string to represent this people tag + * as the subject of an activitystreams feed. + * + * @return string activitystreams subject + */ + + function asActivitySubject() + { + return $this->asActivityNoun('subject'); + } + + /** + * return an xml string to represent this people tag + * as a noun in an activitystreams feed. + * + * @param string $element the xml tag + * + * @return string activitystreams noun + */ + + function asActivityNoun($element) + { + $noun = ActivityObject::fromPeopletag($this); + return $noun->asString('activity:' . $element); + } + + /** + * get the cached number of profiles tagged with this + * people tag, re-count if the argument is true. + * + * @param boolean $recount whether to ignore cache + * + * @return integer count + */ + + function taggedCount($recount=false) + { + if (!$recount) { + return $this->tagged_count; + } + + $tags = new Profile_tag(); + $tags->tag = $this->tag; + $tags->tagger = $this->tagger; + $orig = clone($this); + $this->tagged_count = (int) $tags->count('distinct tagged'); + $this->update($orig); + + return $this->tagged_count; + } + + /** + * get the cached number of profiles subscribed to this + * people tag, re-count if the argument is true. + * + * @param boolean $recount whether to ignore cache + * + * @return integer count + */ + + function subscriberCount($recount=false) + { + if ($recount) { + return $this->subscriber_count; + } + + $sub = new Profile_tag_subscription(); + $sub->profile_tag_id = $this->id; + $orig = clone($this); + $this->subscriber_count = (int) $sub->count('distinct profile_id'); + $this->update($orig); + + return $this->subscriber_count; + } + + /** + * get the Profile_list object by the + * given tagger and with given tag + * + * @param integer $tagger the id of the creator profile + * @param integer $tag the tag + * + * @return integer count + */ + + static function getByTaggerAndTag($tagger, $tag) + { + $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag)); + return $ptag; + } + + /** + * create a profile_list record for a tag, tagger pair + * if it doesn't exist, return it. + * + * @param integer $tagger the tagger + * @param string $tag the tag + * @param string $description description + * @param boolean $private protected or not + * + * @return Profile_list the people tag object + */ + + static function ensureTag($tagger, $tag, $description=null, $private=false) + { + $ptag = Profile_list::getByTaggerAndTag($tagger, $tag); + + if(empty($ptag->id)) { + $args = array( + 'tag' => $tag, + 'tagger' => $tagger, + 'description' => $description, + 'private' => $private + ); + + $new_tag = Profile_list::saveNew($args); + + return $new_tag; + } + return $ptag; + } + + /** + * get the maximum number of characters + * that can be used in the description of + * a people tag. + * + * determined by $config['peopletag']['desclimit'] + * if not set, falls back to $config['site']['textlimit'] + * + * @return integer maximum number of characters + */ + + static function maxDescription() + { + $desclimit = common_config('peopletag', 'desclimit'); + // null => use global limit (distinct from 0!) + if (is_null($desclimit)) { + $desclimit = common_config('site', 'textlimit'); + } + return $desclimit; + } + + /** + * check if the length of given text exceeds + * character limit. + * + * @param string $desc the description + * + * @return boolean is the descripition too long? + */ + + static function descriptionTooLong($desc) + { + $desclimit = self::maxDescription(); + return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit)); + } + + /** + * save a new people tag, this should be always used + * since it makes uri, homeurl, created and modified + * timestamps and performs checks. + * + * @param array $fields an array with fields and their values + * + * @return mixed Profile_list on success, false on fail + */ + static function saveNew($fields) { + + extract($fields); + + $ptag = new Profile_list(); + + $ptag->query('BEGIN'); + + if (empty($tagger)) { + throw new Exception(_('No tagger specified.')); + } + + if (empty($tag)) { + throw new Exception(_('No tag specified.')); + } + + if (empty($mainpage)) { + $mainpage = null; + } + + if (empty($uri)) { + // fill in later... + $uri = null; + } + + if (empty($mainpage)) { + $mainpage = null; + } + + if (empty($description)) { + $description = null; + } + + if (empty($private)) { + $private = false; + } + + $ptag->tagger = $tagger; + $ptag->tag = $tag; + $ptag->description = $description; + $ptag->private = $private; + $ptag->uri = $uri; + $ptag->mainpage = $mainpage; + $ptag->created = common_sql_now(); + $ptag->modified = common_sql_now(); + + $result = $ptag->insert(); + + if (!$result) { + common_log_db_error($ptag, 'INSERT', __FILE__); + throw new ServerException(_('Could not create profile tag.')); + } + + if (!isset($uri) || empty($uri)) { + $orig = clone($ptag); + $ptag->uri = common_local_url('profiletagbyid', array('id' => $ptag->id, 'tagger_id' => $ptag->tagger)); + $result = $ptag->update($orig); + if (!$result) { + common_log_db_error($ptag, 'UPDATE', __FILE__); + throw new ServerException(_('Could not set profile tag URI.')); + } + } + + if (!isset($mainpage) || empty($mainpage)) { + $orig = clone($ptag); + $user = User::staticGet('id', $ptag->tagger); + if(!empty($user)) { + $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'tagger' => $user->nickname)); + } else { + $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works + } + + $result = $ptag->update($orig); + if (!$result) { + common_log_db_error($ptag, 'UPDATE', __FILE__); + throw new ServerException(_('Could not set profile tag mainpage.')); + } + } + return $ptag; + } + + /** + * get all items at given cursor position for api + * + * @param callback $fn a function that takes the following arguments in order: + * $offset, $limit, $since_id, $max_id + * and returns a Profile_list object after making the DB query + * @param array $args arguments required for $fn + * @param integer $cursor the cursor + * @param integer $count max. number of results + * + * Algorithm: + * - if cursor is 0, return empty list + * - if cursor is -1, get first 21 items, next_cursor = 20th prev_cursor = 0 + * - if cursor is +ve get 22 consecutive items before starting at cursor + * - return items[1..20] if items[0] == cursor else return items[0..21] + * - prev_cursor = items[1] + * - next_cursor = id of the last item being returned + * + * - if cursor is -ve get 22 consecutive items after cursor starting at cursor + * - return items[1..20] + * + * @returns array (array (mixed items), int next_cursor, int previous_cursor) + */ + + // XXX: This should be in Memcached_DataObject... eventually. + + static function getAtCursor($fn, $args, $cursor, $count=20) + { + $items = array(); + + $since_id = 0; + $max_id = 0; + $next_cursor = 0; + $prev_cursor = 0; + + if($cursor > 0) { + // if cursor is +ve fetch $count+2 items before cursor starting at cursor + $max_id = $cursor; + $fn_args = array_merge($args, array(0, $count+2, 0, $max_id)); + $list = call_user_func_array($fn, $fn_args); + while($list->fetch()) { + $items[] = clone($list); + } + + if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) || + $items[0]->id == $cursor) { + array_shift($items); + $prev_cursor = isset($items[0]->cursor) ? + -$items[0]->cursor : -$items[0]->id; + } else { + if (count($items) > $count+1) { + array_shift($items); + } + // this means the cursor item has been deleted, check to see if there are more + $fn_args = array_merge($args, array(0, 1, $cursor)); + $more = call_user_func($fn, $fn_args); + if (!$more->fetch() || empty($more)) { + // no more items. + $prev_cursor = 0; + } else { + $prev_cursor = isset($items[0]->cursor) ? + -$items[0]->cursor : -$items[0]->id; + } + } + + if (count($items)==$count+1) { + // this means there is a next page. + $next = array_pop($items); + $next_cursor = isset($next->cursor) ? + $items[$count-1]->cursor : $items[$count-1]->id; + } + + } else if($cursor < -1) { + // if cursor is -ve fetch $count+2 items created after -$cursor-1 + $cursor = abs($cursor); + $since_id = $cursor-1; + + $fn_args = array_merge($args, array(0, $count+2, $since_id)); + $list = call_user_func_array($fn, $fn_args); + while($list->fetch()) { + $items[] = clone($list); + } + + $end = count($items)-1; + if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) || + $items[$end]->id == $cursor) { + array_pop($items); + $next_cursor = isset($items[$end-1]->cursor) ? + $items[$end-1]->cursor : $items[$end-1]->id; + } else { + $next_cursor = isset($items[$end]->cursor) ? + $items[$end]->cursor : $items[$end]->id; + if ($end > $count) array_pop($items); // excess item. + + // check if there are more items for next page + $fn_args = array_merge($args, array(0, 1, 0, $cursor)); + $more = call_user_func_array($fn, $fn_args); + if (!$more->fetch() || empty($more)) { + $next_cursor = 0; + } + } + + if (count($items) == $count+1) { + // this means there is a previous page. + $prev = array_shift($items); + $prev_cursor = isset($prev->cursor) ? + -$items[0]->cursor : -$items[0]->id; + } + } else if($cursor == -1) { + $fn_args = array_merge($args, array(0, $count+1)); + $list = call_user_func_array($fn, $fn_args); + + while($list->fetch()) { + $items[] = clone($list); + } + + if (count($items)==$count+1) { + $next = array_pop($items); + if(isset($next->cursor)) { + $next_cursor = $items[$count-1]->cursor; + } else { + $next_cursor = $items[$count-1]->id; + } + } + + } + return array($items, $next_cursor, $prev_cursor); + } + + /** + * save a collection of people tags into the cache + * + * @param string $ckey cache key + * @param Profile_list &$tag the results to store + * @param integer $offset offset for slicing results + * @param integer $limit maximum number of results + * + * @return boolean success + */ + + static function setCache($ckey, &$tag, $offset=0, $limit=null) { + $cache = Cache::instance(); + if (empty($cache)) { + return false; + } + $str = ''; + $tags = array(); + while ($tag->fetch()) { + $str .= $tag->tagger . ':' . $tag->tag . ';'; + $tags[] = clone($tag); + } + $str = substr($str, 0, -1); + if ($offset>=0 && !is_null($limit)) { + $tags = array_slice($tags, $offset, $limit); + } + + $tag = new ArrayWrapper($tags); + + return self::cacheSet($ckey, $str); + } + + /** + * get people tags from the cache + * + * @param string $ckey cache key + * @param integer $offset offset for slicing + * @param integer $limit limit + * + * @return Profile_list results + */ + + static function getCached($ckey, $offset=0, $limit=null) { + + $keys_str = self::cacheGet($ckey); + if ($keys_str === false) { + return false; + } + + $pairs = explode(';', $keys_str); + $keys = array(); + foreach ($pairs as $pair) { + $keys[] = explode(':', $pair); + } + + if ($offset>=0 && !is_null($limit)) { + $keys = array_slice($keys, $offset, $limit); + } + return self::getByKeys($keys); + } + + /** + * get Profile_list objects from the database + * given their (tag, tagger) key pairs. + * + * @param array $keys array of array(tagger, tag) + * + * @return Profile_list results + */ + + static function getByKeys($keys) { + $cache = Cache::instance(); + + if (!empty($cache)) { + $tags = array(); + + foreach ($keys as $key) { + $t = Profile_list::getByTaggerAndTag($key[0], $key[1]); + if (!empty($t)) { + $tags[] = $t; + } + } + return new ArrayWrapper($tags); + } else { + $tag = new Profile_list(); + if (empty($keys)) { + //if no IDs requested, just return the tag object + return $tag; + } + + $pairs = array(); + foreach ($keys as $key) { + $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")'; + } + + $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')'); + + $tag->find(); + + $temp = array(); + + while ($tag->fetch()) { + $temp[$tag->tagger.'-'.$tag->tag] = clone($tag); + } + + $wrapped = array(); + + foreach ($keys as $key) { + $id = $key[0].'-'.$key[1]; + if (array_key_exists($id, $temp)) { + $wrapped[] = $temp[$id]; + } + } + + return new ArrayWrapper($wrapped); + } + } +} diff --git a/classes/Profile_tag.php b/classes/Profile_tag.php index bd45ce0b45..eb583c98fe 100644 --- a/classes/Profile_tag.php +++ b/classes/Profile_tag.php @@ -22,31 +22,91 @@ class Profile_tag extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - static function getTags($tagger, $tagged) { - $tags = array(); + function pkeyGet($kv) { + return Memcached_DataObject::pkeyGet('Profile_tag', $kv); + } - // XXX: store this in memcached + function links() + { + return array('tagger,tag' => 'profile_list:tagger,tag'); + } - $profile_tag = new Profile_tag(); - $profile_tag->tagger = $tagger; - $profile_tag->tagged = $tagged; + function getMeta() + { + return Profile_list::pkeyGet(array('tagger' => $this->tagger, 'tag' => $this->tag)); + } - $profile_tag->find(); + static function getTags($tagger, $tagged, $auth_user=null) { - while ($profile_tag->fetch()) { - $tags[] = $profile_tag->tag; + $profile_list = new Profile_list(); + $include_priv = 1; + + if (!($auth_user instanceof User || + $auth_user instanceof Profile) || + ($auth_user->id !== $tagger)) { + + $profile_list->private = false; + $include_priv = 0; } - $profile_tag->free(); + $key = sprintf('profile_tag:tagger_tagged_privacy:%d-%d-%d', $tagger, $tagged, $include_priv); + $tags = Profile_list::getCached($key); + if ($tags !== false) { + return $tags; + } + + $profile_tag = new Profile_tag(); + $profile_list->tagger = $tagger; + $profile_tag->tagged = $tagged; + + $profile_list->selectAdd(); + + // only fetch id, tag, mainpage and + // private hoping this will be faster + $profile_list->selectAdd('profile_list.id, ' . + 'profile_list.tag, ' . + 'profile_list.mainpage, ' . + 'profile_list.private'); + $profile_list->joinAdd($profile_tag); + $profile_list->find(); + + Profile_list::setCache($key, $profile_list); + + return $profile_list; + } + + static function getTagsArray($tagger, $tagged, $auth_user_id=null) + { + $ptag = new Profile_tag(); + $ptag->tagger = $tagger; + $ptag->tagged = $tagged; + + if ($tagger != $auth_user_id) { + $list = new Profile_list(); + $list->private = false; + $ptag->joinAdd($list); + $ptag->selectAdd(); + $ptag->selectAdd('profile_tag.tag'); + } + + $tags = array(); + $ptag->find(); + while ($ptag->fetch()) { + $tags[] = $ptag->tag; + } + $ptag->free(); return $tags; } - static function setTags($tagger, $tagged, $newtags) { - $newtags = array_unique($newtags); - $oldtags = Profile_tag::getTags($tagger, $tagged); + static function setTags($tagger, $tagged, $newtags, $privacy=array()) { - // Delete stuff that's old that not in new + $newtags = array_unique($newtags); + $oldtags = self::getTagsArray($tagger, $tagged, $tagger); + + $ptag = new Profile_tag(); + + // Delete stuff that's in old and not in new $to_delete = array_diff($oldtags, $newtags); @@ -54,33 +114,161 @@ class Profile_tag extends Memcached_DataObject $to_insert = array_diff($newtags, $oldtags); - $profile_tag = new Profile_tag(); - - $profile_tag->tagger = $tagger; - $profile_tag->tagged = $tagged; - - $profile_tag->query('BEGIN'); - foreach ($to_delete as $deltag) { - $profile_tag->tag = $deltag; - $result = $profile_tag->delete(); - if (!$result) { - common_log_db_error($profile_tag, 'DELETE', __FILE__); - return false; - } + self::unTag($tagger, $tagged, $deltag); } foreach ($to_insert as $instag) { - $profile_tag->tag = $instag; - $result = $profile_tag->insert(); - if (!$result) { - common_log_db_error($profile_tag, 'INSERT', __FILE__); - return false; - } + $private = isset($privacy[$instag]) ? $privacy[$instag] : false; + self::setTag($tagger, $tagged, $instag, null, $private); + } + return true; + } + + # set a single tag + static function setTag($tagger, $tagged, $tag, $desc=null, $private=false) { + + $ptag = Profile_tag::pkeyGet(array('tagger' => $tagger, + 'tagged' => $tagged, + 'tag' => $tag)); + + # if tag already exists, return it + if(!empty($ptag)) { + return $ptag; } - $profile_tag->query('COMMIT'); + $tagger_profile = Profile::staticGet('id', $tagger); + $tagged_profile = Profile::staticGet('id', $tagged); + if (Event::handle('StartTagProfile', array($tagger_profile, $tagged_profile, $tag))) { + + if (!$tagger_profile->canTag($tagged_profile)) { + throw new ClientException(_('You cannot tag this user.')); + return false; + } + + $tags = new Profile_list(); + $tags->tagger = $tagger; + $count = (int) $tags->count('distinct tag'); + + if ($count >= common_config('peopletag', 'maxtags')) { + throw new ClientException(sprintf(_('You already have created %d or more tags ' . + 'which is the maximum allowed number of tags. ' . + 'Try using or deleting some existing tags.'), + common_config('peopletag', 'maxtags'))); + return false; + } + + $plist = new Profile_list(); + $plist->query('BEGIN'); + + $profile_list = Profile_list::ensureTag($tagger, $tag, $desc, $private); + + if ($profile_list->taggedCount() >= common_config('peopletag', 'maxpeople')) { + throw new ClientException(sprintf(_('You already have %d or more people tagged %s ' . + 'which is the maximum allowed number.' . + 'Try untagging others with the same tag first.'), + common_config('peopletag', 'maxpeople'), $tag)); + return false; + } + + $newtag = new Profile_tag(); + + $newtag->tagger = $tagger; + $newtag->tagged = $tagged; + $newtag->tag = $tag; + + $result = $newtag->insert(); + + + if (!$result) { + common_log_db_error($newtag, 'INSERT', __FILE__); + return false; + } + + try { + $plist->query('COMMIT'); + Event::handle('EndTagProfile', array($newtag)); + } catch (Exception $e) { + $newtag->delete(); + $profile_list->delete(); + throw $e; + return false; + } + + $profile_list->taggedCount(true); + self::blowCaches($tagger, $tagged); + } + + return $newtag; + } + + static function unTag($tagger, $tagged, $tag) { + $ptag = Profile_tag::pkeyGet(array('tagger' => $tagger, + 'tagged' => $tagged, + 'tag' => $tag)); + if (!$ptag) { + return true; + } + + if (Event::handle('StartUntagProfile', array($ptag))) { + $orig = clone($ptag); + $result = $ptag->delete(); + if (!$result) { + common_log_db_error($this, 'DELETE', __FILE__); + return false; + } + Event::handle('EndUntagProfile', array($orig)); + if ($result) { + $profile_list = Profile_list::pkeyGet(array('tag' => $tag, 'tagger' => $tagger)); + $profile_list->taggedCount(true); + self::blowCaches($tagger, $tagged); + return true; + } + return false; + } + } + + // @fixme: move this to Profile_list? + static function cleanup($profile_list) { + $ptag = new Profile_tag(); + $ptag->tagger = $profile_list->tagger; + $ptag->tag = $profile_list->tag; + $ptag->find(); + + while($ptag->fetch()) { + if (Event::handle('StartUntagProfile', array($ptag))) { + $orig = clone($ptag); + $result = $ptag->delete(); + if (!$result) { + common_log_db_error($this, 'DELETE', __FILE__); + } + Event::handle('EndUntagProfile', array($orig)); + } + } + } + + // move a tag! + static function moveTag($orig, $new) { + $tags = new Profile_tag(); + $qry = 'UPDATE profile_tag SET ' . + 'tag = "%s", tagger = "%s" ' . + 'WHERE tag = "%s" ' . + 'AND tagger = "%s"'; + $result = $tags->query(sprintf($qry, $new->tag, $new->tagger, + $orig->tag, $orig->tagger)); + + if (!$result) { + common_log_db_error($tags, 'UPDATE', __FILE__); + return false; + } + return true; + } + + static function blowCaches($tagger, $tagged) { + foreach (array(0, 1) as $perm) { + self::blow(sprintf('profile_tag:tagger_tagged_privacy:%d-%d-%d', $tagger, $tagged, $perm)); + } return true; } @@ -96,6 +284,6 @@ class Profile_tag extends Memcached_DataObject while ($profile->fetch()) { $tagged[] = clone($profile); } - return $tagged; + return true; } } diff --git a/classes/Profile_tag_inbox.php b/classes/Profile_tag_inbox.php new file mode 100644 index 0000000000..dd517b3088 --- /dev/null +++ b/classes/Profile_tag_inbox.php @@ -0,0 +1,27 @@ +private) { + return false; + } + + if (Event::handle('StartSubscribePeopletag', array($peopletag, $profile))) { + $args = array('profile_tag_id' => $peopletag->id, + 'profile_id' => $profile->id); + $existing = Profile_tag_subscription::pkeyGet($args); + if(!empty($existing)) { + return $existing; + } + + $sub = new Profile_tag_subscription(); + $sub->profile_tag_id = $peopletag->id; + $sub->profile_id = $profile->id; + $sub->created = common_sql_now(); + + $result = $sub->insert(); + + if (!$result) { + common_log_db_error($sub, 'INSERT', __FILE__); + throw new Exception(_("Adding people tag subscription failed.")); + } + + $ptag = Profile_list::staticGet('id', $peopletag->id); + $ptag->subscriberCount(true); + + Event::handle('EndSubscribePeopletag', array($peopletag, $profile)); + return $ptag; + } + } + + static function remove($peopletag, $profile) + { + $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $peopletag->id, + 'profile_id' => $profile->id)); + + if (empty($sub)) { + // silence is golden? + return true; + } + + if (Event::handle('StartUnsubscribePeopletag', array($peopletag, $profile))) { + $result = $sub->delete(); + + if (!$result) { + common_log_db_error($sub, 'DELETE', __FILE__); + throw new Exception(_("Removing people tag subscription failed.")); + } + + $peopletag->subscriberCount(true); + + Event::handle('EndUnsubscribePeopletag', array($peopletag, $profile)); + return true; + } + } + + // called if a tag gets deleted / made private + static function cleanup($profile_list) { + $subs = new self(); + $subs->profile_tag_id = $profile_list->id; + $subs->find(); + + while($subs->fetch()) { + $profile = Profile::staticGet('id', $subs->profile_id); + Event::handle('StartUnsubscribePeopletag', array($profile_list, $profile)); + // Delete anyway + $subs->delete(); + Event::handle('StartUnsubscribePeopletag', array($profile_list, $profile)); + } + } +} diff --git a/classes/User.php b/classes/User.php index 6ff856bbaa..7d556c18c2 100644 --- a/classes/User.php +++ b/classes/User.php @@ -532,12 +532,12 @@ class User extends Memcached_DataObject function getSelfTags() { - return Profile_tag::getTags($this->id, $this->id); + return Profile_tag::getTagsArray($this->id, $this->id, $this->id); } - function setSelfTags($newtags) + function setSelfTags($newtags, $privacy) { - return Profile_tag::setTags($this->id, $this->id, $newtags); + return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy); } function block($other) diff --git a/classes/statusnet.ini b/classes/statusnet.ini index 78e07b0407..05f339ca5a 100644 --- a/classes/statusnet.ini +++ b/classes/statusnet.ini @@ -462,6 +462,43 @@ tagger = K tagged = K tag = K +[profile_list] +id = 129 +tagger = 129 +tag = 130 +description = 34 +private = 17 +created = 142 +modified = 384 +uri = 130 +mainpage = 130 +tagged_count = 129 +subscriber_count = 129 + +[profile_list__keys] +id = U +tagger = K +tag = K + +[profile_tag_inbox] +profile_tag_id = 129 +notice_id = 129 +created = 142 + +[profile_tag_inbox__keys] +profile_tag_id = K +notice_id = K + +[profile_tag_subscription] +profile_tag_id = 129 +profile_id = 129 +created = 142 +modified = 384 + +[profile_tag_subscription__keys] +profile_tag_id = K +profile_id = K + [queue_item] id = 129 frame = 194 diff --git a/classes/statusnet.links.ini b/classes/statusnet.links.ini index b9dd5af0c9..28bf03fd45 100644 --- a/classes/statusnet.links.ini +++ b/classes/statusnet.links.ini @@ -55,3 +55,23 @@ file_id = file:id file_id = file:id post_id = notice:id +[profile_list] +tagger = profile:id + +[profile_tag] +tagger = profile:id +tagged = profile:id +; in class definition: +;tag,tagger = profile_list:tag,tagger + +[profile_list] +tagger = profile:id + +[profile_tag_inbox] +profile_tag_id = profile_list:id +notice_id = notice:id + +[profile_tag_subscription] +profile_tag_id = profile_list:id +profile_id = profile:id + diff --git a/config.php.sample b/config.php.sample index 5481ca539e..5378ad973d 100644 --- a/config.php.sample +++ b/config.php.sample @@ -182,6 +182,29 @@ $config['sphinx']['port'] = 3312; // $config['memcached']['server'] = 'localhost'; // $config['memcached']['port'] = 11211; +// People tags +// Maximum number of tags a user can create: +// $config['peopletag']['maxtags'] = 100; +// Maximum number of people can have the same tag by the same user +// $config['peopletag']['maxpeople'] = 500; +// Types of users one can tag. +// Everyone. +// $config['peopletag']['allow_tagging']['all'] = true; +// Local only. +// $config['peopletag']['allow_tagging']['local'] = true; +// Subscriptions / Subscribers only (including remote) +// $config['peopletag']['allow_tagging']['subs'] = true; +// Remote. +// $config['peopletag']['allow_tagging']['remote'] = true; +// Examples: +// The following set of options allows tagging local users and +// remote subscribers / subscription. +// $config['peopletag']['allow_tagging']['all'] = false; +// $config['peopletag']['allow_tagging']['local'] = true; +// $config['peopletag']['allow_tagging']['subs'] = true; +// Or: +// $config['peopletag']['allow_tagging'] = array('local' => true, 'subs' =>true); + // Disable post-by-email // $config['emailpost']['enabled'] = false; diff --git a/db/095topeopletags.sql b/db/095topeopletags.sql new file mode 100644 index 0000000000..e193b98156 --- /dev/null +++ b/db/095topeopletags.sql @@ -0,0 +1,4 @@ +/* populate people tags metadata */ + +insert into profile_list (tagger, tag, modified, description, private) + select distinct tagger, tag, modified, null, false from profile_tag; diff --git a/db/core.php b/db/core.php index fc3461a7a0..10d8e51b9b 100644 --- a/db/core.php +++ b/db/core.php @@ -610,8 +610,9 @@ $schema['profile_tag'] = array( ), 'primary key' => array('tagger', 'tagged', 'tag'), 'foreign keys' => array( - 'profile_tag_tagger_fkey' => array('user', array('tagger' => 'id')), + 'profile_tag_tagger_fkey' => array('profile', array('tagger' => 'id')), 'profile_tag_tagged_fkey' => array('profile', array('tagged' => 'id')), + 'profile_tag_tag_fkey' => array('profile_list', array('tag' => 'tag')), ), 'indexes' => array( 'profile_tag_modified_idx' => array('modified'), @@ -620,6 +621,76 @@ $schema['profile_tag'] = array( ), ); +$schema['profile_list'] = array( + 'fields' => array( + 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'), + 'tagger' => array('type' => 'int', 'not null' => true, 'description' => 'user making the tag'), + 'tag' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'people tag'), + 'description' => array('type' => 'text', 'description' => 'description of the people tag'), + 'private' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'is this tag private'), + + 'created' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date the tag was added'), + 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date the tag was modified'), + + 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universal identifier'), + 'mainpage' => array('type' => 'varchar', 'length' => 255, 'description' => 'page to link to'), + 'tagged_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of people tagged with this tag by this user'), + 'subscriber_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of subscribers to this tag'), + ), + 'primary key' => array('tagger', 'tag'), + 'unique keys' => array( + 'profile_list_id_key' => array('id') + ), + 'foreign keys' => array( + 'profile_list_tagger_fkey' => array('profile', array('tagger' => 'id')), + ), + 'indexes' => array( + 'profile_list_modified_idx' => array('modified'), + 'profile_list_tag_idx' => array('tag'), + 'profile_list_tagger_tag_idx' => array('tagger', 'tag'), + 'profile_list_tagged_count_idx' => array('tagged_count'), + 'profile_list_subscriber_count_idx' => array('subscriber_count'), + ), +); + +$schema['profile_tag_inbox'] = array( + 'description' => 'Many-many table listing notices associated with people tags.', + 'fields' => array( + 'profile_tag_id' => array('type' => 'int', 'not null' => true, 'description' => 'people tag receiving the message'), + 'notice_id' => array('type' => 'int', 'not null' => true, 'description' => 'notice received'), + 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date the notice was created'), + ), + 'primary key' => array('profile_tag_id', 'notice_id'), + 'foreign keys' => array( + 'profile_tag_inbox_profile_list_id_fkey' => array('profile_list', array('profile_tag_id' => 'id')), + 'profile_tag_inbox_notice_id_fkey' => array('notice', array('notice_id' => 'id')), + ), + 'indexes' => array( + 'profile_tag_inbox_created_idx' => array('created'), + 'profile_tag_inbox_profile_tag_id_idx' => array('profile_tag_id'), + ), +); + +$schema['profile_tag_subscription'] = array( + 'fields' => array( + 'profile_tag_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile_tag'), + 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'), + + 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'), + 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'), + ), + 'primary key' => array('profile_tag_id', 'profile_id'), + 'foreign keys' => array( + 'profile_tag_subscription_profile_list_id_fkey' => array('profile_list', array('profile_tag_id' => 'id')), + 'profile_tag_subscription_profile_id_fkey' => array('profile', array('profile_id' => 'id')), + ), + 'indexes' => array( + // @fixme probably we want a (profile_id, created) index here? + 'profile_tag_subscription_profile_id_idx' => array('profile_id'), + 'profile_tag_subscription_created_idx' => array('created'), + ), +); + $schema['profile_block'] = array( 'fields' => array( 'blocker' => array('type' => 'int', 'not null' => true, 'description' => 'user making the block'), diff --git a/db/statusnet.sql b/db/statusnet.sql index debe6f095c..29a555948b 100644 --- a/db/statusnet.sql +++ b/db/statusnet.sql @@ -403,7 +403,7 @@ create table notice_inbox ( ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; create table profile_tag ( - tagger integer not null comment 'user making the tag' references user (id), + tagger integer not null comment 'user making the tag' references profile (id), tagged integer not null comment 'profile tagged' references profile (id), tag varchar(64) not null comment 'hash tag associated with this notice', modified timestamp comment 'date the tag was added', @@ -414,6 +414,53 @@ create table profile_tag ( index profile_tag_tagged_idx (tagged) ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; +/* people tag metadata */ +create table profile_list ( + id integer auto_increment unique key comment 'unique identifier', + tagger integer not null comment 'user making the tag' references profile (id), + tag varchar(64) not null comment 'hash tag', + description text comment 'description for the tag', + private tinyint(1) default 0 comment 'is this list private', + + created datetime not null comment 'date this record was created', + modified timestamp comment 'date this record was modified', + + uri varchar(255) unique key comment 'universal identifier', + mainpage varchar(255) comment 'page for tag info info to link to', + tagged_count smallint not null default 0 comment 'number of people tagged', + subscriber_count smallint not null default 0 comment 'number of people subscribing', + + constraint primary key (tagger, tag), + index profile_list_tag_idx (tag), + index profile_list_tagged_count_idx (tagged_count), + index profile_list_modified_idx (modified), + index profile_list_subscriber_count_idx (subscriber_count) +) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; + +create table profile_tag_inbox ( + profile_tag_id integer not null comment 'peopletag receiving the message' references profile_tag (id), + notice_id integer not null comment 'notice received' references notice (id), + created datetime not null comment 'date the notice was created', + + constraint primary key (profile_tag_id, notice_id), + index profile_tag_inbox_created_idx (created), + index profile_tag_inbox_notice_id_idx (notice_id) + +) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; + +create table profile_tag_subscription ( + profile_tag_id integer not null comment 'foreign key to profile_tag' references profile_list (id), + + profile_id integer not null comment 'foreign key to profile table' references profile (id), + created datetime not null comment 'date this record was created', + modified timestamp comment 'date this record was modified', + + constraint primary key (profile_tag_id, profile_id), + index profile_tag_subscription_profile_id_idx (profile_id), + index profile_tag_subscription_created_idx (created) + +) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin; + create table profile_block ( blocker integer not null comment 'user making the block' references user (id), blocked integer not null comment 'profile that is blocked' references profile (id), diff --git a/doc-src/tags b/doc-src/tags index 091b147ad3..b2e93aa853 100644 --- a/doc-src/tags +++ b/doc-src/tags @@ -25,20 +25,49 @@ Tagging yourself ---------------- You can also add tags for yourself on your [profile -settings](%%action.profilesettings%%) page. Use single words to +settings](%%action.profilesettings%%) page or by using the edit tags +button on your profile page. Use single words to describe yourself, your experiences and your interest. The tags will become links on your profile page to a list of all the users on the site who use that same tag. It can be a nice way to find people who are related to you geographically or who have a common interest. -Tagging your subscriptions --------------------------- +Tagging others +-------------- -You can also tag your subscriptions, on the subscriptions page. This -makes it easy to organize your subscriptions into groups and sort -through them separately. +You can also tag other users by using the edit tags button next to +their profile. Such tags are called *people tags*. Once you have +created a people tag, you can add or remove users from it using the +tag's edit form. This makes it easy to organize your subscriptions +into groups and sort through them separately. Also, it will let +you create custom lists of people that others can subscribe to. + +You can also send a notice "to the attention of" your subscribers +whom you've marked with a particular tag (note: *not* people who've +marked themselves with that tag). "@#family hello" will send a +notice to all your subscribers you've marked with the tag 'family'. + +Private and public people tags +------------------------------ + +A private people tag is only visible to the creator, it cannot be +subscribed to, but the timeline can be viewed. To create a new +private prepend a '.' to the tag in the tags editing box. To set +an existing public tag as private or vice-versa, go to the tag's +edit page. + +The most used public tags are displayed in the +[public people tag cloud](%%action.publicpeopletagcloud%%). Their +size shows their frequency of use. + +Remote people tags +------------------ + +You can even [tag remote users](%%action.profilesettings%%). Just +enter the remote profile's URI and click on the "Fetch" button to +fetch the profile, you can then add tags and save them. + +Subscribing to the timeline of a people tag on another server also +works. Just copy the URL of the people tag's timeline page to the +[OStatus subscription](%%action.ostatussub%%) form. -You can also send a notice "to the attention of" everyone you've -marked with a particular tag (note: *not* people who've marked -themselves with that tag). "@#family hello" will send a notice to -everyone you've marked with the tag 'family'. \ No newline at end of file diff --git a/js/util.js b/js/util.js index fd3c23fb1a..844a5adb8d 100644 --- a/js/util.js +++ b/js/util.js @@ -476,6 +476,74 @@ var SN = { // StatusNet }); }, + FormProfileSearchXHR: function(form) { + $.ajax({ + type: 'POST', + dataType: 'xml', + url: form.attr('action'), + data: form.serialize() + '&ajax=1', + beforeSend: function(xhr) { + form + .addClass(SN.C.S.Processing) + .find('.submit') + .addClass(SN.C.S.Disabled) + .attr(SN.C.S.Disabled, SN.C.S.Disabled); + }, + error: function (xhr, textStatus, errorThrown) { + alert(errorThrown || textStatus); + }, + success: function(data, textStatus) { + var results_placeholder = $('#profile_search_results'); + if (typeof($('ul', data)[0]) != 'undefined') { + var list = document._importNode($('ul', data)[0], true); + results_placeholder.replaceWith(list); + } + else { + var _error = $('
  • ').append(document._importNode($('p', data)[0], true)); + results_placeholder.html(_error); + } + form + .removeClass(SN.C.S.Processing) + .find('.submit') + .removeClass(SN.C.S.Disabled) + .attr(SN.C.S.Disabled, false); + } + }); + }, + + FormPeopletagsXHR: function(form) { + $.ajax({ + type: 'POST', + dataType: 'xml', + url: form.attr('action'), + data: form.serialize() + '&ajax=1', + beforeSend: function(xhr) { + form.find('.submit') + .addClass(SN.C.S.Processing) + .addClass(SN.C.S.Disabled) + .attr(SN.C.S.Disabled, SN.C.S.Disabled); + }, + error: function (xhr, textStatus, errorThrown) { + alert(errorThrown || textStatus); + }, + success: function(data, textStatus) { + var results_placeholder = form.parents('.entity_tags'); + if (typeof($('.entity_tags', data)[0]) != 'undefined') { + var tags = document._importNode($('.entity_tags', data)[0], true); + $(tags).find('.editable').append($('').closest(".notice-options").addClass("opaque");a.find("button.close").click(function(){$(this).remove();a.removeClass("dialogbox").closest(".notice-options").removeClass("opaque");a.find(".submit_dialogbox").remove();a.find(".submit").show();return false})},NoticeAttachments:function(){$(".notice a.attachment").each(function(){SN.U.NoticeWithAttachment($(this).closest(".notice"))})},NoticeWithAttachment:function(b){if(b.find(".attachment").length===0){return}var a=b.find(".attachment.more");if(a.length>0){$(a[0]).click(function(){var c=$(this);c.addClass(SN.C.S.Processing);$.get(c.attr("href")+"/ajax",null,function(d){c.parent(".entry-content").html($(d).find("#attachment_view .entry-content").html())});return false}).attr("title",SN.msg("showmore_tooltip"))}},NoticeDataAttach:function(b){var a=b.find("input[type=file]");a.change(function(f){b.find(".attach-status").remove();var d=$(this).val();if(!d){return false}var c=$('
    ');c.find("code").text(d);c.find("button").click(function(){c.remove();a.val("");return false});b.append(c);if(typeof this.files=="object"){for(var e=0;eg){f=false}if(f){h(c,function(j){var i=$("").attr("title",e).attr("alt",e).attr("src",j).attr("style","height: 120px");d.find(".attach-status").append(i)})}else{var b=$("
    ").text(e);d.find(".attach-status").append(b)}},NoticeLocationAttach:function(a){var e=a.find("[name=lat]");var k=a.find("[name=lon]");var g=a.find("[name=location_ns]").val();var l=a.find("[name=location_id]").val();var b="";var d=a.find("[name=notice_data-geo]");var c=a.find("[name=notice_data-geo]");var j=a.find("label.notice_data-geo");function f(n){j.attr("title",jQuery.trim(j.text())).removeClass("checked");a.find("[name=lat]").val("");a.find("[name=lon]").val("");a.find("[name=location_ns]").val("");a.find("[name=location_id]").val("");a.find("[name=notice_data-geo]").attr("checked",false);$.cookie(SN.C.S.NoticeDataGeoCookie,"disabled",{path:"/"});if(n){a.find(".geo_status_wrapper").removeClass("success").addClass("error");a.find(".geo_status_wrapper .geo_status").text(n)}else{a.find(".geo_status_wrapper").remove()}}function m(n,o){SN.U.NoticeGeoStatus(a,"Looking up place name...");$.getJSON(n,o,function(p){var q,r;if(typeof(p.location_ns)!="undefined"){a.find("[name=location_ns]").val(p.location_ns);q=p.location_ns}if(typeof(p.location_id)!="undefined"){a.find("[name=location_id]").val(p.location_id);r=p.location_id}if(typeof(p.name)=="undefined"){NLN_text=o.lat+";"+o.lon}else{NLN_text=p.name}SN.U.NoticeGeoStatus(a,NLN_text,o.lat,o.lon,p.url);j.attr("title",NoticeDataGeo_text.ShareDisable+" ("+NLN_text+")");a.find("[name=lat]").val(o.lat);a.find("[name=lon]").val(o.lon);a.find("[name=location_ns]").val(q);a.find("[name=location_id]").val(r);a.find("[name=notice_data-geo]").attr("checked",true);var s={NLat:o.lat,NLon:o.lon,NLNS:q,NLID:r,NLN:NLN_text,NLNU:p.url,NDG:true};$.cookie(SN.C.S.NoticeDataGeoCookie,JSON.stringify(s),{path:"/"})})}if(c.length>0){if($.cookie(SN.C.S.NoticeDataGeoCookie)=="disabled"){c.attr("checked",false)}else{c.attr("checked",true)}var h=a.find(".notice_data-geo_wrap");var i=h.attr("data-api");j.attr("title",j.text());c.change(function(){if(c.attr("checked")===true||$.cookie(SN.C.S.NoticeDataGeoCookie)===null){j.attr("title",NoticeDataGeo_text.ShareDisable).addClass("checked");if($.cookie(SN.C.S.NoticeDataGeoCookie)===null||$.cookie(SN.C.S.NoticeDataGeoCookie)=="disabled"){if(navigator.geolocation){SN.U.NoticeGeoStatus(a,"Requesting location from browser...");navigator.geolocation.getCurrentPosition(function(p){a.find("[name=lat]").val(p.coords.latitude);a.find("[name=lon]").val(p.coords.longitude);var q={lat:p.coords.latitude,lon:p.coords.longitude,token:$("#token").val()};m(i,q)},function(p){switch(p.code){case p.PERMISSION_DENIED:f("Location permission denied.");break;case p.TIMEOUT:f("Location lookup timeout.");break}},{timeout:10000})}else{if(e.length>0&&k.length>0){var n={lat:e,lon:k,token:$("#token").val()};m(i,n)}else{f();c.remove();j.remove()}}}else{var o=JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));a.find("[name=lat]").val(o.NLat);a.find("[name=lon]").val(o.NLon);a.find("[name=location_ns]").val(o.NLNS);a.find("[name=location_id]").val(o.NLID);a.find("[name=notice_data-geo]").attr("checked",o.NDG);SN.U.NoticeGeoStatus(a,o.NLN,o.NLat,o.NLon,o.NLNU);j.attr("title",NoticeDataGeo_text.ShareDisable+" ("+o.NLN+")").addClass("checked")}}else{f()}}).change()}},NoticeGeoStatus:function(e,a,f,g,c){var h=e.find(".geo_status_wrapper");if(h.length==0){h=$('
    ');h.find("button.close").click(function(){e.find("[name=notice_data-geo]").removeAttr("checked").change();return false});e.append(h)}var b;if(c){b=$("").attr("href",c)}else{b=$("")}b.text(a);if(f||g){var d=f+";"+g;b.attr("title",d);if(!a){b.text(d)}}h.find(".geo_status").empty().append(b)},NewDirectMessage:function(){NDM=$(".entity_send-a-message a");NDM.attr({href:NDM.attr("href")+"&ajax=1"});NDM.bind("click",function(){var a=$(".entity_send-a-message form");if(a.length===0){$(this).addClass(SN.C.S.Processing);$.get(NDM.attr("href"),null,function(b){$(".entity_send-a-message").append(document._importNode($("form",b)[0],true));a=$(".entity_send-a-message .form_notice");SN.U.FormNoticeXHR(a);SN.U.FormNoticeEnhancements(a);a.append('');$(".entity_send-a-message button").click(function(){a.hide();return false});NDM.removeClass(SN.C.S.Processing)})}else{a.show();$(".entity_send-a-message textarea").focus()}return false})},GetFullYear:function(c,d,a){var b=new Date();b.setFullYear(c,d,a);return b},StatusNetInstance:{Set:function(b){var a=SN.U.StatusNetInstance.Get();if(a!==null){b=$.extend(a,b)}$.cookie(SN.C.S.StatusNetInstance,JSON.stringify(b),{path:"/",expires:SN.U.GetFullYear(2029,0,1)})},Get:function(){var a=$.cookie(SN.C.S.StatusNetInstance);if(a!==null){return JSON.parse(a)}return null},Delete:function(){$.cookie(SN.C.S.StatusNetInstance,null)}},belongsOnTimeline:function(b){var a=$("body").attr("id");if(a=="public"){return true}var c=$("#nav_profile a").attr("href");if(c){var d=$(b).find(".vcard.author a.url").attr("href");if(d==c){if(a=="all"||a=="showstream"){return true}}}return false},switchInputFormTab:function(a){$(".input_form_nav_tab.current").removeClass("current");if(a=="placeholder"){$("#input_form_nav_status").addClass("current")}else{$("#input_form_nav_"+a).addClass("current")}$(".input_form.current").removeClass("current");$("#input_form_"+a).addClass("current").find(".ajax-notice").each(function(){var b=$(this);SN.Init.NoticeFormSetup(b)}).find("textarea:first").focus()}},Init:{NoticeForm:function(){if($("body.user_in").length>0){$("#input_form_placeholder input.placeholder").focus(function(){SN.U.switchInputFormTab("status")});$("body").bind("click",function(g){var d=$("#content .input_forms div.current");if(d.length>0){if($("#content .input_forms").has(g.target).length==0){var a=d.find('textarea, input[type=text], input[type=""]');var c=false;a.each(function(){c=c||$(this).val()});if(!c){SN.U.switchInputFormTab("placeholder")}}}var b=$("li.notice-reply");if(b.length>0){var f=$(g.target);b.each(function(){var j=$(this);if(j.has(g.target).length==0){var h=j.find(".notice_data-text:first");var i=$.trim(h.val());if(i==""||i==h.data("initialText")){var e=j.closest("li.notice");j.remove();e.find("li.notice-reply-placeholder").show()}}})}})}},NoticeFormSetup:function(a){if(!a.data("NoticeFormSetup")){SN.U.NoticeLocationAttach(a);SN.U.FormNoticeXHR(a);SN.U.FormNoticeEnhancements(a);SN.U.NoticeDataAttach(a);a.data("NoticeFormSetup",true)}},Notices:function(){if($("body.user_in").length>0){var a=$(".form_notice:first");if(a.length>0){SN.C.I.NoticeFormMaster=document._importNode(a[0],true)}SN.U.NoticeRepeat();SN.U.NoticeReply();SN.U.NoticeInlineReplySetup()}SN.U.NoticeAttachments()},EntityActions:function(){if($("body.user_in").length>0){SN.U.NewDirectMessage()}},Login:function(){if(SN.U.StatusNetInstance.Get()!==null){var a=SN.U.StatusNetInstance.Get().Nickname;if(a!==null){$("#form_login #nickname").val(a)}}$("#form_login").bind("submit",function(){SN.U.StatusNetInstance.Set({Nickname:$("#form_login #nickname").val()});return true})},AjaxForms:function(){$("form.ajax").live("submit",function(){SN.U.FormXHR($(this));return false});$("form.ajax input[type=submit]").live("click",function(){var a=$(this);var b=a.closest("form");b.find(".hidden-submit-button").remove();$('').attr("name",a.attr("name")).val(a.val()).appendTo(b)})},UploadForms:function(){$("input[type=file]").change(function(d){if(typeof this.files=="object"&&this.files.length>0){var c=0;for(var b=0;b0&&c>a){var e="File too large: maximum upload size is %d bytes.";alert(e.replace("%d",a));$(this).val("");d.preventDefault();return false}}})},CheckBoxes:function(){$("span[class='checkbox-wrapper']").addClass("unchecked");$(".checkbox-wrapper").click(function(){if($(this).children("input").attr("checked")){$(this).children("input").attr({checked:""});$(this).removeClass("checked");$(this).addClass("unchecked");$(this).children("label").text("Private?")}else{$(this).children("input").attr({checked:"checked"});$(this).removeClass("unchecked");$(this).addClass("checked");$(this).children("label").text("Private")}})}}};$(document).ready(function(){SN.Init.AjaxForms();SN.Init.UploadForms();SN.Init.CheckBoxes();if($("."+SN.C.S.FormNotice).length>0){SN.Init.NoticeForm()}if($("#content .notices").length>0){SN.Init.Notices()}if($("#content .entity_actions").length>0){SN.Init.EntityActions()}if($("#form_login").length>0){SN.Init.Login()}});if(!document.ELEMENT_NODE){document.ELEMENT_NODE=1;document.ATTRIBUTE_NODE=2;document.TEXT_NODE=3;document.CDATA_SECTION_NODE=4;document.ENTITY_REFERENCE_NODE=5;document.ENTITY_NODE=6;document.PROCESSING_INSTRUCTION_NODE=7;document.COMMENT_NODE=8;document.DOCUMENT_NODE=9;document.DOCUMENT_TYPE_NODE=10;document.DOCUMENT_FRAGMENT_NODE=11;document.NOTATION_NODE=12}document._importNode=function(e,a){switch(e.nodeType){case document.ELEMENT_NODE:var d=document.createElement(e.nodeName);if(e.attributes&&e.attributes.length>0){for(var c=0,b=e.attributes.length;c0){for(var c=0,b=e.childNodes.length;c0){var j=c.pop();j()}}};window._google_loader_apiLoaded=function(){f()};var d=function(){return(window.google&&google.loader)};var g=function(j){if(d()){return true}h(j);e();return false};e();return{shim:true,type:"ClientLocation",lastPosition:null,getCurrentPosition:function(k,n,o){var m=this;if(!g(function(){m.getCurrentPosition(k,n,o)})){return}if(google.loader.ClientLocation){var l=google.loader.ClientLocation;var j={coords:{latitude:l.latitude,longitude:l.longitude,altitude:null,accuracy:43000,altitudeAccuracy:null,heading:null,speed:null},address:{city:l.address.city,country:l.address.country,country_code:l.address.country_code,region:l.address.region},timestamp:new Date()};k(j);this.lastPosition=j}else{if(n==="function"){n({code:3,message:"Using the Google ClientLocation API and it is not able to calculate a location."})}}},watchPosition:function(j,l,m){this.getCurrentPosition(j,l,m);var k=this;var n=setInterval(function(){k.getCurrentPosition(j,l,m)},10000);return n},clearWatch:function(j){clearInterval(j)},getPermission:function(l,j,k){return true}}});navigator.geolocation=(window.google&&google.gears)?a():b()})()}; \ No newline at end of file +var SN={C:{I:{CounterBlackout:false,MaxLength:140,PatternUsername:/^[0-9a-zA-Z\-_.]*$/,HTTP20x30x:[200,201,202,203,204,205,206,300,301,302,303,304,305,306,307],NoticeFormMaster:null},S:{Disabled:"disabled",Warning:"warning",Error:"error",Success:"success",Processing:"processing",CommandResult:"command_result",FormNotice:"form_notice",NoticeDataGeo:"notice_data-geo",NoticeDataGeoCookie:"NoticeDataGeo",NoticeDataGeoSelected:"notice_data-geo_selected",StatusNetInstance:"StatusNetInstance"}},messages:{},msg:function(a){if(typeof SN.messages[a]=="undefined"){return"["+a+"]"}else{return SN.messages[a]}},U:{FormNoticeEnhancements:function(b){if(jQuery.data(b[0],"ElementData")===undefined){MaxLength=b.find(".count").text();if(typeof(MaxLength)=="undefined"){MaxLength=SN.C.I.MaxLength}jQuery.data(b[0],"ElementData",{MaxLength:MaxLength});SN.U.Counter(b);NDT=b.find(".notice_data-text:first");NDT.bind("keyup",function(c){SN.U.Counter(b)});var a=function(c){window.setTimeout(function(){SN.U.Counter(b)},50)};NDT.bind("cut",a).bind("paste",a)}else{b.find(".count").text(jQuery.data(b[0],"ElementData").MaxLength)}},Counter:function(d){SN.C.I.FormNoticeCurrent=d;var b=jQuery.data(d[0],"ElementData").MaxLength;if(b<=0){return}var c=b-SN.U.CharacterCount(d);var a=d.find(".count");if(c.toString()!=a.text()){if(!SN.C.I.CounterBlackout||c===0){if(a.text()!=String(c)){a.text(c)}if(c<0){d.addClass(SN.C.S.Warning)}else{d.removeClass(SN.C.S.Warning)}if(!SN.C.I.CounterBlackout){SN.C.I.CounterBlackout=true;SN.C.I.FormNoticeCurrent=d;window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);",500)}}}},CharacterCount:function(a){return a.find(".notice_data-text:first").val().length},ClearCounterBlackout:function(a){SN.C.I.CounterBlackout=false;SN.U.Counter(a)},RewriteAjaxAction:function(a){if(document.location.protocol=="https:"&&a.substr(0,5)=="http:"){return a.replace(/^http:\/\/[^:\/]+/,"https://"+document.location.host)}else{return a}},FormXHR:function(a){$.ajax({type:"POST",dataType:"xml",url:SN.U.RewriteAjaxAction(a.attr("action")),data:a.serialize()+"&ajax=1",beforeSend:function(b){a.addClass(SN.C.S.Processing).find(".submit").addClass(SN.C.S.Disabled).attr(SN.C.S.Disabled,SN.C.S.Disabled)},error:function(d,e,c){var b=null;if(d.responseXML){b=$("#error",d.responseXML).text()}alert(b||c||e);a.removeClass(SN.C.S.Processing).find(".submit").removeClass(SN.C.S.Disabled).removeAttr(SN.C.S.Disabled)},success:function(b,c){if(typeof($("form",b)[0])!="undefined"){form_new=document._importNode($("form",b)[0],true);a.replaceWith(form_new)}else{if(typeof($("p",b)[0])!="undefined"){a.replaceWith(document._importNode($("p",b)[0],true))}else{alert("Unknown error.")}}}})},FormNoticeXHR:function(b){SN.C.I.NoticeDataGeo={};b.append('');b.attr("action",SN.U.RewriteAjaxAction(b.attr("action")));var c=function(d,e){b.append($('

    ').addClass(d).text(e))};var a=function(){b.find(".form_response").remove()};b.ajaxForm({dataType:"xml",timeout:"60000",beforeSend:function(d){if(b.find(".notice_data-text:first").val()==""){b.addClass(SN.C.S.Warning);return false}b.addClass(SN.C.S.Processing).find(".submit").addClass(SN.C.S.Disabled).attr(SN.C.S.Disabled,SN.C.S.Disabled);SN.U.normalizeGeoData(b);return true},error:function(f,g,e){b.removeClass(SN.C.S.Processing).find(".submit").removeClass(SN.C.S.Disabled).removeAttr(SN.C.S.Disabled,SN.C.S.Disabled);a();if(g=="timeout"){c("error","Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.")}else{var d=SN.U.GetResponseXML(f);if($("."+SN.C.S.Error,d).length>0){b.append(document._importNode($("."+SN.C.S.Error,d)[0],true))}else{if(parseInt(f.status)===0||jQuery.inArray(parseInt(f.status),SN.C.I.HTTP20x30x)>=0){b.resetForm().find(".attach-status").remove();SN.U.FormNoticeEnhancements(b)}else{c("error","(Sorry! We had trouble sending your notice ("+f.status+" "+f.statusText+"). Please report the problem to the site administrator if this happens again.")}}}},success:function(j,f){a();var p=$("#"+SN.C.S.Error,j);if(p.length>0){c("error",p.text())}else{if($("body")[0].id=="bookmarklet"){self.close()}var d=$("#"+SN.C.S.CommandResult,j);if(d.length>0){c("success",d.text())}else{var o=document._importNode($("li",j)[0],true);var k=$("#notices_primary .notices:first");var m=b.closest("li.notice-reply");if(m.length>0){var l=b.closest(".threaded-replies");var n=l.find(".notice-reply-placeholder");m.remove();var e=$(o).attr("id");if($("#"+e).length==0){$(o).insertBefore(n)}else{}n.show()}else{if(k.length>0&&SN.U.belongsOnTimeline(o)){if($("#"+o.id).length===0){var h=b.find("[name=inreplyto]").val();var g="#notices_primary #notice-"+h;if($("body")[0].id=="conversation"){if(h.length>0&&$(g+" .notices").length<1){$(g).append('
      ')}$($(g+" .notices")[0]).append(o)}else{k.prepend(o)}$("#"+o.id).css({display:"none"}).fadeIn(2500);SN.U.NoticeWithAttachment($("#"+o.id));SN.U.switchInputFormTab("placeholder")}}else{c("success",$("title",j).text())}}}b.resetForm();b.find("[name=inreplyto]").val("");b.find(".attach-status").remove();SN.U.FormNoticeEnhancements(b)}},complete:function(d,e){b.removeClass(SN.C.S.Processing).find(".submit").removeAttr(SN.C.S.Disabled).removeClass(SN.C.S.Disabled);b.find("[name=lat]").val(SN.C.I.NoticeDataGeo.NLat);b.find("[name=lon]").val(SN.C.I.NoticeDataGeo.NLon);b.find("[name=location_ns]").val(SN.C.I.NoticeDataGeo.NLNS);b.find("[name=location_id]").val(SN.C.I.NoticeDataGeo.NLID);b.find("[name=notice_data-geo]").attr("checked",SN.C.I.NoticeDataGeo.NDG)}})},FormProfileSearchXHR:function(a){$.ajax({type:"POST",dataType:"xml",url:a.attr("action"),data:a.serialize()+"&ajax=1",beforeSend:function(b){a.addClass(SN.C.S.Processing).find(".submit").addClass(SN.C.S.Disabled).attr(SN.C.S.Disabled,SN.C.S.Disabled)},error:function(c,d,b){alert(b||d)},success:function(d,f){var b=$("#profile_search_results");if(typeof($("ul",d)[0])!="undefined"){var c=document._importNode($("ul",d)[0],true);b.replaceWith(c)}else{var e=$("
    • ").append(document._importNode($("p",d)[0],true));b.html(e)}a.removeClass(SN.C.S.Processing).find(".submit").removeClass(SN.C.S.Disabled).attr(SN.C.S.Disabled,false)}})},FormPeopletagsXHR:function(a){$.ajax({type:"POST",dataType:"xml",url:a.attr("action"),data:a.serialize()+"&ajax=1",beforeSend:function(b){a.find(".submit").addClass(SN.C.S.Processing).addClass(SN.C.S.Disabled).attr(SN.C.S.Disabled,SN.C.S.Disabled)},error:function(c,d,b){alert(b||d)},success:function(d,e){var c=a.parents(".entity_tags");if(typeof($(".entity_tags",d)[0])!="undefined"){var b=document._importNode($(".entity_tags",d)[0],true);$(b).find(".editable").append($('').closest(".notice-options").addClass("opaque");a.find("button.close").click(function(){$(this).remove();a.removeClass("dialogbox").closest(".notice-options").removeClass("opaque");a.find(".submit_dialogbox").remove();a.find(".submit").show();return false})},NoticeAttachments:function(){$(".notice a.attachment").each(function(){SN.U.NoticeWithAttachment($(this).closest(".notice"))})},NoticeWithAttachment:function(b){if(b.find(".attachment").length===0){return}var a=b.find(".attachment.more");if(a.length>0){$(a[0]).click(function(){var c=$(this);c.addClass(SN.C.S.Processing);$.get(c.attr("href")+"/ajax",null,function(d){c.parent(".entry-content").html($(d).find("#attachment_view .entry-content").html())});return false}).attr("title",SN.msg("showmore_tooltip"))}},NoticeDataAttach:function(b){var a=b.find("input[type=file]");a.change(function(f){b.find(".attach-status").remove();var d=$(this).val();if(!d){return false}var c=$('
      ');c.find("code").text(d);c.find("button").click(function(){c.remove();a.val("");return false});b.append(c);if(typeof this.files=="object"){for(var e=0;eg){f=false}if(f){h(c,function(k){var j=$("").attr("title",e).attr("alt",e).attr("src",k).attr("style","height: 120px");d.find(".attach-status").append(j)})}else{var b=$("
      ").text(e);d.find(".attach-status").append(b)}},NoticeLocationAttach:function(a){var e=a.find("[name=lat]");var l=a.find("[name=lon]");var g=a.find("[name=location_ns]").val();var m=a.find("[name=location_id]").val();var b="";var d=a.find("[name=notice_data-geo]");var c=a.find("[name=notice_data-geo]");var k=a.find("label.notice_data-geo");function f(o){k.attr("title",jQuery.trim(k.text())).removeClass("checked");a.find("[name=lat]").val("");a.find("[name=lon]").val("");a.find("[name=location_ns]").val("");a.find("[name=location_id]").val("");a.find("[name=notice_data-geo]").attr("checked",false);$.cookie(SN.C.S.NoticeDataGeoCookie,"disabled",{path:"/"});if(o){a.find(".geo_status_wrapper").removeClass("success").addClass("error");a.find(".geo_status_wrapper .geo_status").text(o)}else{a.find(".geo_status_wrapper").remove()}}function n(o,p){SN.U.NoticeGeoStatus(a,"Looking up place name...");$.getJSON(o,p,function(q){var r,s;if(typeof(q.location_ns)!="undefined"){a.find("[name=location_ns]").val(q.location_ns);r=q.location_ns}if(typeof(q.location_id)!="undefined"){a.find("[name=location_id]").val(q.location_id);s=q.location_id}if(typeof(q.name)=="undefined"){NLN_text=p.lat+";"+p.lon}else{NLN_text=q.name}SN.U.NoticeGeoStatus(a,NLN_text,p.lat,p.lon,q.url);k.attr("title",NoticeDataGeo_text.ShareDisable+" ("+NLN_text+")");a.find("[name=lat]").val(p.lat);a.find("[name=lon]").val(p.lon);a.find("[name=location_ns]").val(r);a.find("[name=location_id]").val(s);a.find("[name=notice_data-geo]").attr("checked",true);var t={NLat:p.lat,NLon:p.lon,NLNS:r,NLID:s,NLN:NLN_text,NLNU:q.url,NDG:true};$.cookie(SN.C.S.NoticeDataGeoCookie,JSON.stringify(t),{path:"/"})})}if(c.length>0){if($.cookie(SN.C.S.NoticeDataGeoCookie)=="disabled"){c.attr("checked",false)}else{c.attr("checked",true)}var h=a.find(".notice_data-geo_wrap");var j=h.attr("data-api");k.attr("title",k.text());c.change(function(){if(c.attr("checked")===true||$.cookie(SN.C.S.NoticeDataGeoCookie)===null){k.attr("title",NoticeDataGeo_text.ShareDisable).addClass("checked");if($.cookie(SN.C.S.NoticeDataGeoCookie)===null||$.cookie(SN.C.S.NoticeDataGeoCookie)=="disabled"){if(navigator.geolocation){SN.U.NoticeGeoStatus(a,"Requesting location from browser...");navigator.geolocation.getCurrentPosition(function(q){a.find("[name=lat]").val(q.coords.latitude);a.find("[name=lon]").val(q.coords.longitude);var r={lat:q.coords.latitude,lon:q.coords.longitude,token:$("#token").val()};n(j,r)},function(q){switch(q.code){case q.PERMISSION_DENIED:f("Location permission denied.");break;case q.TIMEOUT:f("Location lookup timeout.");break}},{timeout:10000})}else{if(e.length>0&&l.length>0){var o={lat:e,lon:l,token:$("#token").val()};n(j,o)}else{f();c.remove();k.remove()}}}else{var p=JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));a.find("[name=lat]").val(p.NLat);a.find("[name=lon]").val(p.NLon);a.find("[name=location_ns]").val(p.NLNS);a.find("[name=location_id]").val(p.NLID);a.find("[name=notice_data-geo]").attr("checked",p.NDG);SN.U.NoticeGeoStatus(a,p.NLN,p.NLat,p.NLon,p.NLNU);k.attr("title",NoticeDataGeo_text.ShareDisable+" ("+p.NLN+")").addClass("checked")}}else{f()}}).change()}},NoticeGeoStatus:function(e,a,f,g,c){var h=e.find(".geo_status_wrapper");if(h.length==0){h=$('
      ');h.find("button.close").click(function(){e.find("[name=notice_data-geo]").removeAttr("checked").change();return false});e.append(h)}var b;if(c){b=$("").attr("href",c)}else{b=$("")}b.text(a);if(f||g){var d=f+";"+g;b.attr("title",d);if(!a){b.text(d)}}h.find(".geo_status").empty().append(b)},NewDirectMessage:function(){NDM=$(".entity_send-a-message a");NDM.attr({href:NDM.attr("href")+"&ajax=1"});NDM.bind("click",function(){var a=$(".entity_send-a-message form");if(a.length===0){$(this).addClass(SN.C.S.Processing);$.get(NDM.attr("href"),null,function(b){$(".entity_send-a-message").append(document._importNode($("form",b)[0],true));a=$(".entity_send-a-message .form_notice");SN.U.FormNoticeXHR(a);SN.U.FormNoticeEnhancements(a);a.append('');$(".entity_send-a-message button").click(function(){a.hide();return false});NDM.removeClass(SN.C.S.Processing)})}else{a.show();$(".entity_send-a-message textarea").focus()}return false})},GetFullYear:function(c,d,a){var b=new Date();b.setFullYear(c,d,a);return b},StatusNetInstance:{Set:function(b){var a=SN.U.StatusNetInstance.Get();if(a!==null){b=$.extend(a,b)}$.cookie(SN.C.S.StatusNetInstance,JSON.stringify(b),{path:"/",expires:SN.U.GetFullYear(2029,0,1)})},Get:function(){var a=$.cookie(SN.C.S.StatusNetInstance);if(a!==null){return JSON.parse(a)}return null},Delete:function(){$.cookie(SN.C.S.StatusNetInstance,null)}},belongsOnTimeline:function(b){var a=$("body").attr("id");if(a=="public"){return true}var c=$("#nav_profile a").attr("href");if(c){var d=$(b).find(".vcard.author a.url").attr("href");if(d==c){if(a=="all"||a=="showstream"){return true}}}return false},switchInputFormTab:function(a){$(".input_form_nav_tab.current").removeClass("current");if(a=="placeholder"){$("#input_form_nav_status").addClass("current")}else{$("#input_form_nav_"+a).addClass("current")}$(".input_form.current").removeClass("current");$("#input_form_"+a).addClass("current").find(".ajax-notice").each(function(){var b=$(this);SN.Init.NoticeFormSetup(b)}).find("textarea:first").focus()}},Init:{NoticeForm:function(){if($("body.user_in").length>0){$("#input_form_placeholder input.placeholder").focus(function(){SN.U.switchInputFormTab("status")});$("body").bind("click",function(g){var d=$("#content .input_forms div.current");if(d.length>0){if($("#content .input_forms").has(g.target).length==0){var a=d.find('textarea, input[type=text], input[type=""]');var c=false;a.each(function(){c=c||$(this).val()});if(!c){SN.U.switchInputFormTab("placeholder")}}}var b=$("li.notice-reply");if(b.length>0){var f=$(g.target);b.each(function(){var k=$(this);if(k.has(g.target).length==0){var h=k.find(".notice_data-text:first");var j=$.trim(h.val());if(j==""||j==h.data("initialText")){var e=k.closest("li.notice");k.remove();e.find("li.notice-reply-placeholder").show()}}})}})}},NoticeFormSetup:function(a){if(!a.data("NoticeFormSetup")){SN.U.NoticeLocationAttach(a);SN.U.FormNoticeXHR(a);SN.U.FormNoticeEnhancements(a);SN.U.NoticeDataAttach(a);a.data("NoticeFormSetup",true)}},Notices:function(){if($("body.user_in").length>0){var a=$(".form_notice:first");if(a.length>0){SN.C.I.NoticeFormMaster=document._importNode(a[0],true)}SN.U.NoticeRepeat();SN.U.NoticeReply();SN.U.NoticeInlineReplySetup()}SN.U.NoticeAttachments()},EntityActions:function(){if($("body.user_in").length>0){$(".form_user_subscribe").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_user_unsubscribe").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_group_join").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_group_leave").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_user_nudge").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_peopletag_subscribe").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_peopletag_unsubscribe").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_user_add_peopletag").live("click",function(){SN.U.FormXHR($(this));return false});$(".form_user_remove_peopletag").live("click",function(){SN.U.FormXHR($(this));return false});SN.U.NewDirectMessage()}},ProfileSearch:function(){if($("body.user_in").length>0){$(".form_peopletag_edit_user_search input.submit").live("click",function(){SN.U.FormProfileSearchXHR($(this).parents("form"));return false})}},Login:function(){if(SN.U.StatusNetInstance.Get()!==null){var a=SN.U.StatusNetInstance.Get().Nickname;if(a!==null){$("#form_login #nickname").val(a)}}$("#form_login").bind("submit",function(){SN.U.StatusNetInstance.Set({Nickname:$("#form_login #nickname").val()});return true})},PeopletagAutocomplete:function(b){var a=function(d){return d.split(/\s+/)};var c=function(d){return a(d).pop()};b.live("keydown",function(d){if(d.keyCode===$.ui.keyCode.TAB&&$(this).data("autocomplete").menu.active){d.preventDefault()}}).autocomplete({minLength:0,source:function(e,d){d($.ui.autocomplete.filter(SN.C.PtagACData,c(e.term)))},focus:function(){return false},select:function(e,f){var d=a(this.value);d.pop();d.push(f.item.value);d.push("");this.value=d.join(" ");return false}}).data("autocomplete")._renderItem=function(e,f){var d=''+f.tag+' '+f.mode+''+f.freq+"";return $("
    • ").addClass("mode-"+f.mode).addClass("ptag-ac-line").data("item.autocomplete",f).append(d).appendTo(e)}},PeopleTags:function(){$(".user_profile_tags .editable").append($('