]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/QnAPlugin.php
[ROUTES] Allow accept-header specification during router creation
[quix0rs-gnu-social.git] / plugins / QnA / QnAPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2011, StatusNet, Inc.
5  *
6  * Microapp plugin for Questions and Answers
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  QnA
24  * @package   StatusNet
25  * @author    Zach Copley <zach@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     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Question and Answer plugin
39  *
40  * @category  Plugin
41  * @package   StatusNet
42  * @author    Zach Copley <zach@status.net>
43  * @copyright 2011 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class QnAPlugin extends MicroAppPlugin
48 {
49     const PLUGIN_VERSION = '2.0.0';
50
51     var $oldSaveNew = true;
52
53     /**
54      * Set up our tables (question and answer)
55      *
56      * @see Schema
57      * @see ColumnDef
58      *
59      * @return boolean hook value; true means continue processing, false means stop.
60      */
61     function onCheckSchema()
62     {
63         $schema = Schema::get();
64
65         $schema->ensureTable('qna_question', QnA_Question::schemaDef());
66         $schema->ensureTable('qna_answer', QnA_Answer::schemaDef());
67         $schema->ensureTable('qna_vote', QnA_Vote::schemaDef());
68
69         return true;
70     }
71
72     public function newFormAction() {
73         return 'qnanewquestion';
74     }
75
76     /**
77      * Map URLs to actions
78      *
79      * @param URLMapper $m path-to-action mapper
80      *
81      * @return boolean hook value; true means continue processing, false means stop.
82      */
83
84     public function onRouterInitialized(URLMapper $m)
85     {
86         $UUIDregex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
87
88         $m->connect('main/qna/newquestion',
89                     ['action' => 'qnanewquestion']);
90
91         $m->connect('answer/qna/closequestion',
92                     ['action' => 'qnaclosequestion']);
93
94         $m->connect('main/qna/newanswer',
95                     ['action' => 'qnanewanswer']);
96
97         $m->connect('main/qna/reviseanswer',
98                     ['action' => 'qnareviseanswer']);
99
100         $m->connect('question/vote/:id',
101                     ['action' => 'qnavote',
102                      'type'   => 'question'],
103                     ['id' => $UUIDregex]);
104
105         $m->connect('question/:id',
106                     ['action' => 'qnashowquestion'],
107                     ['id' => $UUIDregex]);
108
109         $m->connect('answer/vote/:id',
110                     ['action' => 'qnavote',
111                      'type'   => 'answer'],
112                     ['id' => $UUIDregex]);
113
114         $m->connect('answer/:id',
115                     ['action' => 'qnashowanswer'],
116                     ['id' => $UUIDregex]);
117
118         return true;
119     }
120
121     function onPluginVersion(array &$versions)
122     {
123         $versions[] = array(
124             'name'        => 'QnA',
125             'version'     => self::PLUGIN_VERSION,
126             'author'      => 'Zach Copley',
127             'homepage'    => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/QnA',
128             'description' =>
129              // TRANS: Plugin description.
130              _m('Question and Answers micro-app.')
131         );
132         return true;
133     }
134
135     function appTitle() {
136         // TRANS: Application title.
137         return _m('TITLE','Question');
138     }
139
140     function tag() {
141         return 'question';
142     }
143
144     function types() {
145         return array(
146             QnA_Question::OBJECT_TYPE,
147             QnA_Answer::OBJECT_TYPE
148         );
149     }
150
151     /**
152      * Given a parsed ActivityStreams activity, save it into a notice
153      * and other data structures.
154      *
155      * @param Activity $activity
156      * @param Profile $actor
157      * @param array $options=array()
158      *
159      * @return Notice the resulting notice
160      */
161     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
162     {
163         if (count($activity->objects) != 1) {
164             // TRANS: Exception thrown when there are too many activity objects.
165             throw new Exception(_m('Too many activity objects.'));
166         }
167
168         $questionObj = $activity->objects[0];
169
170         if ($questionObj->type != QnA_Question::OBJECT_TYPE) {
171             // TRANS: Exception thrown when an incorrect object type is encountered.
172             throw new Exception(_m('Wrong type for object.'));
173         }
174
175         $notice = null;
176
177         switch ($activity->verb) {
178         case ActivityVerb::POST:
179             $notice = QnA_Question::saveNew(
180                 $actor,
181                 $questionObj->title,
182                 $questionObj->summary,
183                 $options
184             );
185             break;
186         case Answer::ObjectType:
187             $question = QnA_Question::getKV('uri', $questionObj->id);
188             if (empty($question)) {
189                 // FIXME: save the question
190                 // TRANS: Exception thrown when answering a non-existing question.
191                 throw new Exception(_m('Answer to unknown question.'));
192             }
193             $notice = QnA_Answer::saveNew($actor, $question, $options);
194             break;
195         default:
196             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
197             throw new Exception(_m('Unknown object type.'));
198         }
199
200         return $notice;
201     }
202
203     /**
204      * Turn a Notice into an activity object
205      *
206      * @param Notice $notice
207      *
208      * @return ActivityObject
209      */
210
211     function activityObjectFromNotice(Notice $notice)
212     {
213         $question = null;
214
215         switch ($notice->object_type) {
216         case QnA_Question::OBJECT_TYPE:
217             $question = QnA_Question::fromNotice($notice);
218             break;
219         case QnA_Answer::OBJECT_TYPE:
220             $answer   = QnA_Answer::fromNotice($notice);
221             $question = $answer->getQuestion();
222             break;
223         }
224
225         if (empty($question)) {
226             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
227             throw new Exception(_m('Unknown object type.'));
228         }
229
230         $notice = $question->getNotice();
231
232         if (empty($notice)) {
233             // TRANS: Exception thrown when requesting a non-existing question notice.
234             throw new Exception(_m('Unknown question notice.'));
235         }
236
237         $obj = new ActivityObject();
238
239         $obj->id      = $question->uri;
240         $obj->type    = QnA_Question::OBJECT_TYPE;
241         $obj->title   = $question->title;
242         $obj->link    = $notice->getUrl();
243
244         // XXX: probably need other stuff here
245
246         return $obj;
247     }
248
249     /**
250      * Output our CSS class for QnA notice list elements
251      *
252      * @param NoticeListItem $nli The item being shown
253      *
254      * @return boolean hook value
255      */
256
257     function onStartOpenNoticeListItemElement(NoticeListItem $nli)
258     {
259         $type = $nli->notice->object_type;
260
261         switch($type)
262         {
263         case QnA_Question::OBJECT_TYPE:
264             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
265             $class = 'h-entry notice question';
266             if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
267                 $class .= ' limited-scope';
268             }
269
270             $question = QnA_Question::getKV('uri', $nli->notice->uri);
271
272             if (!empty($question->closed)) {
273                 $class .= ' closed';
274             }
275
276             $nli->out->elementStart(
277                 'li', array(
278                     'class' => $class,
279                     'id'    => 'notice-' . $id
280                 )
281             );
282             Event::handle('EndOpenNoticeListItemElement', array($nli));
283             return false;
284             break;
285         case QnA_Answer::OBJECT_TYPE:
286             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
287
288             $cls = array('h-entry', 'notice', 'answer');
289
290             $answer = QnA_Answer::getKV('uri', $nli->notice->uri);
291
292             if (!empty($answer) && !empty($answer->best)) {
293                 $cls[] = 'best';
294             }
295
296             $nli->out->elementStart(
297                 'li',
298                 array(
299                     'class' => implode(' ', $cls),
300                     'id'    => 'notice-' . $id
301                 )
302             );
303             Event::handle('EndOpenNoticeListItemElement', array($nli));
304             return false;
305             break;
306         default:
307             return true;
308         }
309
310         return true;
311     }
312
313     /**
314      * Output the HTML for this kind of object in a list
315      *
316      * @param NoticeListItem $nli The list item being shown.
317      *
318      * @return boolean hook value
319      *
320      * @todo FIXME: WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
321      */
322     function onStartShowNoticeItem(NoticeListItem $nli)
323     {
324         if (!$this->isMyNotice($nli->notice)) {
325             return true;
326         }
327
328         $out = $nli->out;
329         $notice = $nli->notice;
330
331         $nli->showNotice($notice, $out);
332
333         $nli->showNoticeLink();
334         $nli->showNoticeSource();
335         $nli->showNoticeLocation();
336         $nli->showPermalink();
337
338         $nli->showNoticeOptions();
339
340         if ($notice->object_type == QnA_Question::OBJECT_TYPE) {
341             $user = common_current_user();
342             $question = QnA_Question::getByNotice($notice);
343
344             if (!empty($user) and !empty($question)) {
345                 $profile = $user->getProfile();
346                 $answer = $question->getAnswer($profile);
347
348                 // Output a placeholder input -- clicking on it will
349                 // bring up a real answer form
350
351                 // NOTE: this whole ul is just a placeholder
352                 if (empty($question->closed) && empty($answer)) {
353                     $out->elementStart('ul', 'notices qna-dummy');
354                     $out->elementStart('li', 'qna-dummy-placeholder');
355                     $out->element(
356                         'input',
357                         array(
358                             'class' => 'placeholder',
359                             // TRANS: Placeholder value for a possible answer to a question
360                             // TRANS: by the logged in user.
361                             'value' => _m('Your answer...')
362                         )
363                     );
364                     $out->elementEnd('li');
365                     $out->elementEnd('ul');
366                 }
367             }
368         }
369
370         return false;
371     }
372
373     function adaptNoticeListItem($nli) {
374         return new QnAListItem($nli);
375     }
376
377     static function shorten($content, $notice)
378     {
379         $short = null;
380
381         if (Notice::contentTooLong($content)) {
382             common_debug("content too long");
383             $max = Notice::maxContent();
384             // TRANS: Link description for link to full notice text if it is longer than
385             // TRANS: what will be dispplayed.
386             $ellipsis = _m('…');
387             $short = mb_substr($content, 0, $max - 1);
388             $short .= sprintf('<a href="%1$s" rel="more" title="%2$s">%3$s</a>',
389                               $notice->getUrl(),
390                               // TRANS: Title for link that is an ellipsis in English.
391                               _m('more...'),
392                               $ellipsis);
393         } else {
394             $short = $content;
395         }
396
397         return $short;
398     }
399
400     /**
401      * Form for our app
402      *
403      * @param HTMLOutputter $out
404      * @return Widget
405      */
406     function entryForm($out)
407     {
408         return new QnanewquestionForm($out);
409     }
410
411     /**
412      * When a notice is deleted, clean up related tables.
413      *
414      * @param Notice $notice
415      */
416     function deleteRelated(Notice $notice)
417     {
418         switch ($notice->object_type) {
419         case QnA_Question::OBJECT_TYPE:
420             common_log(LOG_DEBUG, "Deleting question from notice...");
421             $question = QnA_Question::fromNotice($notice);
422             $question->delete();
423             break;
424         case QnA_Answer::OBJECT_TYPE:
425             common_log(LOG_DEBUG, "Deleting answer from notice...");
426             $answer = QnA_Answer::fromNotice($notice);
427             common_log(LOG_DEBUG, "to delete: $answer->id");
428             $answer->delete();
429             break;
430         default:
431             common_log(LOG_DEBUG, "Not deleting related, wtf...");
432         }
433     }
434
435     function onEndShowScripts($action)
436     {
437         $action->script($this->path('js/qna.js'));
438         return true;
439     }
440
441     function onEndShowStyles($action)
442     {
443         $action->cssLink($this->path('css/qna.css'));
444         return true;
445     }
446 }