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