]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/QnAPlugin.php
Merge request from robmyers upping the PHP version dependency
[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
50     var $oldSaveNew = true;
51
52     /**
53      * Set up our tables (question and answer)
54      *
55      * @see Schema
56      * @see ColumnDef
57      *
58      * @return boolean hook value; true means continue processing, false means stop.
59      */
60     function onCheckSchema()
61     {
62         $schema = Schema::get();
63
64         $schema->ensureTable('qna_question', QnA_Question::schemaDef());
65         $schema->ensureTable('qna_answer', QnA_Answer::schemaDef());
66         $schema->ensureTable('qna_vote', QnA_Vote::schemaDef());
67
68         return true;
69     }
70
71     public function newFormAction() {
72         return 'qnanewquestion';
73     }
74
75     /**
76      * Map URLs to actions
77      *
78      * @param Net_URL_Mapper $m path-to-action mapper
79      *
80      * @return boolean hook value; true means continue processing, false means stop.
81      */
82
83     function onRouterInitialized($m)
84     {
85         $UUIDregex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
86
87         $m->connect(
88             'main/qna/newquestion',
89             array('action' => 'qnanewquestion')
90         );
91         $m->connect(
92             'answer/qna/closequestion',
93             array('action' => 'qnaclosequestion')
94         );
95         $m->connect(
96             'main/qna/newanswer',
97             array('action' => 'qnanewanswer')
98         );
99         $m->connect(
100             'main/qna/reviseanswer',
101             array('action' => 'qnareviseanswer')
102         );
103         $m->connect(
104             'question/vote/:id',
105             array('action' => 'qnavote', 'type' => 'question'),
106             array('id' => $UUIDregex)
107         );
108         $m->connect(
109             'question/:id',
110             array('action' => 'qnashowquestion'),
111             array('id' => $UUIDregex)
112         );
113         $m->connect(
114             'answer/vote/:id',
115             array('action' => 'qnavote', 'type' => 'answer'),
116             array('id' => $UUIDregex)
117         );
118         $m->connect(
119             'answer/:id',
120             array('action' => 'qnashowanswer'),
121             array('id' => $UUIDregex)
122         );
123
124         return true;
125     }
126
127     function onPluginVersion(&$versions)
128     {
129         $versions[] = array(
130             'name'        => 'QnA',
131             'version'     => GNUSOCIAL_VERSION,
132             'author'      => 'Zach Copley',
133             'homepage'    => 'http://status.net/wiki/Plugin:QnA',
134             'description' =>
135              // TRANS: Plugin description.
136              _m('Question and Answers micro-app.')
137         );
138         return true;
139     }
140
141     function appTitle() {
142         // TRANS: Application title.
143         return _m('TITLE','Question');
144     }
145
146     function tag() {
147         return 'question';
148     }
149
150     function types() {
151         return array(
152             QnA_Question::OBJECT_TYPE,
153             QnA_Answer::OBJECT_TYPE
154         );
155     }
156
157     /**
158      * Given a parsed ActivityStreams activity, save it into a notice
159      * and other data structures.
160      *
161      * @param Activity $activity
162      * @param Profile $actor
163      * @param array $options=array()
164      *
165      * @return Notice the resulting notice
166      */
167     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
168     {
169         if (count($activity->objects) != 1) {
170             // TRANS: Exception thrown when there are too many activity objects.
171             throw new Exception(_m('Too many activity objects.'));
172         }
173
174         $questionObj = $activity->objects[0];
175
176         if ($questionObj->type != QnA_Question::OBJECT_TYPE) {
177             // TRANS: Exception thrown when an incorrect object type is encountered.
178             throw new Exception(_m('Wrong type for object.'));
179         }
180
181         $notice = null;
182
183         switch ($activity->verb) {
184         case ActivityVerb::POST:
185             $notice = QnA_Question::saveNew(
186                 $actor,
187                 $questionObj->title,
188                 $questionObj->summary,
189                 $options
190             );
191             break;
192         case Answer::ObjectType:
193             $question = QnA_Question::getKV('uri', $questionObj->id);
194             if (empty($question)) {
195                 // FIXME: save the question
196                 // TRANS: Exception thrown when answering a non-existing question.
197                 throw new Exception(_m('Answer to unknown question.'));
198             }
199             $notice = QnA_Answer::saveNew($actor, $question, $options);
200             break;
201         default:
202             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
203             throw new Exception(_m('Unknown object type.'));
204         }
205
206         return $notice;
207     }
208
209     /**
210      * Turn a Notice into an activity object
211      *
212      * @param Notice $notice
213      *
214      * @return ActivityObject
215      */
216
217     function activityObjectFromNotice(Notice $notice)
218     {
219         $question = null;
220
221         switch ($notice->object_type) {
222         case QnA_Question::OBJECT_TYPE:
223             $question = QnA_Question::fromNotice($notice);
224             break;
225         case QnA_Answer::OBJECT_TYPE:
226             $answer   = QnA_Answer::fromNotice($notice);
227             $question = $answer->getQuestion();
228             break;
229         }
230
231         if (empty($question)) {
232             // TRANS: Exception thrown when an object type is encountered that cannot be handled.
233             throw new Exception(_m('Unknown object type.'));
234         }
235
236         $notice = $question->getNotice();
237
238         if (empty($notice)) {
239             // TRANS: Exception thrown when requesting a non-existing question notice.
240             throw new Exception(_m('Unknown question notice.'));
241         }
242
243         $obj = new ActivityObject();
244
245         $obj->id      = $question->uri;
246         $obj->type    = QnA_Question::OBJECT_TYPE;
247         $obj->title   = $question->title;
248         $obj->link    = $notice->getUrl();
249
250         // XXX: probably need other stuff here
251
252         return $obj;
253     }
254
255     /**
256      * Output our CSS class for QnA notice list elements
257      *
258      * @param NoticeListItem $nli The item being shown
259      *
260      * @return boolean hook value
261      */
262
263     function onStartOpenNoticeListItemElement($nli)
264     {
265         $type = $nli->notice->object_type;
266
267         switch($type)
268         {
269         case QnA_Question::OBJECT_TYPE:
270             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
271             $class = 'h-entry notice question';
272             if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
273                 $class .= ' limited-scope';
274             }
275
276             $question = QnA_Question::getKV('uri', $nli->notice->uri);
277
278             if (!empty($question->closed)) {
279                 $class .= ' closed';
280             }
281
282             $nli->out->elementStart(
283                 'li', array(
284                     'class' => $class,
285                     'id'    => 'notice-' . $id
286                 )
287             );
288             Event::handle('EndOpenNoticeListItemElement', array($nli));
289             return false;
290             break;
291         case QnA_Answer::OBJECT_TYPE:
292             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
293
294             $cls = array('h-entry', 'notice', 'answer');
295
296             $answer = QnA_Answer::getKV('uri', $nli->notice->uri);
297
298             if (!empty($answer) && !empty($answer->best)) {
299                 $cls[] = 'best';
300             }
301
302             $nli->out->elementStart(
303                 'li',
304                 array(
305                     'class' => implode(' ', $cls),
306                     'id'    => 'notice-' . $id
307                 )
308             );
309             Event::handle('EndOpenNoticeListItemElement', array($nli));
310             return false;
311             break;
312         default:
313             return true;
314         }
315
316         return true;
317     }
318
319     /**
320      * Custom HTML output for our notices
321      *
322      * @param Notice $notice
323      * @param HTMLOutputter $out
324      */
325     function showNoticeContent(Notice $notice, $out)
326     {
327         switch ($notice->object_type) {
328         case QnA_Question::OBJECT_TYPE:
329             return $this->showNoticeQuestion($notice, $out);
330         case QnA_Answer::OBJECT_TYPE:
331             return $this->showNoticeAnswer($notice, $out);
332         default:
333             throw new Exception(
334                 // TRANS: Exception thrown when performing an unexpected action on a question.
335                 // TRANS: %s is the unpexpected object type.
336                 sprintf(_m('Unexpected type for QnA plugin: %s.'),
337                         $notice->object_type
338                 )
339             );
340         }
341     }
342
343     function showNoticeQuestion(Notice $notice, $out)
344     {
345         $user = common_current_user();
346
347         // @hack we want regular rendering, then just add stuff after that
348         $nli = new NoticeListItem($notice, $out);
349         $nli->showNotice();
350
351         $out->elementStart('div', array('class' => 'e-content question-description'));
352
353         $question = QnA_Question::getByNotice($notice);
354
355         if (!empty($question)) {
356
357             $form = new QnashowquestionForm($out, $question);
358             $form->show();
359
360         } else {
361             // TRANS: Error message displayed when question data is not present.
362             $out->text(_m('Question data is missing.'));
363         }
364         $out->elementEnd('div');
365
366         // @fixme
367         $out->elementStart('div', array('class' => 'e-content'));
368     }
369
370     /**
371      * Output the HTML for this kind of object in a list
372      *
373      * @param NoticeListItem $nli The list item being shown.
374      *
375      * @return boolean hook value
376      *
377      * @todo FIXME: WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
378      */
379     function onStartShowNoticeItem($nli)
380     {
381         if (!$this->isMyNotice($nli->notice)) {
382             return true;
383         }
384
385         $out = $nli->out;
386         $notice = $nli->notice;
387
388         $this->showNotice($notice, $out);
389
390         $nli->showNoticeLink();
391         $nli->showNoticeSource();
392         $nli->showNoticeLocation();
393         $nli->showContext();
394         $nli->showRepeat();
395
396         $out->elementEnd('div');
397
398         $nli->showNoticeOptions();
399
400         if ($notice->object_type == QnA_Question::OBJECT_TYPE) {
401             $user = common_current_user();
402             $question = QnA_Question::getByNotice($notice);
403
404             if (!empty($user) and !empty($question)) {
405                 $profile = $user->getProfile();
406                 $answer = $question->getAnswer($profile);
407
408                 // Output a placeholder input -- clicking on it will
409                 // bring up a real answer form
410
411                 // NOTE: this whole ul is just a placeholder
412                 if (empty($question->closed) && empty($answer)) {
413                     $out->elementStart('ul', 'notices qna-dummy');
414                     $out->elementStart('li', 'qna-dummy-placeholder');
415                     $out->element(
416                         'input',
417                         array(
418                             'class' => 'placeholder',
419                             // TRANS: Placeholder value for a possible answer to a question
420                             // TRANS: by the logged in user.
421                             'value' => _m('Your answer...')
422                         )
423                     );
424                     $out->elementEnd('li');
425                     $out->elementEnd('ul');
426                 }
427             }
428         }
429
430         return false;
431     }
432
433     function showNoticeAnswer(Notice $notice, $out)
434     {
435         $user = common_current_user();
436
437         $answer   = QnA_Answer::getByNotice($notice);
438         $question = $answer->getQuestion();
439
440         $nli = new NoticeListItem($notice, $out);
441         $nli->showNotice();
442
443         $out->elementStart('div', array('class' => 'e-content answer-content'));
444
445         if (!empty($answer)) {
446             $form = new QnashowanswerForm($out, $answer);
447             $form->show();
448         } else {
449             // TRANS: Error message displayed when answer data is not present.
450             $out->text(_m('Answer data is missing.'));
451         }
452
453         $out->elementEnd('div');
454
455         // @todo FIXME
456         $out->elementStart('div', array('class' => 'e-content'));
457     }
458
459     static function shorten($content, $notice)
460     {
461         $short = null;
462
463         if (Notice::contentTooLong($content)) {
464             common_debug("content too long");
465             $max = Notice::maxContent();
466             // TRANS: Link description for link to full notice text if it is longer than
467             // TRANS: what will be dispplayed.
468             $ellipsis = _m('…');
469             $short = mb_substr($content, 0, $max - 1);
470             $short .= sprintf('<a href="%1$s" rel="more" title="%2$s">%3$s</a>',
471                               $notice->getUrl(),
472                               // TRANS: Title for link that is an ellipsis in English.
473                               _m('more...'),
474                               $ellipsis);
475         } else {
476             $short = $content;
477         }
478
479         return $short;
480     }
481
482     /**
483      * Form for our app
484      *
485      * @param HTMLOutputter $out
486      * @return Widget
487      */
488     function entryForm($out)
489     {
490         return new QnanewquestionForm($out);
491     }
492
493     /**
494      * When a notice is deleted, clean up related tables.
495      *
496      * @param Notice $notice
497      */
498     function deleteRelated(Notice $notice)
499     {
500         switch ($notice->object_type) {
501         case QnA_Question::OBJECT_TYPE:
502             common_log(LOG_DEBUG, "Deleting question from notice...");
503             $question = QnA_Question::fromNotice($notice);
504             $question->delete();
505             break;
506         case QnA_Answer::OBJECT_TYPE:
507             common_log(LOG_DEBUG, "Deleting answer from notice...");
508             $answer = QnA_Answer::fromNotice($notice);
509             common_log(LOG_DEBUG, "to delete: $answer->id");
510             $answer->delete();
511             break;
512         default:
513             common_log(LOG_DEBUG, "Not deleting related, wtf...");
514         }
515     }
516
517     function onEndShowScripts($action)
518     {
519         $action->script($this->path('js/qna.js'));
520         return true;
521     }
522
523     function onEndShowStyles($action)
524     {
525         $action->cssLink($this->path('css/qna.css'));
526         return true;
527     }
528 }