3 * @file src/Object/Post.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Content\ContactSelector;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\Renderer;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Conversation;
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\Strings;
25 use Friendica\Util\Temporal;
30 class Post extends BaseObject
33 private $template = null;
34 private $available_templates = [
35 'wall' => 'wall_thread.tpl',
36 'wall2wall' => 'wallwall_thread.tpl'
38 private $comment_box_template = 'comment_item.tpl';
39 private $toplevel = false;
40 private $writable = false;
44 private $children = [];
45 private $parent = null;
50 private $thread = null;
51 private $redirect_url = null;
52 private $owner_url = '';
53 private $owner_photo = '';
54 private $owner_name = '';
55 private $wall_to_wall = false;
56 private $threaded = false;
57 private $visiting = false;
62 * @param array $data data array
64 public function __construct(array $data)
67 $this->setTemplate('wall');
68 $this->toplevel = $this->getId() == $this->getDataValue('parent');
70 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
71 foreach ($_SESSION['remote'] as $visitor) {
72 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
73 $this->visiting = true;
79 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
80 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
81 'network' => $this->getDataValue('author-network'),
82 'url' => $this->getDataValue('author-link')];
83 $this->redirect_url = Contact::magicLinkbyContact($author);
84 if (!$this->isToplevel()) {
85 $this->threaded = true;
88 // Prepare the children
89 if (!empty($data['children'])) {
90 foreach ($data['children'] as $item) {
91 // Only add will be displayed
92 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
94 } elseif (!visible_activity($item)) {
98 // You can always comment on Diaspora and OStatus items
99 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
100 $item['writable'] = true;
103 $item['pagedrop'] = $data['pagedrop'];
104 $child = new Post($item);
105 $this->addChild($child);
111 * Get data in a form usable by a conversation template
113 * @param array $conv_responses conversation responses
114 * @param integer $thread_level default = 1
116 * @return mixed The data requested on success
119 public function getTemplateData(array $conv_responses, $thread_level = 1)
123 $item = $this->getData();
125 // If the time between "created" and "edited" differs we add
126 // a notice that the post was edited.
127 // Note: In some networks reshared items seem to have (sometimes) a difference
128 // between creation time and edit time of a second. Thats why we add the notice
129 // only if the difference is more than 1 second.
130 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
132 'label' => L10n::t('This entry was edited'),
133 'date' => DateTimeFormat::local($item['edited'], 'r'),
134 'relative' => Temporal::getRelativeDate($item['edited'])
142 $isstarred = "unstarred";
146 $total_children = $this->countDescendants();
148 $conv = $this->getThread();
150 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
151 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
152 ? L10n::t('Private Message')
155 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
160 if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
161 if ($item["event-id"] != 0) {
162 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
164 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
167 $dropping = in_array($item['uid'], [0, local_user()]);
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) {
177 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
181 $origin = $item['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'];
192 if ($origin && ($item['id'] != $item['parent']) && ($item['network'] == Protocol::ACTIVITYPUB)) {
193 // ActivityPub doesn't allow removal of remote comments
194 $delete = L10n::t('Delete locally');
196 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
197 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
201 'dropping' => $dropping,
202 'pagedrop' => $item['pagedrop'],
203 'select' => L10n::t('Select'),
211 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
213 $profile_name = $item['author-name'];
214 if (!empty($item['author-link']) && empty($item['author-name'])) {
215 $profile_name = $item['author-link'];
218 $author = ['uid' => 0, 'id' => $item['author-id'],
219 'network' => $item['author-network'], 'url' => $item['author-link']];
221 if (local_user() || remote_user()) {
222 $profile_link = Contact::magicLinkbyContact($author);
224 $profile_link = $item['author-link'];
227 if (strpos($profile_link, 'redir/') === 0) {
228 $sparkle = ' sparkle';
231 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
232 Addon::callHooks('render_location', $locate);
233 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
235 // process action responses - e.g. like/dislike/attend/agree/whatever
236 $response_verbs = ['like', 'dislike'];
240 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
241 $response_verbs[] = 'attendyes';
242 $response_verbs[] = 'attendno';
243 $response_verbs[] = 'attendmaybe';
244 if ($conv->isWritable()) {
246 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
250 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
252 foreach ($response_verbs as $value => $verbs) {
253 $responses[$verbs]['output'] = !empty($conv_responses[$verbs][$item['uri']]) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '';
257 * We should avoid doing this all the time, but it depends on the conversation mode
258 * And the conv mode may change when we change the conv, or it changes its mode
259 * Maybe we should establish a way to be notified about conversation changes
261 $this->checkWallToWall();
263 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
264 $osparkle = ' sparkle';
269 if ($this->isToplevel()) {
271 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
272 if (DBA::isResult($thread)) {
274 'do' => L10n::t("ignore thread"),
275 'undo' => L10n::t("unignore thread"),
276 'toggle' => L10n::t("toggle ignore status"),
277 'classdo' => $thread['ignored'] ? "hidden" : "",
278 'classundo' => $thread['ignored'] ? "" : "hidden",
279 'ignored' => L10n::t('ignored'),
283 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
284 $isstarred = (($item['starred']) ? "starred" : "unstarred");
287 'do' => L10n::t("add star"),
288 'undo' => L10n::t("remove star"),
289 'toggle' => L10n::t("toggle star status"),
290 'classdo' => $item['starred'] ? "hidden" : "",
291 'classundo' => $item['starred'] ? "" : "hidden",
292 'starred' => L10n::t('starred'),
296 'add' => L10n::t("add tag"),
305 if ($conv->isWritable()) {
307 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
308 'dislike' => [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")],
311 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
315 $comment = $this->getCommentBox($indent);
317 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
321 localize_item($item);
323 $body = Item::prepareBody($item, true);
325 list($categories, $folders) = get_cats_and_terms($item);
328 $text_e = strip_tags($body);
329 $name_e = $profile_name;
331 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
332 $title_e = ucfirst($item['content-warning']);
334 $title_e = $item['title'];
337 $location_e = $location;
338 $owner_name_e = $this->getOwnerName();
340 // Disable features that aren't available in several networks
341 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
342 unset($buttons["dislike"]);
347 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
348 unset($buttons["like"]);
351 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
352 unset($buttons["like"]);
355 $tags = Term::populateTagsFromItem($item);
358 'template' => $this->getTemplate(),
359 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
360 'suppress_tags' => Config::get('system', 'suppress_tags'),
361 'tags' => $tags['tags'],
362 'hashtags' => $tags['hashtags'],
363 'mentions' => $tags['mentions'],
364 'txt_cats' => L10n::t('Categories:'),
365 'txt_folders' => L10n::t('Filed under:'),
366 'has_cats' => ((count($categories)) ? 'true' : ''),
367 'has_folders' => ((count($folders)) ? 'true' : ''),
368 'categories' => $categories,
369 'folders' => $folders,
372 'id' => $this->getId(),
373 'guid' => urlencode($item['guid']),
374 'isevent' => $isevent,
376 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
377 'olinktitle' => L10n::t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
378 'to' => L10n::t('to'),
379 'via' => L10n::t('via'),
380 'wall' => L10n::t('Wall-to-Wall'),
381 'vwall' => L10n::t('via Wall-To-Wall:'),
382 'profile_url' => $profile_link,
383 'item_photo_menu' => item_photo_menu($item),
385 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
386 'osparkle' => $osparkle,
387 'sparkle' => $sparkle,
389 'localtime' => DateTimeFormat::local($item['created'], 'r'),
390 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
391 'app' => $item['app'],
392 'created' => Temporal::getRelativeDate($item['created']),
394 'location' => $location_e,
397 'owner_url' => $this->getOwnerUrl(),
398 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
399 'owner_name' => $owner_name_e,
400 'plink' => Item::getPlink($item),
402 'isstarred' => $isstarred,
409 'like' => $responses['like']['output'],
410 'dislike' => $responses['dislike']['output'],
411 'responses' => $responses,
412 'switchcomment' => L10n::t('Comment'),
413 'comment' => $comment,
414 'previewing' => $conv->isPreview() ? ' preview ' : '',
415 'wait' => L10n::t('Please wait'),
416 'thread_level' => $thread_level,
418 'network' => $item["network"],
419 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
420 'received' => $item['received'],
421 'commented' => $item['commented'],
422 'created_date' => $item['created'],
423 'return' => ($a->cmd) ? bin2hex($a->cmd) : '',
426 $arr = ['item' => $item, 'output' => $tmp_item];
427 Addon::callHooks('display_item', $arr);
429 $result = $arr['output'];
431 $result['children'] = [];
432 $children = $this->getChildren();
433 $nb_children = count($children);
434 if ($nb_children > 0) {
435 foreach ($children as $child) {
436 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
439 if (($nb_children > 2) || ($thread_level > 1)) {
440 $result['children'][0]['comment_firstcollapsed'] = true;
441 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
442 $result['children'][0]['hidden_comments_num'] = $total_children;
443 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
444 $result['children'][0]['hide_text'] = L10n::t('show more');
445 if ($thread_level > 1) {
446 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
448 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
453 if ($this->isToplevel()) {
454 $result['total_comments_num'] = "$total_children";
455 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
458 $result['private'] = $item['private'];
459 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
461 if ($this->isThreaded()) {
462 $result['flatten'] = false;
463 $result['threaded'] = true;
465 $result['flatten'] = true;
466 $result['threaded'] = false;
475 public function getId()
477 return $this->getDataValue('id');
483 public function isThreaded()
485 return $this->threaded;
491 * @param Post $item The child item to add
495 public function addChild(Post $item)
497 $item_id = $item->getId();
499 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
501 } elseif ($this->getChild($item->getId())) {
502 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
506 * Only add what will be displayed
508 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
510 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
514 $item->setParent($this);
515 $this->children[] = $item;
517 return end($this->children);
521 * Get a child by its ID
523 * @param integer $id The child id
527 public function getChild($id)
529 foreach ($this->getChildren() as $child) {
530 if ($child->getId() == $id) {
539 * Get all our children
543 public function getChildren()
545 return $this->children;
551 * @param Post $item The item to set as parent
555 protected function setParent(Post $item)
557 $parent = $this->getParent();
559 $parent->removeChild($this);
562 $this->parent = $item;
563 $this->setThread($item->getThread());
571 protected function removeParent()
573 $this->parent = null;
574 $this->thread = null;
580 * @param Post $item The child to be removed
582 * @return boolean Success or failure
584 public function removeChild(Post $item)
586 $id = $item->getId();
587 foreach ($this->getChildren() as $key => $child) {
588 if ($child->getId() == $id) {
589 $child->removeParent();
590 unset($this->children[$key]);
591 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
592 $this->children = array_values($this->children);
596 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
605 protected function getParent()
607 return $this->parent;
611 * Set conversation thread
613 * @param Thread $thread
617 public function setThread(Thread $thread = null)
619 $this->thread = $thread;
621 // Set it on our children too
622 foreach ($this->getChildren() as $child) {
623 $child->setThread($thread);
632 public function getThread()
634 return $this->thread;
640 * We shouldn't need this
644 public function getData()
652 * @param string $name key
654 * @return mixed value on success
657 public function getDataValue($name)
659 if (!isset($this->data[$name])) {
660 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
664 return $this->data[$name];
670 * @param string $name template name
673 private function setTemplate($name)
675 if (empty($this->available_templates[$name])) {
676 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
680 $this->template = $this->available_templates[$name];
690 private function getTemplate()
692 return $this->template;
696 * Check if this is a toplevel post
700 private function isToplevel()
702 return $this->toplevel;
706 * Check if this is writable
710 private function isWritable()
712 $conv = $this->getThread();
715 // This will allow us to comment on wall-to-wall items owned by our friends
716 // and community forums even if somebody else wrote the post.
717 // bug #517 - this fixes for conversation owner
718 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
722 // this fixes for visitors
723 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
725 return $this->writable;
729 * Count the total of our descendants
733 private function countDescendants()
735 $children = $this->getChildren();
736 $total = count($children);
738 foreach ($children as $child) {
739 $total += $child->countDescendants();
747 * Get the template for the comment box
751 private function getCommentBoxTemplate()
753 return $this->comment_box_template;
757 * Get the comment box
759 * @param string $indent Indent value
761 * @return mixed The comment box string (empty if no comment box)
764 private function getCommentBox($indent)
769 $conv = $this->getThread();
771 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
775 if ($conv->isWritable() && $this->isWritable()) {
776 $qc = $qcomment = null;
779 * Hmmm, code depending on the presence of a particular addon?
780 * This should be better if done by a hook
782 if (Addon::isEnabled('qcomment')) {
783 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
784 $qcomment = (($qc) ? explode("\n", $qc) : null);
787 // Fetch the user id from the parent when the owner user is empty
788 $uid = $conv->getProfileOwner();
789 $parent_uid = $this->getDataValue('uid');
791 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
795 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
796 $comment_box = Renderer::replaceMacros($template, [
797 '$return_path' => $a->query_string,
798 '$threaded' => $this->isThreaded(),
800 '$wall' => ($conv->getMode() === 'profile'),
801 '$id' => $this->getId(),
802 '$parent' => $this->getId(),
803 '$qcomment' => $qcomment,
804 '$profile_uid' => $uid,
805 '$mylink' => $a->removeBaseURL($a->contact['url']),
806 '$mytitle' => L10n::t('This is you'),
807 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
808 '$comment' => L10n::t('Comment'),
809 '$submit' => L10n::t('Submit'),
810 '$edbold' => L10n::t('Bold'),
811 '$editalic' => L10n::t('Italic'),
812 '$eduline' => L10n::t('Underline'),
813 '$edquote' => L10n::t('Quote'),
814 '$edcode' => L10n::t('Code'),
815 '$edimg' => L10n::t('Image'),
816 '$edurl' => L10n::t('Link'),
817 '$edattach' => L10n::t('Link or Media'),
818 '$prompttext' => L10n::t('Please enter a image/video/audio/webpage URL:'),
819 '$preview' => L10n::t('Preview'),
820 '$indent' => $indent,
821 '$sourceapp' => L10n::t($a->sourcename),
822 '$ww' => $conv->getMode() === 'network' ? $ww : '',
823 '$rand_num' => Crypto::randomDigits(12)
833 private function getRedirectUrl()
835 return $this->redirect_url;
839 * Check if we are a wall to wall item and set the relevant properties
843 protected function checkWallToWall()
846 $conv = $this->getThread();
847 $this->wall_to_wall = false;
849 if ($this->isToplevel()) {
850 if ($conv->getMode() !== 'profile') {
851 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
852 // On the network page, I am the owner. On the display page it will be the profile owner.
853 // This will have been stored in $a->page_contact by our calling page.
854 // Put this person as the wall owner of the wall-to-wall notice.
856 $this->owner_url = Contact::magicLink($a->page_contact['url']);
857 $this->owner_photo = $a->page_contact['thumb'];
858 $this->owner_name = $a->page_contact['name'];
859 $this->wall_to_wall = true;
860 } elseif ($this->getDataValue('owner-link')) {
861 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
862 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
863 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
865 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
866 // The author url doesn't match the owner (typically the contact)
867 // and also doesn't match the contact alias.
868 // The name match is a hack to catch several weird cases where URLs are
869 // all over the park. It can be tricked, but this prevents you from
870 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
871 // well that it's the same Bob Smith.
872 // But it could be somebody else with the same name. It just isn't highly likely.
875 $this->owner_photo = $this->getDataValue('owner-avatar');
876 $this->owner_name = $this->getDataValue('owner-name');
877 $this->wall_to_wall = true;
879 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
880 'network' => $this->getDataValue('owner-network'),
881 'url' => $this->getDataValue('owner-link')];
882 $this->owner_url = Contact::magicLinkbyContact($owner);
888 if (!$this->wall_to_wall) {
889 $this->setTemplate('wall');
890 $this->owner_url = '';
891 $this->owner_photo = '';
892 $this->owner_name = '';
899 private function isWallToWall()
901 return $this->wall_to_wall;
907 private function getOwnerUrl()
909 return $this->owner_url;
915 private function getOwnerName()
917 return $this->owner_name;
923 private function isVisiting()
925 return $this->visiting;