]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Improve dba::selectFirst calls
[friendica.git] / src / Object / Post.php
1 <?php
2 /**
3  * @file src/Object/Post.php
4  */
5 namespace Friendica\Object;
6
7 use Friendica\BaseObject;
8 use Friendica\Content\ContactSelector;
9 use Friendica\Content\Feature;
10 use Friendica\Core\PConfig;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use dba;
14
15 require_once 'include/dba.php';
16 require_once 'include/text.php';
17 require_once 'boot.php';
18 require_once 'include/conversation.php';
19
20 /**
21  * An item
22  */
23 class Post extends BaseObject
24 {
25         private $data = array();
26         private $template = null;
27         private $available_templates = array(
28                 'wall' => 'wall_thread.tpl',
29                 'wall2wall' => 'wallwall_thread.tpl'
30         );
31         private $comment_box_template = 'comment_item.tpl';
32         private $toplevel = false;
33         private $writable = false;
34         private $children = array();
35         private $parent = null;
36         private $thread = null;
37         private $redirect_url = null;
38         private $owner_url = '';
39         private $owner_photo = '';
40         private $owner_name = '';
41         private $wall_to_wall = false;
42         private $threaded = false;
43         private $visiting = false;
44
45         /**
46          * Constructor
47          *
48          * @param array $data data array
49          */
50         public function __construct(array $data)
51         {
52                 $a = self::getApp();
53
54                 $this->data = $data;
55                 $this->setTemplate('wall');
56                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
57
58                 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
59                         foreach ($_SESSION['remote'] as $visitor) {
60                                 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
61                                         $this->visiting = true;
62                                         break;
63                                 }
64                         }
65                 }
66
67                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
68                 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
69
70                 if (!$this->isToplevel()) {
71                         $this->threaded = true;
72                 }
73
74                 // Prepare the children
75                 if (count($data['children'])) {
76                         foreach ($data['children'] as $item) {
77                                 // Only add will be displayed
78                                 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
79                                         continue;
80                                 } elseif (!visible_activity($item)) {
81                                         continue;
82                                 }
83
84                                 // You can always comment on Diaspora items
85                                 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
86                                         $item['writable'] = true;
87                                 }
88
89                                 $item['pagedrop'] = $data['pagedrop'];
90                                 $child = new Post($item);
91                                 $this->addChild($child);
92                         }
93                 }
94         }
95
96         /**
97          * Get data in a form usable by a conversation template
98          *
99          * @param object  $conv_responses conversation responses
100          * @param integer $thread_level   default = 1
101          *
102          * @return mixed The data requested on success
103          *               false on failure
104          */
105         public function getTemplateData($conv_responses, $thread_level = 1)
106         {
107                 require_once "mod/proxy.php";
108
109                 $result = array();
110
111                 $a = self::getApp();
112
113                 $item = $this->getData();
114                 $edited = false;
115                 // If the time between "created" and "edited" differs we add
116                 // a notice that the post was edited.
117                 // Note: In some networks reshared items seem to have (sometimes) a difference
118                 // between creation time and edit time of a second. Thats why we add the notice
119                 // only if the difference is more than 1 second.
120                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
121                         $edited = array(
122                                 'label'    => t('This entry was edited'),
123                                 'date'     => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
124                                 'relative' => relative_date($item['edited'])
125                         );
126                 }
127                 $commentww = '';
128                 $sparkle = '';
129                 $buttons = '';
130                 $dropping = false;
131                 $star = false;
132                 $ignore = false;
133                 $isstarred = "unstarred";
134                 $indent = '';
135                 $shiny = '';
136                 $osparkle = '';
137                 $total_children = $this->countDescendants();
138
139                 $conv = $this->getThread();
140
141                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
142                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
143                         ? t('Private Message')
144                         : false);
145                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
146
147                 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
148                         if ($item["event-id"] != 0) {
149                                 $edpost = array("events/event/" . $item['event-id'], t("Edit"));
150                         } else {
151                                 $edpost = array("editpost/" . $item['id'], t("Edit"));
152                         }
153                         $dropping = in_array($item['uid'], [0, local_user()]);
154                 } else {
155                         $edpost = false;
156                 }
157
158                 // Editing on items of not subscribed users isn't currently possible
159                 // There are some issues on editing that prevent this.
160                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
161                 if ($item['uid'] == 0) {
162                         $edpost = false;
163                 }
164
165                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
166                         $dropping = true;
167                 }
168
169                 $drop = array(
170                         'dropping' => $dropping,
171                         'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
172                         'select'   => t('Select'),
173                         'delete'   => t('Delete'),
174                 );
175
176                 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
177
178                 $diff_author = !link_compare($item['url'], $item['author-link']);
179                 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
180                 if ($item['author-link'] && (!$item['author-name'])) {
181                         $profile_name = $item['author-link'];
182                 }
183
184                 $sp = false;
185                 $profile_link = best_link_url($item, $sp);
186                 if ($profile_link === 'mailbox') {
187                         $profile_link = '';
188                 }
189
190                 if ($sp) {
191                         $sparkle = ' sparkle';
192                 } else {
193                         $profile_link = zrl($profile_link);
194                 }
195
196                 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
197                         $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
198                         if ($author_contact["thumb"]) {
199                                 $item['author-thumb'] = $author_contact["thumb"];
200                         } else {
201                                 $item['author-thumb'] = $item['author-avatar'];
202                         }
203                 }
204
205                 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
206                         $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
207                         if ($owner_contact["thumb"]) {
208                                 $item['owner-thumb'] = $owner_contact["thumb"];
209                         } else {
210                                 $item['owner-thumb'] = $item['owner-avatar'];
211                         }
212                 }
213
214                 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
215                 call_hooks('render_location', $locate);
216                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
217
218                 // process action responses - e.g. like/dislike/attend/agree/whatever
219                 $response_verbs = array('like', 'dislike');
220
221                 $isevent = false;
222                 $attend = [];
223                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
224                         $response_verbs[] = 'attendyes';
225                         $response_verbs[] = 'attendno';
226                         $response_verbs[] = 'attendmaybe';
227                         if ($conv->isWritable()) {
228                                 $isevent = true;
229                                 $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
230                         }
231                 }
232
233                 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
234
235                 foreach ($response_verbs as $value => $verbs) {
236                         $responses[$verbs]['output'] = x($conv_responses[$verbs], $item['uri']) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '';
237                 }
238
239                 /*
240                  * We should avoid doing this all the time, but it depends on the conversation mode
241                  * And the conv mode may change when we change the conv, or it changes its mode
242                  * Maybe we should establish a way to be notified about conversation changes
243                  */
244                 $this->checkWallToWall();
245
246                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
247                         $osparkle = ' sparkle';
248                 }
249
250                 $tagger = '';
251
252                 if ($this->isToplevel()) {
253                         if ($conv->getProfileOwner() == local_user()) {
254                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
255
256                                 $star = array(
257                                         'do'        => t("add star"),
258                                         'undo'      => t("remove star"),
259                                         'toggle'    => t("toggle star status"),
260                                         'classdo'   => $item['starred'] ? "hidden" : "",
261                                         'classundo' => $item['starred'] ? "" : "hidden",
262                                         'starred'   => t('starred'),
263                                 );
264                                 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
265                                 if (DBM::is_result($thread)) {
266                                         $ignore = array(
267                                                 'do'        => t("ignore thread"),
268                                                 'undo'      => t("unignore thread"),
269                                                 'toggle'    => t("toggle ignore status"),
270                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
271                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
272                                                 'ignored'   => t('ignored'),
273                                         );
274                                 }
275
276                                 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
277                                         $tagger = array(
278                                                 'add'   => t("add tag"),
279                                                 'class' => "",
280                                         );
281                                 }
282                         }
283                 } else {
284                         $indent = 'comment';
285                 }
286
287                 if ($conv->isWritable()) {
288                         $buttons = array(
289                                 'like'    => array(t("I like this \x28toggle\x29"), t("like")),
290                                 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
291                         );
292                         if ($shareable) {
293                                 $buttons['share'] = array(t('Share this'), t('share'));
294                         }
295
296                         // If a contact isn't writable, we cannot send a like or dislike to it
297                         if (!$item['writable']) {
298                                 unset($buttons["like"]);
299                                 unset($buttons["dislike"]);
300                         }
301                 }
302
303                 $comment = $this->getCommentBox($indent);
304
305                 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
306                         $shiny = 'shiny';
307                 }
308
309                 localize_item($item);
310
311                 $body = prepare_body($item, true);
312
313                 list($categories, $folders) = get_cats_and_terms($item);
314
315                 $body_e       = $body;
316                 $text_e       = strip_tags($body);
317                 $name_e       = $profile_name;
318                 $title_e      = $item['title'];
319                 $location_e   = $location;
320                 $owner_name_e = $this->getOwnerName();
321
322                 // Disable features that aren't available in several networks
323                 /// @todo Add NETWORK_DIASPORA when it will pass this information
324                 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
325                         unset($buttons["dislike"]);
326                         $isevent = false;
327                         $tagger = '';
328                 }
329
330                 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
331                         unset($buttons["like"]);
332                 }
333
334                 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
335                         unset($buttons["like"]);
336                 }
337
338                 $tmp_item = array(
339                         'template'        => $this->getTemplate(),
340                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
341                         'tags'            => $item['tags'],
342                         'hashtags'        => $item['hashtags'],
343                         'mentions'        => $item['mentions'],
344                         'txt_cats'        => t('Categories:'),
345                         'txt_folders'     => t('Filed under:'),
346                         'has_cats'        => ((count($categories)) ? 'true' : ''),
347                         'has_folders'     => ((count($folders)) ? 'true' : ''),
348                         'categories'      => $categories,
349                         'folders'         => $folders,
350                         'body'            => $body_e,
351                         'text'            => $text_e,
352                         'id'              => $this->getId(),
353                         'guid'            => urlencode($item['guid']),
354                         'isevent'         => $isevent,
355                         'attend'          => $attend,
356                         'linktitle'       => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
357                         'olinktitle'      => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
358                         'to'              => t('to'),
359                         'via'             => t('via'),
360                         'wall'            => t('Wall-to-Wall'),
361                         'vwall'           => t('via Wall-To-Wall:'),
362                         'profile_url'     => $profile_link,
363                         'item_photo_menu' => item_photo_menu($item),
364                         'name'            => $name_e,
365                         'thumb'           => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
366                         'osparkle'        => $osparkle,
367                         'sparkle'         => $sparkle,
368                         'title'           => $title_e,
369                         'localtime'       => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
370                         'ago'             => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
371                         'app'             => $item['app'],
372                         'created'         => relative_date($item['created']),
373                         'lock'            => $lock,
374                         'location'        => $location_e,
375                         'indent'          => $indent,
376                         'shiny'           => $shiny,
377                         'owner_url'       => $this->getOwnerUrl(),
378                         'owner_photo'     => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
379                         'owner_name'      => htmlentities($owner_name_e),
380                         'plink'           => get_plink($item),
381                         'edpost'          => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
382                         'isstarred'       => $isstarred,
383                         'star'            => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
384                         'ignore'          => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
385                         'tagger'          => $tagger,
386                         'filer'           => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
387                         'drop'            => $drop,
388                         'vote'            => $buttons,
389                         'like'            => $responses['like']['output'],
390                         'dislike'         => $responses['dislike']['output'],
391                         'responses'       => $responses,
392                         'switchcomment'   => t('Comment'),
393                         'comment'         => $comment,
394                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
395                         'wait'            => t('Please wait'),
396                         'thread_level'    => $thread_level,
397                         'edited'          => $edited,
398                         'network'         => $item["item_network"],
399                         'network_name'    => ContactSelector::networkToName($item['item_network'], $profile_link),
400                         'received'        => $item['received'],
401                         'commented'       => $item['commented'],
402                         'created_date'    => $item['created'],
403                 );
404
405                 $arr = array('item' => $item, 'output' => $tmp_item);
406                 call_hooks('display_item', $arr);
407
408                 $result = $arr['output'];
409
410                 $result['children'] = array();
411                 $children = $this->getChildren();
412                 $nb_children = count($children);
413                 if ($nb_children > 0) {
414                         foreach ($children as $child) {
415                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
416                         }
417                         // Collapse
418                         if (($nb_children > 2) || ($thread_level > 1)) {
419                                 $result['children'][0]['comment_firstcollapsed'] = true;
420                                 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
421                                 $result['children'][0]['hidden_comments_num'] = $total_children;
422                                 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
423                                 $result['children'][0]['hide_text'] = t('show more');
424                                 if ($thread_level > 1) {
425                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
426                                 } else {
427                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
428                                 }
429                         }
430                 }
431
432                 if ($this->isToplevel()) {
433                         $result['total_comments_num'] = "$total_children";
434                         $result['total_comments_text'] = tt('comment', 'comments', $total_children);
435                 }
436
437                 $result['private'] = $item['private'];
438                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
439
440                 if ($this->isThreaded()) {
441                         $result['flatten'] = false;
442                         $result['threaded'] = true;
443                 } else {
444                         $result['flatten'] = true;
445                         $result['threaded'] = false;
446                 }
447
448                 return $result;
449         }
450
451         /**
452          * @return integer
453          */
454         public function getId()
455         {
456                 return $this->getDataValue('id');
457         }
458
459         /**
460          * @return boolean
461          */
462         public function isThreaded()
463         {
464                 return $this->threaded;
465         }
466
467         /**
468          * Add a child item
469          *
470          * @param object $item The child item to add
471          *
472          * @return mixed
473          */
474         public function addChild(Post $item)
475         {
476                 $item_id = $item->getId();
477                 if (!$item_id) {
478                         logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
479                         return false;
480                 } elseif ($this->getChild($item->getId())) {
481                         logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
482                         return false;
483                 }
484                 /*
485                  * Only add what will be displayed
486                  */
487                 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
488                         return false;
489                 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
490                         return false;
491                 }
492
493                 $item->setParent($this);
494                 $this->children[] = $item;
495
496                 return end($this->children);
497         }
498
499         /**
500          * Get a child by its ID
501          *
502          * @param integer $id The child id
503          *
504          * @return mixed
505          */
506         public function getChild($id)
507         {
508                 foreach ($this->getChildren() as $child) {
509                         if ($child->getId() == $id) {
510                                 return $child;
511                         }
512                 }
513
514                 return null;
515         }
516
517         /**
518          * Get all our children
519          *
520          * @return object
521          */
522         public function getChildren()
523         {
524                 return $this->children;
525         }
526
527         /**
528          * Set our parent
529          *
530          * @param object $item The item to set as parent
531          *
532          * @return void
533          */
534         protected function setParent($item)
535         {
536                 $parent = $this->getParent();
537                 if ($parent) {
538                         $parent->removeChild($this);
539                 }
540
541                 $this->parent = $item;
542                 $this->setThread($item->getThread());
543         }
544
545         /**
546          * Remove our parent
547          *
548          * @return void
549          */
550         protected function removeParent()
551         {
552                 $this->parent = null;
553                 $this->thread = null;
554         }
555
556         /**
557          * Remove a child
558          *
559          * @param object $item The child to be removed
560          *
561          * @return boolean Success or failure
562          */
563         public function removeChild($item)
564         {
565                 $id = $item->getId();
566                 foreach ($this->getChildren() as $key => $child) {
567                         if ($child->getId() == $id) {
568                                 $child->removeParent();
569                                 unset($this->children[$key]);
570                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
571                                 $this->children = array_values($this->children);
572                                 return true;
573                         }
574                 }
575                 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
576                 return false;
577         }
578
579         /**
580          * Get parent item
581          *
582          * @return object
583          */
584         protected function getParent()
585         {
586                 return $this->parent;
587         }
588
589         /**
590          * Set conversation
591          *
592          * @param object $conv The conversation
593          *
594          * @return void
595          */
596         public function setThread($conv)
597         {
598                 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
599
600                 $this->thread = $conv;
601
602                 // Set it on our children too
603                 foreach ($this->getChildren() as $child) {
604                         $child->setThread($conv);
605                 }
606         }
607
608         /**
609          * Get conversation
610          *
611          * @return object
612          */
613         public function getThread()
614         {
615                 return $this->thread;
616         }
617
618         /**
619          * Get raw data
620          *
621          * We shouldn't need this
622          *
623          * @return array
624          */
625         public function getData()
626         {
627                 return $this->data;
628         }
629
630         /**
631          * Get a data value
632          *
633          * @param object $name key
634          *
635          * @return mixed value on success
636          *               false on failure
637          */
638         public function getDataValue($name)
639         {
640                 if (!isset($this->data[$name])) {
641                         // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
642                         return false;
643                 }
644
645                 return $this->data[$name];
646         }
647
648         /**
649          * Set template
650          *
651          * @param object $name template name
652          *
653          * @return void
654          */
655         private function setTemplate($name)
656         {
657                 if (!x($this->available_templates, $name)) {
658                         logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
659                         return false;
660                 }
661
662                 $this->template = $this->available_templates[$name];
663         }
664
665         /**
666          * Get template
667          *
668          * @return object
669          */
670         private function getTemplate()
671         {
672                 return $this->template;
673         }
674
675         /**
676          * Check if this is a toplevel post
677          *
678          * @return boolean
679          */
680         private function isToplevel()
681         {
682                 return $this->toplevel;
683         }
684
685         /**
686          * Check if this is writable
687          *
688          * @return boolean
689          */
690         private function isWritable()
691         {
692                 $conv = $this->getThread();
693
694                 if ($conv) {
695                         // This will allow us to comment on wall-to-wall items owned by our friends
696                         // and community forums even if somebody else wrote the post.
697                         // bug #517 - this fixes for conversation owner
698                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
699                                 return true;
700                         }
701
702                         // this fixes for visitors
703                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
704                 }
705                 return $this->writable;
706         }
707
708         /**
709          * Count the total of our descendants
710          *
711          * @return integer
712          */
713         private function countDescendants()
714         {
715                 $children = $this->getChildren();
716                 $total = count($children);
717                 if ($total > 0) {
718                         foreach ($children as $child) {
719                                 $total += $child->countDescendants();
720                         }
721                 }
722
723                 return $total;
724         }
725
726         /**
727          * Get the template for the comment box
728          *
729          * @return string
730          */
731         private function getCommentBoxTemplate()
732         {
733                 return $this->comment_box_template;
734         }
735
736         /**
737          * Get the comment box
738          *
739          * @param string $indent Indent value
740          *
741          * @return mixed The comment box string (empty if no comment box)
742          *               false on failure
743          */
744         private function getCommentBox($indent)
745         {
746                 $a = self::getApp();
747
748                 $comment_box = '';
749                 $conv = $this->getThread();
750                 $ww = '';
751                 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
752                         $ww = 'ww';
753                 }
754
755                 if ($conv->isWritable() && $this->isWritable()) {
756                         $qc = $qcomment = null;
757
758                         /*
759                          * Hmmm, code depending on the presence of a particular plugin?
760                          * This should be better if done by a hook
761                          */
762                         if (in_array('qcomment', $a->plugins)) {
763                                 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
764                                 $qcomment = (($qc) ? explode("\n", $qc) : null);
765                         }
766
767                         // Fetch the user id from the parent when the owner user is empty
768                         $uid = $conv->getProfileOwner();
769                         $parent_uid = $this->getDataValue('uid');
770
771                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
772                                 $uid = $parent_uid;
773                         }
774
775                         $template = get_markup_template($this->getCommentBoxTemplate());
776                         $comment_box = replace_macros($template, array(
777                                 '$return_path' => $a->query_string,
778                                 '$threaded'    => $this->isThreaded(),
779                                 '$jsreload'    => '',
780                                 '$type'        => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
781                                 '$id'          => $this->getId(),
782                                 '$parent'      => $this->getId(),
783                                 '$qcomment'    => $qcomment,
784                                 '$profile_uid' => $uid,
785                                 '$mylink'      => $a->remove_baseurl($a->contact['url']),
786                                 '$mytitle'     => t('This is you'),
787                                 '$myphoto'     => $a->remove_baseurl($a->contact['thumb']),
788                                 '$comment'     => t('Comment'),
789                                 '$submit'      => t('Submit'),
790                                 '$edbold'      => t('Bold'),
791                                 '$editalic'    => t('Italic'),
792                                 '$eduline'     => t('Underline'),
793                                 '$edquote'     => t('Quote'),
794                                 '$edcode'      => t('Code'),
795                                 '$edimg'       => t('Image'),
796                                 '$edurl'       => t('Link'),
797                                 '$edvideo'     => t('Video'),
798                                 '$preview'     => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
799                                 '$indent'      => $indent,
800                                 '$sourceapp'   => t($a->sourcename),
801                                 '$ww'          => $conv->getMode() === 'network' ? $ww : '',
802                                 '$rand_num'    => random_digits(12)
803                         ));
804                 }
805
806                 return $comment_box;
807         }
808
809         /**
810          * @return string
811          */
812         private function getRedirectUrl()
813         {
814                 return $this->redirect_url;
815         }
816
817         /**
818          * Check if we are a wall to wall item and set the relevant properties
819          *
820          * @return void
821          */
822         protected function checkWallToWall()
823         {
824                 $a = self::getApp();
825                 $conv = $this->getThread();
826                 $this->wall_to_wall = false;
827
828                 if ($this->isToplevel()) {
829                         if ($conv->getMode() !== 'profile') {
830                                 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
831                                         // On the network page, I am the owner. On the display page it will be the profile owner.
832                                         // This will have been stored in $a->page_contact by our calling page.
833                                         // Put this person as the wall owner of the wall-to-wall notice.
834
835                                         $this->owner_url = zrl($a->page_contact['url']);
836                                         $this->owner_photo = $a->page_contact['thumb'];
837                                         $this->owner_name = $a->page_contact['name'];
838                                         $this->wall_to_wall = true;
839                                 } elseif ($this->getDataValue('owner-link')) {
840                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
841                                         $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
842                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
843
844                                         if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
845                                                 // The author url doesn't match the owner (typically the contact)
846                                                 // and also doesn't match the contact alias.
847                                                 // The name match is a hack to catch several weird cases where URLs are
848                                                 // all over the park. It can be tricked, but this prevents you from
849                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
850                                                 // well that it's the same Bob Smith.
851                                                 // But it could be somebody else with the same name. It just isn't highly likely.
852
853
854                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
855                                                 $this->owner_name = $this->getDataValue('owner-name');
856                                                 $this->wall_to_wall = true;
857                                                 // If it is our contact, use a friendly redirect link
858                                                 if ($this->getDataValue('network') === NETWORK_DFRN
859                                                         && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
860                                                 ) {
861                                                         $this->owner_url = $this->getRedirectUrl();
862                                                 } else {
863                                                         $this->owner_url = zrl($this->getDataValue('owner-link'));
864                                                 }
865                                         }
866                                 }
867                         }
868                 }
869
870                 if (!$this->wall_to_wall) {
871                         $this->setTemplate('wall');
872                         $this->owner_url = '';
873                         $this->owner_photo = '';
874                         $this->owner_name = '';
875                 }
876         }
877
878         /**
879          * @return boolean
880          */
881         private function isWallToWall()
882         {
883                 return $this->wall_to_wall;
884         }
885
886         /**
887          * @return string
888          */
889         private function getOwnerUrl()
890         {
891                 return $this->owner_url;
892         }
893
894         /**
895          * @return string
896          */
897         private function getOwnerName()
898         {
899                 return $this->owner_name;
900         }
901
902         /**
903          * @return boolean
904          */
905         private function isVisiting()
906         {
907                 return $this->visiting;
908         }
909 }