3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2011, StatusNet, Inc.
6 * A plugin to enable social-bookmarking functionality
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Affero General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Affero General Public License for more details.
20 * You should have received a copy of the GNU Affero General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * @category PollPlugin
25 * @author Brion Vibber <brion@status.net>
26 * @copyright 2011 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28 * @link http://status.net/
31 if (!defined('STATUSNET')) {
36 * Poll plugin main class
38 * @category PollPlugin
40 * @author Brion Vibber <brionv@status.net>
41 * @author Evan Prodromou <evan@status.net>
42 * @copyright 2011 StatusNet, Inc.
43 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
44 * @link http://status.net/
46 class PollPlugin extends MicroAppPlugin
48 const VERSION = '0.1';
50 // @fixme which domain should we use for these namespaces?
51 const POLL_OBJECT = 'http://activityschema.org/object/poll';
52 const POLL_RESPONSE_OBJECT = 'http://activityschema.org/object/poll-response';
55 * Database schema setup
60 * @return boolean hook value; true means continue processing, false means stop.
62 function onCheckSchema()
64 $schema = Schema::get();
65 $schema->ensureTable('poll', Poll::schemaDef());
66 $schema->ensureTable('poll_response', Poll_response::schemaDef());
67 $schema->ensureTable('user_poll_prefs', User_poll_prefs::schemaDef());
72 * Show the CSS necessary for this plugin
74 * @param Action $action the action being run
76 * @return boolean hook value
78 function onEndShowStyles($action)
80 $action->cssLink($this->path('poll.css'));
85 * Load related modules when needed
87 * @param string $cls Name of the class to be loaded
89 * @return boolean hook value; true means continue processing, false means stop.
91 function onAutoload($cls)
93 $dir = dirname(__FILE__);
97 case 'ShowpollAction':
99 case 'RespondpollAction':
100 case 'PollsettingsAction':
101 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
104 case 'Poll_response':
105 case 'User_poll_prefs':
106 include_once $dir.'/'.$cls.'.php';
109 case 'PollResponseForm':
110 case 'PollResultForm':
111 include_once $dir.'/'.strtolower($cls).'.php';
119 * Map URLs to actions
121 * @param Net_URL_Mapper $m path-to-action mapper
123 * @return boolean hook value; true means continue processing, false means stop.
125 function onRouterInitialized($m)
127 $m->connect('main/poll/new',
128 array('action' => 'newpoll'));
130 $m->connect('main/poll/:id',
131 array('action' => 'showpoll'),
132 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
134 $m->connect('main/poll/response/:id',
135 array('action' => 'showpollresponse'),
136 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
138 $m->connect('main/poll/:id/respond',
139 array('action' => 'respondpoll'),
140 array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
142 $m->connect('settings/poll',
143 array('action' => 'pollsettings'));
149 * Plugin version data
151 * @param array &$versions array of version data
155 function onPluginVersion(&$versions)
157 $versions[] = array('name' => 'Poll',
158 'version' => self::VERSION,
159 'author' => 'Brion Vibber',
160 'homepage' => 'http://status.net/wiki/Plugin:Poll',
162 // TRANS: Plugin description.
163 _m('Simple extension for supporting basic polls.'));
169 return array(self::POLL_OBJECT, self::POLL_RESPONSE_OBJECT);
173 * When a notice is deleted, delete the related Poll
175 * @param Notice $notice Notice being deleted
177 * @return boolean hook value
179 function deleteRelated($notice)
181 $p = Poll::getByNotice($notice);
191 * Save a poll from an activity
193 * @param Profile $profile Profile to use as author
194 * @param Activity $activity Activity to save
195 * @param array $options Options to pass to bookmark-saving code
197 * @return Notice resulting notice
199 function saveNoticeFromActivity($activity, $profile, $options=array())
202 common_log(LOG_DEBUG, "XXX activity: " . var_export($activity, true));
203 common_log(LOG_DEBUG, "XXX profile: " . var_export($profile, true));
204 common_log(LOG_DEBUG, "XXX options: " . var_export($options, true));
206 // Ok for now, we can grab stuff from the XML entry directly.
207 // This won't work when reading from JSON source
208 if ($activity->entry) {
209 $pollElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'poll');
210 $responseElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'response');
211 if ($pollElements->length) {
215 $data = $pollElements->item(0);
216 foreach ($data->getElementsByTagNameNS(self::POLL_OBJECT, 'question') as $node) {
217 $question = $node->textContent;
219 foreach ($data->getElementsByTagNameNS(self::POLL_OBJECT, 'option') as $node) {
220 $opts[] = $node->textContent;
223 $notice = Poll::saveNew($profile, $question, $opts, $options);
224 common_log(LOG_DEBUG, "Saved Poll from ActivityStream data ok: notice id " . $notice->id);
226 } catch (Exception $e) {
227 common_log(LOG_DEBUG, "Poll save from ActivityStream data failed: " . $e->getMessage());
229 } else if ($responseElements->length) {
230 $data = $responseElements->item(0);
231 $pollUri = $data->getAttribute('poll');
232 $selection = intval($data->getAttribute('selection'));
235 // TRANS: Exception thrown trying to respond to a poll without a poll reference.
236 throw new Exception(_m('Invalid poll response: No poll reference.'));
238 $poll = Poll::staticGet('uri', $pollUri);
240 // TRANS: Exception thrown trying to respond to a non-existing poll.
241 throw new Exception(_m('Invalid poll response: Poll is unknown.'));
244 $notice = Poll_response::saveNew($profile, $poll, $selection, $options);
245 common_log(LOG_DEBUG, "Saved Poll_response ok, notice id: " . $notice->id);
247 } catch (Exception $e) {
248 common_log(LOG_DEBUG, "Poll response save fail: " . $e->getMessage());
251 common_log(LOG_DEBUG, "YYY no poll data");
256 function activityObjectFromNotice($notice)
258 assert($this->isMyNotice($notice));
260 switch ($notice->object_type) {
261 case self::POLL_OBJECT:
262 return $this->activityObjectFromNoticePoll($notice);
263 case self::POLL_RESPONSE_OBJECT:
264 return $this->activityObjectFromNoticePollResponse($notice);
266 // TRANS: Exception thrown when performing an unexpected action on a poll.
267 // TRANS: %s is the unexpected object type.
268 throw new Exception(sprintf(_m('Unexpected type for poll plugin: %s.'), $notice->object_type));
272 function activityObjectFromNoticePollResponse($notice)
274 $object = new ActivityObject();
275 $object->id = $notice->uri;
276 $object->type = self::POLL_RESPONSE_OBJECT;
277 $object->title = $notice->content;
278 $object->summary = $notice->content;
279 $object->link = $notice->bestUrl();
281 $response = Poll_response::getByNotice($notice);
283 $poll = $response->getPoll();
285 // Stash data to be formatted later by
286 // $this->activityObjectOutputAtom() or
287 // $this->activityObjectOutputJson()...
288 $object->pollSelection = intval($response->selection);
289 $object->pollUri = $poll->uri;
295 function activityObjectFromNoticePoll($notice)
297 $object = new ActivityObject();
298 $object->id = $notice->uri;
299 $object->type = self::POLL_OBJECT;
300 $object->title = $notice->content;
301 $object->summary = $notice->content;
302 $object->link = $notice->bestUrl();
304 $poll = Poll::getByNotice($notice);
306 // Stash data to be formatted later by
307 // $this->activityObjectOutputAtom() or
308 // $this->activityObjectOutputJson()...
309 $object->pollQuestion = $poll->question;
310 $object->pollOptions = $poll->getOptions();
317 * Called when generating Atom XML ActivityStreams output from an
318 * ActivityObject belonging to this plugin. Gives the plugin
319 * a chance to add custom output.
321 * Note that you can only add output of additional XML elements,
322 * not change existing stuff here.
324 * If output is already handled by the base Activity classes,
325 * you can leave this base implementation as a no-op.
327 * @param ActivityObject $obj
328 * @param XMLOutputter $out to add elements at end of object
330 function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
332 if (isset($obj->pollQuestion)) {
334 * <poll:poll xmlns:poll="http://apinamespace.org/activitystreams/object/poll">
335 * <poll:question>Who wants a poll question?</poll:question>
336 * <poll:option>Option one</poll:option>
337 * <poll:option>Option two</poll:option>
338 * <poll:option>Option three</poll:option>
341 $data = array('xmlns:poll' => self::POLL_OBJECT);
342 $out->elementStart('poll:poll', $data);
343 $out->element('poll:question', array(), $obj->pollQuestion);
344 foreach ($obj->pollOptions as $opt) {
345 $out->element('poll:option', array(), $opt);
347 $out->elementEnd('poll:poll');
349 if (isset($obj->pollSelection)) {
351 * <poll:response xmlns:poll="http://apinamespace.org/activitystreams/object/poll">
352 * poll="http://..../poll/...."
355 $data = array('xmlns:poll' => self::POLL_OBJECT,
356 'poll' => $obj->pollUri,
357 'selection' => $obj->pollSelection);
358 $out->element('poll:response', $data, '');
363 * Called when generating JSON ActivityStreams output from an
364 * ActivityObject belonging to this plugin. Gives the plugin
365 * a chance to add custom output.
367 * Modify the array contents to your heart's content, and it'll
368 * all get serialized out as JSON.
370 * If output is already handled by the base Activity classes,
371 * you can leave this base implementation as a no-op.
373 * @param ActivityObject $obj
374 * @param array &$out JSON-targeted array which can be modified
376 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
378 common_log(LOG_DEBUG, 'QQQ: ' . var_export($obj, true));
379 if (isset($obj->pollQuestion)) {
382 * "question": "Who wants a poll question?",
390 $data = array('question' => $obj->pollQuestion,
391 'options' => array());
392 foreach ($obj->pollOptions as $opt) {
393 $data['options'][] = $opt;
395 $out['poll'] = $data;
397 if (isset($obj->pollSelection)) {
400 * "poll": "http://..../poll/....",
404 $data = array('poll' => $obj->pollUri,
405 'selection' => $obj->pollSelection);
406 $out['pollResponse'] = $data;
412 * @fixme WARNING WARNING WARNING parent class closes the final div that we
413 * open here, but we probably shouldn't open it here. Check parent class
414 * and Bookmark plugin for if that's right.
416 function showNotice($notice, $out)
418 switch ($notice->object_type) {
419 case self::POLL_OBJECT:
420 return $this->showNoticePoll($notice, $out);
421 case self::POLL_RESPONSE_OBJECT:
422 return $this->showNoticePollResponse($notice, $out);
424 // TRANS: Exception thrown when performing an unexpected action on a poll.
425 // TRANS: %s is the unexpected object type.
426 throw new Exception(sprintf(_m('Unexpected type for poll plugin: %s.'), $notice->object_type));
430 function showNoticePoll($notice, $out)
432 $user = common_current_user();
434 // @hack we want regular rendering, then just add stuff after that
435 $nli = new NoticeListItem($notice, $out);
438 $out->elementStart('div', array('class' => 'entry-content poll-content'));
439 $poll = Poll::getByNotice($notice);
442 $profile = $user->getProfile();
443 $response = $poll->getResponse($profile);
445 // User has already responded; show the results.
446 $form = new PollResultForm($poll, $out);
448 $form = new PollResponseForm($poll, $out);
453 // TRANS: Error text displayed if no poll data could be found.
454 $out->text(_m('Poll data is missing'));
456 $out->elementEnd('div');
459 $out->elementStart('div', array('class' => 'entry-content'));
462 function showNoticePollResponse($notice, $out)
464 $user = common_current_user();
466 // @hack we want regular rendering, then just add stuff after that
467 $nli = new NoticeListItem($notice, $out);
471 $out->elementStart('div', array('class' => 'entry-content'));
474 function entryForm($out)
476 return new NewPollForm($out);
479 // @fixme is this from parent?
487 // TRANS: Application title.
488 return _m('APPTITLE','Poll');
491 function onStartAddNoticeReply($nli, $parent, $child)
493 // Filter out any poll responses
494 if ($parent->object_type == self::POLL_OBJECT &&
495 $child->object_type == self::POLL_RESPONSE_OBJECT) {
501 // Hide poll responses for @chuck
503 function onEndNoticeWhoGets($notice, &$ni) {
504 if ($notice->object_type == self::POLL_RESPONSE_OBJECT) {
505 foreach ($ni as $id => $source) {
506 $user = User::staticGet('id', $id);
508 $pollPrefs = User_poll_prefs::staticGet('user_id', $user->id);
509 if (!empty($pollPrefs) && ($pollPrefs->hide_responses)) {
519 * Menu item for personal subscriptions/groups area
521 * @param Action $action action being executed
523 * @return boolean hook return
526 function onEndAccountSettingsNav($action)
528 $action_name = $action->trimmed('action');
530 $action->menuItem(common_local_url('pollsettings'),
531 // TRANS: Poll plugin menu item on user settings page.
533 // TRANS: Poll plugin tooltip for user settings menu item.
534 _m('Configure poll behavior'),
535 $action_name === 'pollsettings');