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\PConfig;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Item;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Temporal;
21 require_once 'include/dba.php';
22 require_once 'include/text.php';
23 require_once 'boot.php';
24 require_once 'include/conversation.php';
29 class Post extends BaseObject
32 private $template = null;
33 private $available_templates = [
34 'wall' => 'wall_thread.tpl',
35 'wall2wall' => 'wallwall_thread.tpl'
37 private $comment_box_template = 'comment_item.tpl';
38 private $toplevel = false;
39 private $writable = false;
40 private $children = [];
41 private $parent = null;
42 private $thread = null;
43 private $redirect_url = null;
44 private $owner_url = '';
45 private $owner_photo = '';
46 private $owner_name = '';
47 private $wall_to_wall = false;
48 private $threaded = false;
49 private $visiting = false;
54 * @param array $data data array
56 public function __construct(array $data)
61 $this->setTemplate('wall');
62 $this->toplevel = $this->getId() == $this->getDataValue('parent');
64 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
65 foreach ($_SESSION['remote'] as $visitor) {
66 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
67 $this->visiting = true;
73 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
74 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
75 'network' => $this->getDataValue('author-network'),
76 'url' => $this->getDataValue('author-link')];
77 $this->redirect_url = Contact::magicLinkbyContact($author);
78 if (!$this->isToplevel()) {
79 $this->threaded = true;
82 // Prepare the children
83 if (!empty($data['children'])) {
84 foreach ($data['children'] as $item) {
85 // Only add will be displayed
86 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
88 } elseif (!visible_activity($item)) {
92 // You can always comment on Diaspora and OStatus items
93 if (in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA]) && (local_user() == $item['uid'])) {
94 $item['writable'] = true;
97 $item['pagedrop'] = $data['pagedrop'];
98 $child = new Post($item);
99 $this->addChild($child);
105 * Get data in a form usable by a conversation template
107 * @param object $conv_responses conversation responses
108 * @param integer $thread_level default = 1
110 * @return mixed The data requested on success
113 public function getTemplateData($conv_responses, $thread_level = 1)
115 require_once "mod/proxy.php";
121 $item = $this->getData();
123 // If the time between "created" and "edited" differs we add
124 // a notice that the post was edited.
125 // Note: In some networks reshared items seem to have (sometimes) a difference
126 // between creation time and edit time of a second. Thats why we add the notice
127 // only if the difference is more than 1 second.
128 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
130 'label' => L10n::t('This entry was edited'),
131 'date' => DateTimeFormat::local($item['edited'], 'r'),
132 'relative' => Temporal::getRelativeDate($item['edited'])
141 $isstarred = "unstarred";
145 $total_children = $this->countDescendants();
147 $conv = $this->getThread();
149 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
150 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
151 ? L10n::t('Private Message')
153 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
155 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
156 if ($item["event-id"] != 0) {
157 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
159 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
161 $dropping = in_array($item['uid'], [0, local_user()]);
166 // Editing on items of not subscribed users isn't currently possible
167 // There are some issues on editing that prevent this.
168 // But also it is an issue of the supported protocols that doesn't allow editing at all.
169 if ($item['uid'] == 0) {
173 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
177 $origin = $item['origin'];
180 /// @todo This shouldn't be done as query here, but better during the data creation.
181 // it is now done here, since during the RC phase we shouldn't make to intense changes.
182 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
183 if (DBM::is_result($parent)) {
184 $origin = $parent['origin'];
188 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
189 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
192 'dropping' => $dropping,
193 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
194 'select' => L10n::t('Select'),
198 if (!local_user() || ($item['uid'] == 0)) {
202 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
204 $profile_name = htmlentities($item['author-name']);
205 if (!empty($item['author-link']) && empty($item['author-name'])) {
206 $profile_name = $item['author-link'];
209 $author = ['uid' => 0, 'id' => $item['author-id'],
210 'network' => $item['author-network'], 'url' => $item['author-link']];
211 $profile_link = Contact::magicLinkbyContact($author);
212 if (strpos($profile_link, 'redir/') === 0) {
213 $sparkle = ' sparkle';
216 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
217 Addon::callHooks('render_location', $locate);
218 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
220 // process action responses - e.g. like/dislike/attend/agree/whatever
221 $response_verbs = ['like', 'dislike'];
225 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
226 $response_verbs[] = 'attendyes';
227 $response_verbs[] = 'attendno';
228 $response_verbs[] = 'attendmaybe';
229 if ($conv->isWritable()) {
231 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
235 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
237 foreach ($response_verbs as $value => $verbs) {
238 $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']) : '';
242 * We should avoid doing this all the time, but it depends on the conversation mode
243 * And the conv mode may change when we change the conv, or it changes its mode
244 * Maybe we should establish a way to be notified about conversation changes
246 $this->checkWallToWall();
248 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
249 $osparkle = ' sparkle';
254 if ($this->isToplevel()) {
255 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
256 $isstarred = (($item['starred']) ? "starred" : "unstarred");
259 'do' => L10n::t("add star"),
260 'undo' => L10n::t("remove star"),
261 'toggle' => L10n::t("toggle star status"),
262 'classdo' => $item['starred'] ? "hidden" : "",
263 'classundo' => $item['starred'] ? "" : "hidden",
264 'starred' => L10n::t('starred'),
267 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
268 if (DBM::is_result($thread)) {
270 'do' => L10n::t("ignore thread"),
271 'undo' => L10n::t("unignore thread"),
272 'toggle' => L10n::t("toggle ignore status"),
273 'classdo' => $thread['ignored'] ? "hidden" : "",
274 'classundo' => $thread['ignored'] ? "" : "hidden",
275 'ignored' => L10n::t('ignored'),
279 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
281 'add' => L10n::t("add tag"),
290 if ($conv->isWritable()) {
292 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
293 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
296 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
300 $comment = $this->getCommentBox($indent);
302 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
306 localize_item($item);
308 $body = prepare_body($item, true);
310 list($categories, $folders) = get_cats_and_terms($item);
313 $text_e = strip_tags($body);
314 $name_e = $profile_name;
316 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
317 $title_e = ucfirst($item['content-warning']);
319 $title_e = $item['title'];
322 $location_e = $location;
323 $owner_name_e = $this->getOwnerName();
325 // Disable features that aren't available in several networks
326 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
327 unset($buttons["dislike"]);
332 if (($item["network"] == NETWORK_FEED) && isset($buttons["like"])) {
333 unset($buttons["like"]);
336 if (($item["network"] == NETWORK_MAIL) && isset($buttons["like"])) {
337 unset($buttons["like"]);
341 'template' => $this->getTemplate(),
342 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
343 'suppress_tags' => Config::get('system', 'suppress_tags'),
344 'tags' => $item['tags'],
345 'hashtags' => $item['hashtags'],
346 'mentions' => $item['mentions'],
347 'txt_cats' => L10n::t('Categories:'),
348 'txt_folders' => L10n::t('Filed under:'),
349 'has_cats' => ((count($categories)) ? 'true' : ''),
350 'has_folders' => ((count($folders)) ? 'true' : ''),
351 'categories' => $categories,
352 'folders' => $folders,
355 'id' => $this->getId(),
356 'guid' => urlencode($item['guid']),
357 'isevent' => $isevent,
359 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
360 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), $item['owner-link']),
361 'to' => L10n::t('to'),
362 'via' => L10n::t('via'),
363 'wall' => L10n::t('Wall-to-Wall'),
364 'vwall' => L10n::t('via Wall-To-Wall:'),
365 'profile_url' => $profile_link,
366 'item_photo_menu' => item_photo_menu($item),
368 'thumb' => $a->remove_baseurl(proxy_url($item['author-avatar'], false, PROXY_SIZE_THUMB)),
369 'osparkle' => $osparkle,
370 'sparkle' => $sparkle,
372 'localtime' => DateTimeFormat::local($item['created'], 'r'),
373 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
374 'app' => $item['app'],
375 'created' => Temporal::getRelativeDate($item['created']),
377 'location' => $location_e,
380 'owner_url' => $this->getOwnerUrl(),
381 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-avatar'], false, PROXY_SIZE_THUMB)),
382 'owner_name' => htmlentities($owner_name_e),
383 'plink' => get_plink($item),
384 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
385 'isstarred' => $isstarred,
386 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
387 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
389 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
392 'like' => $responses['like']['output'],
393 'dislike' => $responses['dislike']['output'],
394 'responses' => $responses,
395 'switchcomment' => L10n::t('Comment'),
396 'comment' => $comment,
397 'previewing' => $conv->isPreview() ? ' preview ' : '',
398 'wait' => L10n::t('Please wait'),
399 'thread_level' => $thread_level,
401 'network' => $item["network"],
402 'network_name' => ContactSelector::networkToName($item['network'], $profile_link),
403 'received' => $item['received'],
404 'commented' => $item['commented'],
405 'created_date' => $item['created'],
408 $arr = ['item' => $item, 'output' => $tmp_item];
409 Addon::callHooks('display_item', $arr);
411 $result = $arr['output'];
413 $result['children'] = [];
414 $children = $this->getChildren();
415 $nb_children = count($children);
416 if ($nb_children > 0) {
417 foreach ($children as $child) {
418 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
421 if (($nb_children > 2) || ($thread_level > 1)) {
422 $result['children'][0]['comment_firstcollapsed'] = true;
423 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
424 $result['children'][0]['hidden_comments_num'] = $total_children;
425 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
426 $result['children'][0]['hide_text'] = L10n::t('show more');
427 if ($thread_level > 1) {
428 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
430 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
435 if ($this->isToplevel()) {
436 $result['total_comments_num'] = "$total_children";
437 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
440 $result['private'] = $item['private'];
441 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
443 if ($this->isThreaded()) {
444 $result['flatten'] = false;
445 $result['threaded'] = true;
447 $result['flatten'] = true;
448 $result['threaded'] = false;
457 public function getId()
459 return $this->getDataValue('id');
465 public function isThreaded()
467 return $this->threaded;
473 * @param object $item The child item to add
477 public function addChild(Post $item)
479 $item_id = $item->getId();
481 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
483 } elseif ($this->getChild($item->getId())) {
484 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
488 * Only add what will be displayed
490 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
492 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
496 $item->setParent($this);
497 $this->children[] = $item;
499 return end($this->children);
503 * Get a child by its ID
505 * @param integer $id The child id
509 public function getChild($id)
511 foreach ($this->getChildren() as $child) {
512 if ($child->getId() == $id) {
521 * Get all our children
525 public function getChildren()
527 return $this->children;
533 * @param object $item The item to set as parent
537 protected function setParent($item)
539 $parent = $this->getParent();
541 $parent->removeChild($this);
544 $this->parent = $item;
545 $this->setThread($item->getThread());
553 protected function removeParent()
555 $this->parent = null;
556 $this->thread = null;
562 * @param object $item The child to be removed
564 * @return boolean Success or failure
566 public function removeChild($item)
568 $id = $item->getId();
569 foreach ($this->getChildren() as $key => $child) {
570 if ($child->getId() == $id) {
571 $child->removeParent();
572 unset($this->children[$key]);
573 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
574 $this->children = array_values($this->children);
578 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
587 protected function getParent()
589 return $this->parent;
595 * @param object $conv The conversation
599 public function setThread($conv)
601 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
603 $this->thread = $conv;
605 // Set it on our children too
606 foreach ($this->getChildren() as $child) {
607 $child->setThread($conv);
616 public function getThread()
618 return $this->thread;
624 * We shouldn't need this
628 public function getData()
636 * @param object $name key
638 * @return mixed value on success
641 public function getDataValue($name)
643 if (!isset($this->data[$name])) {
644 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
648 return $this->data[$name];
654 * @param object $name template name
658 private function setTemplate($name)
660 if (!x($this->available_templates, $name)) {
661 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
665 $this->template = $this->available_templates[$name];
673 private function getTemplate()
675 return $this->template;
679 * Check if this is a toplevel post
683 private function isToplevel()
685 return $this->toplevel;
689 * Check if this is writable
693 private function isWritable()
695 $conv = $this->getThread();
698 // This will allow us to comment on wall-to-wall items owned by our friends
699 // and community forums even if somebody else wrote the post.
700 // bug #517 - this fixes for conversation owner
701 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
705 // this fixes for visitors
706 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
708 return $this->writable;
712 * Count the total of our descendants
716 private function countDescendants()
718 $children = $this->getChildren();
719 $total = count($children);
721 foreach ($children as $child) {
722 $total += $child->countDescendants();
730 * Get the template for the comment box
734 private function getCommentBoxTemplate()
736 return $this->comment_box_template;
740 * Get the comment box
742 * @param string $indent Indent value
744 * @return mixed The comment box string (empty if no comment box)
747 private function getCommentBox($indent)
752 $conv = $this->getThread();
754 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
758 if ($conv->isWritable() && $this->isWritable()) {
759 $qc = $qcomment = null;
762 * Hmmm, code depending on the presence of a particular addon?
763 * This should be better if done by a hook
765 if (in_array('qcomment', $a->addons)) {
766 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
767 $qcomment = (($qc) ? explode("\n", $qc) : null);
770 // Fetch the user id from the parent when the owner user is empty
771 $uid = $conv->getProfileOwner();
772 $parent_uid = $this->getDataValue('uid');
774 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
778 $template = get_markup_template($this->getCommentBoxTemplate());
779 $comment_box = replace_macros($template, [
780 '$return_path' => $a->query_string,
781 '$threaded' => $this->isThreaded(),
783 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
784 '$id' => $this->getId(),
785 '$parent' => $this->getId(),
786 '$qcomment' => $qcomment,
787 '$profile_uid' => $uid,
788 '$mylink' => $a->remove_baseurl($a->contact['url']),
789 '$mytitle' => L10n::t('This is you'),
790 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
791 '$comment' => L10n::t('Comment'),
792 '$submit' => L10n::t('Submit'),
793 '$edbold' => L10n::t('Bold'),
794 '$editalic' => L10n::t('Italic'),
795 '$eduline' => L10n::t('Underline'),
796 '$edquote' => L10n::t('Quote'),
797 '$edcode' => L10n::t('Code'),
798 '$edimg' => L10n::t('Image'),
799 '$edurl' => L10n::t('Link'),
800 '$edvideo' => L10n::t('Video'),
801 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
802 '$indent' => $indent,
803 '$sourceapp' => L10n::t($a->sourcename),
804 '$ww' => $conv->getMode() === 'network' ? $ww : '',
805 '$rand_num' => random_digits(12)
815 private function getRedirectUrl()
817 return $this->redirect_url;
821 * Check if we are a wall to wall item and set the relevant properties
825 protected function checkWallToWall()
828 $conv = $this->getThread();
829 $this->wall_to_wall = false;
831 if ($this->isToplevel()) {
832 if ($conv->getMode() !== 'profile') {
833 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
834 // On the network page, I am the owner. On the display page it will be the profile owner.
835 // This will have been stored in $a->page_contact by our calling page.
836 // Put this person as the wall owner of the wall-to-wall notice.
838 $this->owner_url = Contact::magicLink($a->page_contact['url']);
839 $this->owner_photo = $a->page_contact['thumb'];
840 $this->owner_name = $a->page_contact['name'];
841 $this->wall_to_wall = true;
842 } elseif ($this->getDataValue('owner-link')) {
843 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
844 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
845 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
847 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
848 // The author url doesn't match the owner (typically the contact)
849 // and also doesn't match the contact alias.
850 // The name match is a hack to catch several weird cases where URLs are
851 // all over the park. It can be tricked, but this prevents you from
852 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
853 // well that it's the same Bob Smith.
854 // But it could be somebody else with the same name. It just isn't highly likely.
857 $this->owner_photo = $this->getDataValue('owner-avatar');
858 $this->owner_name = $this->getDataValue('owner-name');
859 $this->wall_to_wall = true;
861 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
862 'network' => $this->getDataValue('owner-network'),
863 'url' => $this->getDataValue('owner-link')];
864 $this->owner_url = Contact::magicLinkbyContact($owner);
870 if (!$this->wall_to_wall) {
871 $this->setTemplate('wall');
872 $this->owner_url = '';
873 $this->owner_photo = '';
874 $this->owner_name = '';
881 private function isWallToWall()
883 return $this->wall_to_wall;
889 private function getOwnerUrl()
891 return $this->owner_url;
897 private function getOwnerName()
899 return $this->owner_name;
905 private function isVisiting()
907 return $this->visiting;