]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Poll/PollPlugin.php
Merge remote branch 'origin/1.0.x' into 1.0.x
[quix0rs-gnu-social.git] / plugins / Poll / PollPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2011, StatusNet, Inc.
5  *
6  * A plugin to enable social-bookmarking functionality
7  *
8  * PHP version 5
9  *
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.
14  *
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.
19  *
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/>.
22  *
23  * @category  PollPlugin
24  * @package   StatusNet
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/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Poll plugin main class
37  *
38  * @category  PollPlugin
39  * @package   StatusNet
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/
45  */
46 class PollPlugin extends MicroAppPlugin
47 {
48     const VERSION         = '0.1';
49
50     // @fixme which domain should we use for these namespaces?
51     const POLL_OBJECT          = 'http://apinamespace.org/activitystreams/object/poll';
52     const POLL_RESPONSE_OBJECT = 'http://apinamespace.org/activitystreams/object/poll-response';
53
54     /**
55      * Database schema setup
56      *
57      * @see Schema
58      * @see ColumnDef
59      *
60      * @return boolean hook value; true means continue processing, false means stop.
61      */
62     function onCheckSchema()
63     {
64         $schema = Schema::get();
65         $schema->ensureTable('poll', Poll::schemaDef());
66         $schema->ensureTable('poll_response', Poll_response::schemaDef());
67         return true;
68     }
69
70     /**
71      * Show the CSS necessary for this plugin
72      *
73      * @param Action $action the action being run
74      *
75      * @return boolean hook value
76      */
77     function onEndShowStyles($action)
78     {
79         $action->cssLink($this->path('poll.css'));
80         return true;
81     }
82
83     /**
84      * Load related modules when needed
85      *
86      * @param string $cls Name of the class to be loaded
87      *
88      * @return boolean hook value; true means continue processing, false means stop.
89      */
90     function onAutoload($cls)
91     {
92         $dir = dirname(__FILE__);
93
94         switch ($cls)
95         {
96         case 'ShowpollAction':
97         case 'NewpollAction':
98         case 'RespondpollAction':
99             include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
100             return false;
101         case 'Poll':
102         case 'Poll_response':
103             include_once $dir.'/'.$cls.'.php';
104             return false;
105         case 'NewPollForm':
106         case 'PollResponseForm':
107         case 'PollResultForm':
108             include_once $dir.'/'.strtolower($cls).'.php';
109             return false;
110         default:
111             return true;
112         }
113     }
114
115     /**
116      * Map URLs to actions
117      *
118      * @param Net_URL_Mapper $m path-to-action mapper
119      *
120      * @return boolean hook value; true means continue processing, false means stop.
121      */
122     function onRouterInitialized($m)
123     {
124         $m->connect('main/poll/new',
125                     array('action' => 'newpoll'));
126
127         $m->connect('main/poll/:id',
128                     array('action' => 'showpoll'),
129                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
130
131         $m->connect('main/poll/response/:id',
132                     array('action' => 'showpollresponse'),
133                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
134
135         $m->connect('main/poll/:id/respond',
136                     array('action' => 'respondpoll'),
137                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
138
139         return true;
140     }
141
142     /**
143      * Plugin version data
144      *
145      * @param array &$versions array of version data
146      *
147      * @return value
148      */
149     function onPluginVersion(&$versions)
150     {
151         $versions[] = array('name' => 'Poll',
152                             'version' => self::VERSION,
153                             'author' => 'Brion Vibber',
154                             'homepage' => 'http://status.net/wiki/Plugin:Poll',
155                             'rawdescription' =>
156                             // TRANS: Plugin description.
157                             _m('Simple extension for supporting basic polls.'));
158         return true;
159     }
160
161     function types()
162     {
163         return array(self::POLL_OBJECT, self::POLL_RESPONSE_OBJECT);
164     }
165
166     /**
167      * When a notice is deleted, delete the related Poll
168      *
169      * @param Notice $notice Notice being deleted
170      *
171      * @return boolean hook value
172      */
173     function deleteRelated($notice)
174     {
175         $p = Poll::getByNotice($notice);
176
177         if (!empty($p)) {
178             $p->delete();
179         }
180
181         return true;
182     }
183
184     /**
185      * Save a poll from an activity
186      *
187      * @param Profile  $profile  Profile to use as author
188      * @param Activity $activity Activity to save
189      * @param array    $options  Options to pass to bookmark-saving code
190      *
191      * @return Notice resulting notice
192      */
193     function saveNoticeFromActivity($activity, $profile, $options=array())
194     {
195         // @fixme
196         common_log(LOG_DEBUG, "XXX activity: " . var_export($activity, true));
197         common_log(LOG_DEBUG, "XXX profile: " . var_export($profile, true));
198         common_log(LOG_DEBUG, "XXX options: " . var_export($options, true));
199
200         // Ok for now, we can grab stuff from the XML entry directly.
201         // This won't work when reading from JSON source
202         if ($activity->entry) {
203             $pollElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'poll');
204             $responseElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'response');
205             if ($pollElements->length) {
206                 $data = $pollElements->item(0);
207                 $question = $data->getAttribute('question');
208                 $opts = array();
209                 foreach ($data->attributes as $node) {
210                     $name = $node->nodeName;
211                     if (substr($name, 0, 6) == 'option') {
212                         $n = intval(substr($name, 6));
213                         if ($n > 0) {
214                             $opts[$n - 1] = $node->nodeValue;
215                         }
216                     }
217                 }
218                 common_log(LOG_DEBUG, "YYY question: $question");
219                 common_log(LOG_DEBUG, "YYY opts: " . var_export($opts, true));
220                 try {
221                     $notice = Poll::saveNew($profile, $question, $opts, $options);
222                     common_log(LOG_DEBUG, "YYY ok: " . $notice->id);
223                     return $notice;
224                 } catch (Exception $e) {
225                     common_log(LOG_DEBUG, "YYY fail: " . $e->getMessage());
226                 }
227             } else if ($responseElements->length) {
228                 $data = $responseElements->item(0);
229                 $pollUri = $data->getAttribute('poll');
230                 $selection = intval($data->getAttribute('selection'));
231
232                 if (!$pollUri) {
233                     // TRANS: Exception thrown trying to respond to a poll without a poll reference.
234                     throw new Exception(_m('Invalid poll response: no poll reference.'));
235                 }
236                 $poll = Poll::staticGet('uri', $pollUri);
237                 if (!$poll) {
238                     // TRANS: Exception thrown trying to respond to a non-existing poll.
239                     throw new Exception(_m('Invalid poll response: poll is unknown.'));
240                 }
241                 try {
242                     $notice = Poll_response::saveNew($profile, $poll, $selection, $options);
243                     common_log(LOG_DEBUG, "YYY response ok: " . $notice->id);
244                     return $notice;
245                 } catch (Exception $e) {
246                     common_log(LOG_DEBUG, "YYY response fail: " . $e->getMessage());
247                 }
248             } else {
249                 common_log(LOG_DEBUG, "YYY no poll data");
250             }
251         }
252     }
253
254     function activityObjectFromNotice($notice)
255     {
256         assert($this->isMyNotice($notice));
257
258         switch ($notice->object_type) {
259         case self::POLL_OBJECT:
260             return $this->activityObjectFromNoticePoll($notice);
261         case self::POLL_RESPONSE_OBJECT:
262             return $this->activityObjectFromNoticePollResponse($notice);
263         default:
264             // TRANS: Exception thrown when performing an unexpected action on a poll.
265             // TRANS: %s is the unpexpected object type.
266             throw new Exception(sprintf(_m('Unexpected type for poll plugin: %s.'), $notice->object_type));
267         }
268     }
269
270     function activityObjectFromNoticePollResponse($notice)
271     {
272         $object = new ActivityObject();
273         $object->id      = $notice->uri;
274         $object->type    = self::POLL_OBJECT;
275         $object->title   = $notice->content;
276         $object->summary = $notice->content;
277         $object->link    = $notice->bestUrl();
278
279         $response = Poll_response::getByNotice($notice);
280         if (!$response) {
281             common_log(LOG_DEBUG, "QQQ notice uri: $notice->uri");
282         } else {
283             $poll = $response->getPoll();
284             /**
285              * For the moment, using a kind of icky-looking schema that happens to
286              * work with out code for generating both Atom and JSON forms, though
287              * I don't like it:
288              *
289              * <poll:response xmlns:poll="http://apinamespace.org/activitystreams/object/poll"
290              *                poll="http://..../poll/...."
291              *                selection="3" />
292              *
293              * "poll:response": {
294              *     "xmlns:poll": http://apinamespace.org/activitystreams/object/poll
295              *     "uri": "http://..../poll/...."
296              *     "selection": 3
297              * }
298              *
299              */
300             // @fixme there's no way to specify an XML node tree here, like <poll><option/><option/></poll>
301             // @fixme there's no way to specify a JSON array or multi-level tree unless you break the XML attribs
302             // @fixme XML node contents don't get shown in JSON
303             $data = array('xmlns:poll' => self::POLL_OBJECT,
304                           'poll'       => $poll->uri,
305                           'selection'  => intval($response->selection));
306             $object->extra[] = array('poll:response', $data, '');
307         }
308         return $object;
309     }
310
311     function activityObjectFromNoticePoll($notice)
312     {
313         $object = new ActivityObject();
314         $object->id      = $notice->uri;
315         $object->type    = self::POLL_RESPONSE_OBJECT;
316         $object->title   = $notice->content;
317         $object->summary = $notice->content;
318         $object->link    = $notice->bestUrl();
319
320         $poll = Poll::getByNotice($notice);
321         /**
322          * Adding the poll-specific data. There's no standard in AS for polls,
323          * so we're making stuff up.
324          *
325          * For the moment, using a kind of icky-looking schema that happens to
326          * work with out code for generating both Atom and JSON forms, though
327          * I don't like it:
328          *
329          * <poll:data xmlns:poll="http://apinamespace.org/activitystreams/object/poll"
330          *            question="Who wants a poll question?"
331          *            option1="Option one"
332          *            option2="Option two"
333          *            option3="Option three"></poll:data>
334          *
335          * "poll:response": {
336          *     "xmlns:poll": http://apinamespace.org/activitystreams/object/poll
337          *     "question": "Who wants a poll question?"
338          *     "option1": "Option one"
339          *     "option2": "Option two"
340          *     "option3": "Option three"
341          * }
342          *
343          */
344         // @fixme there's no way to specify an XML node tree here, like <poll><option/><option/></poll>
345         // @fixme there's no way to specify a JSON array or multi-level tree unless you break the XML attribs
346         // @fixme XML node contents don't get shown in JSON
347         $data = array('xmlns:poll' => self::POLL_OBJECT,
348                       'question'   => $poll->question);
349         foreach ($poll->getOptions() as $i => $opt) {
350             $data['option' . ($i + 1)] = $opt;
351         }
352         $object->extra[] = array('poll:poll', $data, '');
353         return $object;
354     }
355
356     /**
357      * @fixme WARNING WARNING WARNING parent class closes the final div that we
358      * open here, but we probably shouldn't open it here. Check parent class
359      * and Bookmark plugin for if that's right.
360      */
361     function showNotice($notice, $out)
362     {
363         switch ($notice->object_type) {
364         case self::POLL_OBJECT:
365             return $this->showNoticePoll($notice, $out);
366         case self::POLL_RESPONSE_OBJECT:
367             return $this->showNoticePollResponse($notice, $out);
368         default:
369             // TRANS: Exception thrown when performing an unexpected action on a poll.
370             // TRANS: %s is the unpexpected object type.
371             throw new Exception(sprintf(_m('Unexpected type for poll plugin: %s.'), $notice->object_type));
372         }
373     }
374
375     function showNoticePoll($notice, $out)
376     {
377         $user = common_current_user();
378
379         // @hack we want regular rendering, then just add stuff after that
380         $nli = new NoticeListItem($notice, $out);
381         $nli->showNotice();
382
383         $out->elementStart('div', array('class' => 'entry-content poll-content'));
384         $poll = Poll::getByNotice($notice);
385         if ($poll) {
386             if ($user) {
387                 $profile = $user->getProfile();
388                 $response = $poll->getResponse($profile);
389                 if ($response) {
390                     // User has already responded; show the results.
391                     $form = new PollResultForm($poll, $out);
392                 } else {
393                     $form = new PollResponseForm($poll, $out);
394                 }
395                 $form->show();
396             }
397         } else {
398             $out->text(_('Poll data is missing'));
399         }
400         $out->elementEnd('div');
401
402         // @fixme
403         $out->elementStart('div', array('class' => 'entry-content'));
404     }
405
406     function showNoticePollResponse($notice, $out)
407     {
408         $user = common_current_user();
409
410         // @hack we want regular rendering, then just add stuff after that
411         $nli = new NoticeListItem($notice, $out);
412         $nli->showNotice();
413
414         // @fixme
415         $out->elementStart('div', array('class' => 'entry-content'));
416     }
417
418     function entryForm($out)
419     {
420         return new NewPollForm($out);
421     }
422
423     // @fixme is this from parent?
424     function tag()
425     {
426         return 'poll';
427     }
428
429     function appTitle()
430     {
431         // TRANS: Application title.
432         return _m('APPTITLE','Poll');
433     }
434 }