]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Poll/PollPlugin.php
fix
[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
47 class PollPlugin extends MicroAppPlugin
48 {
49     const VERSION         = '0.1';
50
51     // @fixme which domain should we use for these namespaces?
52     const POLL_OBJECT          = 'http://apinamespace.org/activitystreams/object/poll';
53     const POLL_RESPONSE_OBJECT = 'http://apinamespace.org/activitystreams/object/poll-response';
54
55     /**
56      * Database schema setup
57      *
58      * @see Schema
59      * @see ColumnDef
60      *
61      * @return boolean hook value; true means continue processing, false means stop.
62      */
63
64     function onCheckSchema()
65     {
66         $schema = Schema::get();
67         $schema->ensureTable('poll', Poll::schemaDef());
68         $schema->ensureTable('poll_response', Poll_response::schemaDef());
69         return true;
70     }
71
72     /**
73      * Show the CSS necessary for this plugin
74      *
75      * @param Action $action the action being run
76      *
77      * @return boolean hook value
78      */
79
80     function onEndShowStyles($action)
81     {
82         $action->cssLink($this->path('poll.css'));
83         return true;
84     }
85
86     /**
87      * Load related modules when needed
88      *
89      * @param string $cls Name of the class to be loaded
90      *
91      * @return boolean hook value; true means continue processing, false means stop.
92      */
93
94     function onAutoload($cls)
95     {
96         $dir = dirname(__FILE__);
97
98         switch ($cls)
99         {
100         case 'ShowpollAction':
101         case 'NewpollAction':
102         case 'RespondpollAction':
103             include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
104             return false;
105         case 'Poll':
106         case 'Poll_response':
107             include_once $dir.'/'.$cls.'.php';
108             return false;
109         case 'NewPollForm':
110         case 'PollResponseForm':
111         case 'PollResultForm':
112             include_once $dir.'/'.strtolower($cls).'.php';
113             return false;
114         default:
115             return true;
116         }
117     }
118
119     /**
120      * Map URLs to actions
121      *
122      * @param Net_URL_Mapper $m path-to-action mapper
123      *
124      * @return boolean hook value; true means continue processing, false means stop.
125      */
126
127     function onRouterInitialized($m)
128     {
129         $m->connect('main/poll/new',
130                     array('action' => 'newpoll'));
131
132         $m->connect('main/poll/:id',
133                     array('action' => 'showpoll'),
134                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
135
136         $m->connect('main/poll/response/:id',
137                     array('action' => 'showpollresponse'),
138                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
139
140         $m->connect('main/poll/:id/respond',
141                     array('action' => 'respondpoll'),
142                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
143
144         return true;
145     }
146
147     /**
148      * Plugin version data
149      *
150      * @param array &$versions array of version data
151      *
152      * @return value
153      */
154
155     function onPluginVersion(&$versions)
156     {
157         $versions[] = array('name' => 'Poll',
158                             'version' => self::VERSION,
159                             'author' => 'Brion Vibber',
160                             'homepage' => 'http://status.net/wiki/Plugin:Poll',
161                             'rawdescription' =>
162                             _m('Simple extension for supporting basic polls.'));
163         return true;
164     }
165
166     function types()
167     {
168         return array(self::POLL_OBJECT, self::POLL_RESPONSE_OBJECT);
169     }
170
171     /**
172      * When a notice is deleted, delete the related Poll
173      *
174      * @param Notice $notice Notice being deleted
175      *
176      * @return boolean hook value
177      */
178
179     function deleteRelated($notice)
180     {
181         $p = Poll::getByNotice($notice);
182
183         if (!empty($p)) {
184             $p->delete();
185         }
186
187         return true;
188     }
189
190     /**
191      * Save a poll from an activity
192      *
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
196      *
197      * @return Notice resulting notice
198      */
199
200     function saveNoticeFromActivity($activity, $profile, $options=array())
201     {
202         // @fixme
203         common_log(LOG_DEBUG, "XXX activity: " . var_export($activity, true));
204         common_log(LOG_DEBUG, "XXX profile: " . var_export($profile, true));
205         common_log(LOG_DEBUG, "XXX options: " . var_export($options, true));
206
207         // Ok for now, we can grab stuff from the XML entry directly.
208         // This won't work when reading from JSON source
209         if ($activity->entry) {
210             $pollElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'poll');
211             $responseElements = $activity->entry->getElementsByTagNameNS(self::POLL_OBJECT, 'response');
212             if ($pollElements->length) {
213                 $data = $pollElements->item(0);
214                 $question = $data->getAttribute('question');
215                 $opts = array();
216                 foreach ($data->attributes as $node) {
217                     $name = $node->nodeName;
218                     if (substr($name, 0, 6) == 'option') {
219                         $n = intval(substr($name, 6));
220                         if ($n > 0) {
221                             $opts[$n - 1] = $node->nodeValue;
222                         }
223                     }
224                 }
225                 common_log(LOG_DEBUG, "YYY question: $question");
226                 common_log(LOG_DEBUG, "YYY opts: " . var_export($opts, true));
227                 try {
228                     $notice = Poll::saveNew($profile, $question, $opts, $options);
229                     common_log(LOG_DEBUG, "YYY ok: " . $notice->id);
230                     return $notice;
231                 } catch (Exception $e) {
232                     common_log(LOG_DEBUG, "YYY fail: " . $e->getMessage());
233                 }
234             } else if ($responseElements->length) {
235                 $data = $responseElements->item(0);
236                 $pollUri = $data->getAttribute('poll');
237                 $selection = intval($data->getAttribute('selection'));
238
239                 if (!$pollUri) {
240                     throw new Exception('Invalid poll response: no poll reference.');
241                 }
242                 $poll = Poll::staticGet('uri', $pollUri);
243                 if (!$poll) {
244                     throw new Exception('Invalid poll response: poll is unknown.');
245                 }
246                 try {
247                     $notice = Poll_response::saveNew($profile, $poll, $selection, $options);
248                     common_log(LOG_DEBUG, "YYY response ok: " . $notice->id);
249                     return $notice;
250                 } catch (Exception $e) {
251                     common_log(LOG_DEBUG, "YYY response fail: " . $e->getMessage());
252                 }
253             } else {
254                 common_log(LOG_DEBUG, "YYY no poll data");
255             }
256         }
257     }
258
259     function activityObjectFromNotice($notice)
260     {
261         assert($this->isMyNotice($notice));
262
263         switch ($notice->object_type) {
264         case self::POLL_OBJECT:
265             return $this->activityObjectFromNoticePoll($notice);
266         case self::POLL_RESPONSE_OBJECT:
267             return $this->activityObjectFromNoticePollResponse($notice);
268         default:
269             throw new Exception('Unexpected type for poll plugin: ' . $notice->object_type);
270         }
271     }
272
273     function activityObjectFromNoticePollResponse($notice)
274     {
275         $object = new ActivityObject();
276         $object->id      = $notice->uri;
277         $object->type    = self::POLL_OBJECT;
278         $object->title   = $notice->content;
279         $object->summary = $notice->content;
280         $object->link    = $notice->bestUrl();
281
282         $response = Poll_response::getByNotice($notice);
283         $poll = $response->getPoll();
284
285         /**
286          * For the moment, using a kind of icky-looking schema that happens to
287          * work with out code for generating both Atom and JSON forms, though
288          * I don't like it:
289          *
290          * <poll:response xmlns:poll="http://apinamespace.org/activitystreams/object/poll"
291          *                poll="http://..../poll/...."
292          *                selection="3" />
293          *
294          * "poll:response": {
295          *     "xmlns:poll": http://apinamespace.org/activitystreams/object/poll
296          *     "uri": "http://..../poll/...."
297          *     "selection": 3
298          * }
299          *
300          */
301         // @fixme there's no way to specify an XML node tree here, like <poll><option/><option/></poll>
302         // @fixme there's no way to specify a JSON array or multi-level tree unless you break the XML attribs
303         // @fixme XML node contents don't get shown in JSON
304         $data = array('xmlns:poll' => self::POLL_OBJECT,
305                       'poll'       => $poll->uri,
306                       'selection'  => intval($response->selection));
307         $object->extra[] = array('poll:response', $data, '');
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             throw new Exception('Unexpected type for poll plugin: ' . $notice->object_type);
370         }
371     }
372
373     function showNoticePoll($notice, $out)
374     {
375         $user = common_current_user();
376
377         // @hack we want regular rendering, then just add stuff after that
378         $nli = new NoticeListItem($notice, $out);
379         $nli->showNotice();
380
381         $out->elementStart('div', array('class' => 'entry-content poll-content'));
382         $poll = Poll::getByNotice($notice);
383         if ($poll) {
384             if ($user) {
385                 $profile = $user->getProfile();
386                 $response = $poll->getResponse($profile);
387                 if ($response) {
388                     // User has already responded; show the results.
389                     $form = new PollResultForm($poll, $out);
390                 } else {
391                     $form = new PollResponseForm($poll, $out);
392                 }
393                 $form->show();
394             }
395         } else {
396             $out->text('Poll data is missing');
397         }
398         $out->elementEnd('div');
399
400         // @fixme
401         $out->elementStart('div', array('class' => 'entry-content'));
402     }
403
404     function showNoticePollResponse($notice, $out)
405     {
406         $user = common_current_user();
407
408         // @hack we want regular rendering, then just add stuff after that
409         $nli = new NoticeListItem($notice, $out);
410         $nli->showNotice();
411
412         // @fixme
413         $out->elementStart('div', array('class' => 'entry-content'));
414     }
415
416     function entryForm($out)
417     {
418         return new NewPollForm($out);
419     }
420
421     // @fixme is this from parent?
422     function tag()
423     {
424         return 'poll';
425     }
426
427     function appTitle()
428     {
429         return _m('Poll');
430     }
431 }