3 * @file src/Object/Post.php
5 namespace Friendica\Object;
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\Strings;
25 use Friendica\Util\Temporal;
27 require_once 'include/dba.php';
28 require_once 'include/text.php';
29 require_once 'boot.php';
30 require_once 'include/conversation.php';
35 class Post extends BaseObject
38 private $template = null;
39 private $available_templates = [
40 'wall' => 'wall_thread.tpl',
41 'wall2wall' => 'wallwall_thread.tpl'
43 private $comment_box_template = 'comment_item.tpl';
44 private $toplevel = false;
45 private $writable = false;
46 private $children = [];
47 private $parent = null;
48 private $thread = null;
49 private $redirect_url = null;
50 private $owner_url = '';
51 private $owner_photo = '';
52 private $owner_name = '';
53 private $wall_to_wall = false;
54 private $threaded = false;
55 private $visiting = false;
60 * @param array $data data array
62 public function __construct(array $data)
67 $this->setTemplate('wall');
68 $this->toplevel = $this->getId() == $this->getDataValue('parent');
70 if (x($_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 object $conv_responses conversation responses
114 * @param integer $thread_level default = 1
116 * @return mixed The data requested on success
119 public function getTemplateData($conv_responses, $thread_level = 1)
125 $item = $this->getData();
127 // If the time between "created" and "edited" differs we add
128 // a notice that the post was edited.
129 // Note: In some networks reshared items seem to have (sometimes) a difference
130 // between creation time and edit time of a second. Thats why we add the notice
131 // only if the difference is more than 1 second.
132 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
134 'label' => L10n::t('This entry was edited'),
135 'date' => DateTimeFormat::local($item['edited'], 'r'),
136 'relative' => Temporal::getRelativeDate($item['edited'])
145 $isstarred = "unstarred";
149 $total_children = $this->countDescendants();
151 $conv = $this->getThread();
153 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
154 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
155 ? L10n::t('Private Message')
158 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
160 if (local_user() && 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")];
166 $dropping = in_array($item['uid'], [0, local_user()]);
171 // Editing on items of not subscribed users isn't currently possible
172 // There are some issues on editing that prevent this.
173 // But also it is an issue of the supported protocols that doesn't allow editing at all.
174 if ($item['uid'] == 0) {
178 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
182 $origin = $item['origin'];
185 /// @todo This shouldn't be done as query here, but better during the data creation.
186 // it is now done here, since during the RC phase we shouldn't make to intense changes.
187 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
188 if (DBA::isResult($parent)) {
189 $origin = $parent['origin'];
193 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
194 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
197 'dropping' => $dropping,
198 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
199 'select' => L10n::t('Select'),
203 if (!local_user() || ($item['uid'] == 0)) {
207 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
209 $profile_name = htmlentities($item['author-name']);
210 if (!empty($item['author-link']) && empty($item['author-name'])) {
211 $profile_name = $item['author-link'];
214 $author = ['uid' => 0, 'id' => $item['author-id'],
215 'network' => $item['author-network'], 'url' => $item['author-link']];
217 if (local_user() || remote_user()) {
218 $profile_link = Contact::magicLinkbyContact($author);
220 $profile_link = $item['author-link'];
223 if (strpos($profile_link, 'redir/') === 0) {
224 $sparkle = ' sparkle';
227 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
228 Addon::callHooks('render_location', $locate);
229 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
231 // process action responses - e.g. like/dislike/attend/agree/whatever
232 $response_verbs = ['like', 'dislike'];
236 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
237 $response_verbs[] = 'attendyes';
238 $response_verbs[] = 'attendno';
239 $response_verbs[] = 'attendmaybe';
240 if ($conv->isWritable()) {
242 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
246 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
248 foreach ($response_verbs as $value => $verbs) {
249 $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']) : '';
253 * We should avoid doing this all the time, but it depends on the conversation mode
254 * And the conv mode may change when we change the conv, or it changes its mode
255 * Maybe we should establish a way to be notified about conversation changes
257 $this->checkWallToWall();
259 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
260 $osparkle = ' sparkle';
265 if ($this->isToplevel()) {
266 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
267 if (DBA::isResult($thread)) {
269 'do' => L10n::t("ignore thread"),
270 'undo' => L10n::t("unignore thread"),
271 'toggle' => L10n::t("toggle ignore status"),
272 'classdo' => $thread['ignored'] ? "hidden" : "",
273 'classundo' => $thread['ignored'] ? "" : "hidden",
274 'ignored' => L10n::t('ignored'),
278 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
279 $isstarred = (($item['starred']) ? "starred" : "unstarred");
282 'do' => L10n::t("add star"),
283 'undo' => L10n::t("remove star"),
284 'toggle' => L10n::t("toggle star status"),
285 'classdo' => $item['starred'] ? "hidden" : "",
286 'classundo' => $item['starred'] ? "" : "hidden",
287 'starred' => L10n::t('starred'),
290 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
292 'add' => L10n::t("add tag"),
301 if ($conv->isWritable()) {
303 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
304 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
307 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
311 $comment = $this->getCommentBox($indent);
313 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
317 localize_item($item);
319 $body = Item::prepareBody($item, true);
321 list($categories, $folders) = get_cats_and_terms($item);
324 $text_e = strip_tags($body);
325 $name_e = $profile_name;
327 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
328 $title_e = ucfirst($item['content-warning']);
330 $title_e = $item['title'];
333 $location_e = $location;
334 $owner_name_e = $this->getOwnerName();
336 // Disable features that aren't available in several networks
337 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
338 unset($buttons["dislike"]);
343 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
344 unset($buttons["like"]);
347 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
348 unset($buttons["like"]);
351 $tags = Term::populateTagsFromItem($item);
354 'template' => $this->getTemplate(),
355 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
356 'suppress_tags' => Config::get('system', 'suppress_tags'),
357 'tags' => $tags['tags'],
358 'hashtags' => $tags['hashtags'],
359 'mentions' => $tags['mentions'],
360 'txt_cats' => L10n::t('Categories:'),
361 'txt_folders' => L10n::t('Filed under:'),
362 'has_cats' => ((count($categories)) ? 'true' : ''),
363 'has_folders' => ((count($folders)) ? 'true' : ''),
364 'categories' => $categories,
365 'folders' => $folders,
368 'id' => $this->getId(),
369 'guid' => urlencode($item['guid']),
370 'isevent' => $isevent,
372 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
373 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), $item['owner-link']),
374 'to' => L10n::t('to'),
375 'via' => L10n::t('via'),
376 'wall' => L10n::t('Wall-to-Wall'),
377 'vwall' => L10n::t('via Wall-To-Wall:'),
378 'profile_url' => $profile_link,
379 'item_photo_menu' => item_photo_menu($item),
381 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
382 'osparkle' => $osparkle,
383 'sparkle' => $sparkle,
385 'localtime' => DateTimeFormat::local($item['created'], 'r'),
386 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
387 'app' => $item['app'],
388 'created' => Temporal::getRelativeDate($item['created']),
390 'location' => $location_e,
393 'owner_url' => $this->getOwnerUrl(),
394 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
395 'owner_name' => htmlentities($owner_name_e),
396 'plink' => Item::getPlink($item),
397 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
398 'isstarred' => $isstarred,
399 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
400 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
402 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
405 'like' => $responses['like']['output'],
406 'dislike' => $responses['dislike']['output'],
407 'responses' => $responses,
408 'switchcomment' => L10n::t('Comment'),
409 'comment' => $comment,
410 'previewing' => $conv->isPreview() ? ' preview ' : '',
411 'wait' => L10n::t('Please wait'),
412 'thread_level' => $thread_level,
414 'network' => $item["network"],
415 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
416 'received' => $item['received'],
417 'commented' => $item['commented'],
418 'created_date' => $item['created'],
419 'return' => ($a->cmd) ? bin2hex($a->cmd) : '',
422 $arr = ['item' => $item, 'output' => $tmp_item];
423 Addon::callHooks('display_item', $arr);
425 $result = $arr['output'];
427 $result['children'] = [];
428 $children = $this->getChildren();
429 $nb_children = count($children);
430 if ($nb_children > 0) {
431 foreach ($children as $child) {
432 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
435 if (($nb_children > 2) || ($thread_level > 1)) {
436 $result['children'][0]['comment_firstcollapsed'] = true;
437 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
438 $result['children'][0]['hidden_comments_num'] = $total_children;
439 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
440 $result['children'][0]['hide_text'] = L10n::t('show more');
441 if ($thread_level > 1) {
442 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
444 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
449 if ($this->isToplevel()) {
450 $result['total_comments_num'] = "$total_children";
451 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
454 $result['private'] = $item['private'];
455 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
457 if ($this->isThreaded()) {
458 $result['flatten'] = false;
459 $result['threaded'] = true;
461 $result['flatten'] = true;
462 $result['threaded'] = false;
471 public function getId()
473 return $this->getDataValue('id');
479 public function isThreaded()
481 return $this->threaded;
487 * @param object $item The child item to add
491 public function addChild(Post $item)
493 $item_id = $item->getId();
495 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
497 } elseif ($this->getChild($item->getId())) {
498 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
502 * Only add what will be displayed
504 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
506 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
510 $item->setParent($this);
511 $this->children[] = $item;
513 return end($this->children);
517 * Get a child by its ID
519 * @param integer $id The child id
523 public function getChild($id)
525 foreach ($this->getChildren() as $child) {
526 if ($child->getId() == $id) {
535 * Get all our children
539 public function getChildren()
541 return $this->children;
547 * @param object $item The item to set as parent
551 protected function setParent($item)
553 $parent = $this->getParent();
555 $parent->removeChild($this);
558 $this->parent = $item;
559 $this->setThread($item->getThread());
567 protected function removeParent()
569 $this->parent = null;
570 $this->thread = null;
576 * @param object $item The child to be removed
578 * @return boolean Success or failure
580 public function removeChild($item)
582 $id = $item->getId();
583 foreach ($this->getChildren() as $key => $child) {
584 if ($child->getId() == $id) {
585 $child->removeParent();
586 unset($this->children[$key]);
587 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
588 $this->children = array_values($this->children);
592 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
601 protected function getParent()
603 return $this->parent;
609 * @param object $conv The conversation
613 public function setThread($conv)
615 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
617 $this->thread = $conv;
619 // Set it on our children too
620 foreach ($this->getChildren() as $child) {
621 $child->setThread($conv);
630 public function getThread()
632 return $this->thread;
638 * We shouldn't need this
642 public function getData()
650 * @param object $name key
652 * @return mixed value on success
655 public function getDataValue($name)
657 if (!isset($this->data[$name])) {
658 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
662 return $this->data[$name];
668 * @param object $name template name
672 private function setTemplate($name)
674 if (!x($this->available_templates, $name)) {
675 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
679 $this->template = $this->available_templates[$name];
687 private function getTemplate()
689 return $this->template;
693 * Check if this is a toplevel post
697 private function isToplevel()
699 return $this->toplevel;
703 * Check if this is writable
707 private function isWritable()
709 $conv = $this->getThread();
712 // This will allow us to comment on wall-to-wall items owned by our friends
713 // and community forums even if somebody else wrote the post.
714 // bug #517 - this fixes for conversation owner
715 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
719 // this fixes for visitors
720 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
722 return $this->writable;
726 * Count the total of our descendants
730 private function countDescendants()
732 $children = $this->getChildren();
733 $total = count($children);
735 foreach ($children as $child) {
736 $total += $child->countDescendants();
744 * Get the template for the comment box
748 private function getCommentBoxTemplate()
750 return $this->comment_box_template;
754 * Get the comment box
756 * @param string $indent Indent value
758 * @return mixed The comment box string (empty if no comment box)
761 private function getCommentBox($indent)
766 $conv = $this->getThread();
768 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
772 if ($conv->isWritable() && $this->isWritable()) {
773 $qc = $qcomment = null;
776 * Hmmm, code depending on the presence of a particular addon?
777 * This should be better if done by a hook
779 if (Addon::isEnabled('qcomment')) {
780 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
781 $qcomment = (($qc) ? explode("\n", $qc) : null);
784 // Fetch the user id from the parent when the owner user is empty
785 $uid = $conv->getProfileOwner();
786 $parent_uid = $this->getDataValue('uid');
788 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
792 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
793 $comment_box = Renderer::replaceMacros($template, [
794 '$return_path' => $a->query_string,
795 '$threaded' => $this->isThreaded(),
797 '$wall' => ($conv->getMode() === 'profile'),
798 '$id' => $this->getId(),
799 '$parent' => $this->getId(),
800 '$qcomment' => $qcomment,
801 '$profile_uid' => $uid,
802 '$mylink' => $a->removeBaseURL($a->contact['url']),
803 '$mytitle' => L10n::t('This is you'),
804 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
805 '$comment' => L10n::t('Comment'),
806 '$submit' => L10n::t('Submit'),
807 '$edbold' => L10n::t('Bold'),
808 '$editalic' => L10n::t('Italic'),
809 '$eduline' => L10n::t('Underline'),
810 '$edquote' => L10n::t('Quote'),
811 '$edcode' => L10n::t('Code'),
812 '$edimg' => L10n::t('Image'),
813 '$edurl' => L10n::t('Link'),
814 '$edattach' => L10n::t('Link or Media'),
815 '$prompttext' => L10n::t('Please enter a image/video/audio/webpage URL:'),
816 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
817 '$indent' => $indent,
818 '$sourceapp' => L10n::t($a->sourcename),
819 '$ww' => $conv->getMode() === 'network' ? $ww : '',
820 '$rand_num' => Crypto::randomDigits(12)
830 private function getRedirectUrl()
832 return $this->redirect_url;
836 * Check if we are a wall to wall item and set the relevant properties
840 protected function checkWallToWall()
843 $conv = $this->getThread();
844 $this->wall_to_wall = false;
846 if ($this->isToplevel()) {
847 if ($conv->getMode() !== 'profile') {
848 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
849 // On the network page, I am the owner. On the display page it will be the profile owner.
850 // This will have been stored in $a->page_contact by our calling page.
851 // Put this person as the wall owner of the wall-to-wall notice.
853 $this->owner_url = Contact::magicLink($a->page_contact['url']);
854 $this->owner_photo = $a->page_contact['thumb'];
855 $this->owner_name = $a->page_contact['name'];
856 $this->wall_to_wall = true;
857 } elseif ($this->getDataValue('owner-link')) {
858 $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
859 $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
860 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
862 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
863 // The author url doesn't match the owner (typically the contact)
864 // and also doesn't match the contact alias.
865 // The name match is a hack to catch several weird cases where URLs are
866 // all over the park. It can be tricked, but this prevents you from
867 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
868 // well that it's the same Bob Smith.
869 // But it could be somebody else with the same name. It just isn't highly likely.
872 $this->owner_photo = $this->getDataValue('owner-avatar');
873 $this->owner_name = $this->getDataValue('owner-name');
874 $this->wall_to_wall = true;
876 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
877 'network' => $this->getDataValue('owner-network'),
878 'url' => $this->getDataValue('owner-link')];
879 $this->owner_url = Contact::magicLinkbyContact($owner);
885 if (!$this->wall_to_wall) {
886 $this->setTemplate('wall');
887 $this->owner_url = '';
888 $this->owner_photo = '';
889 $this->owner_name = '';
896 private function isWallToWall()
898 return $this->wall_to_wall;
904 private function getOwnerUrl()
906 return $this->owner_url;
912 private function getOwnerName()
914 return $this->owner_name;
920 private function isVisiting()
922 return $this->visiting;