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\PConfig;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Profile;
17 require_once 'include/dba.php';
18 require_once 'include/text.php';
19 require_once 'boot.php';
20 require_once 'include/conversation.php';
25 class Post extends BaseObject
28 private $template = null;
29 private $available_templates = [
30 'wall' => 'wall_thread.tpl',
31 'wall2wall' => 'wallwall_thread.tpl'
33 private $comment_box_template = 'comment_item.tpl';
34 private $toplevel = false;
35 private $writable = false;
36 private $children = [];
37 private $parent = null;
38 private $thread = null;
39 private $redirect_url = null;
40 private $owner_url = '';
41 private $owner_photo = '';
42 private $owner_name = '';
43 private $wall_to_wall = false;
44 private $threaded = false;
45 private $visiting = false;
50 * @param array $data data array
52 public function __construct(array $data)
57 $this->setTemplate('wall');
58 $this->toplevel = $this->getId() == $this->getDataValue('parent');
60 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
61 foreach ($_SESSION['remote'] as $visitor) {
62 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
63 $this->visiting = true;
69 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
70 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
72 if (!$this->isToplevel()) {
73 $this->threaded = true;
76 // Prepare the children
77 if (count($data['children'])) {
78 foreach ($data['children'] as $item) {
79 // Only add will be displayed
80 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
82 } elseif (!visible_activity($item)) {
86 // You can always comment on Diaspora and OStatus items
87 if (in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA]) && (local_user() == $item['uid'])) {
88 $item['writable'] = true;
91 $item['pagedrop'] = $data['pagedrop'];
92 $child = new Post($item);
93 $this->addChild($child);
99 * Get data in a form usable by a conversation template
101 * @param object $conv_responses conversation responses
102 * @param integer $thread_level default = 1
104 * @return mixed The data requested on success
107 public function getTemplateData($conv_responses, $thread_level = 1)
109 require_once "mod/proxy.php";
115 $item = $this->getData();
117 // If the time between "created" and "edited" differs we add
118 // a notice that the post was edited.
119 // Note: In some networks reshared items seem to have (sometimes) a difference
120 // between creation time and edit time of a second. Thats why we add the notice
121 // only if the difference is more than 1 second.
122 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
124 'label' => t('This entry was edited'),
125 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
126 'relative' => relative_date($item['edited'])
135 $isstarred = "unstarred";
139 $total_children = $this->countDescendants();
141 $conv = $this->getThread();
143 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
144 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
145 ? t('Private Message')
147 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
149 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
150 if ($item["event-id"] != 0) {
151 $edpost = ["events/event/" . $item['event-id'], t("Edit")];
153 $edpost = ["editpost/" . $item['id'], t("Edit")];
155 $dropping = in_array($item['uid'], [0, local_user()]);
160 // Editing on items of not subscribed users isn't currently possible
161 // There are some issues on editing that prevent this.
162 // But also it is an issue of the supported protocols that doesn't allow editing at all.
163 if ($item['uid'] == 0) {
167 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
172 'dropping' => $dropping,
173 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
174 'select' => t('Select'),
175 'delete' => t('Delete'),
178 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? t("save to folder") : false);
180 $diff_author = !link_compare($item['url'], $item['author-link']);
181 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
182 if ($item['author-link'] && (!$item['author-name'])) {
183 $profile_name = $item['author-link'];
187 $profile_link = best_link_url($item, $sp);
188 if ($profile_link === 'mailbox') {
193 $sparkle = ' sparkle';
195 $profile_link = Profile::zrl($profile_link);
198 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
199 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
200 if ($author_contact["thumb"]) {
201 $item['author-thumb'] = $author_contact["thumb"];
203 $item['author-thumb'] = $item['author-avatar'];
207 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
208 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
209 if ($owner_contact["thumb"]) {
210 $item['owner-thumb'] = $owner_contact["thumb"];
212 $item['owner-thumb'] = $item['owner-avatar'];
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 = [t('I will attend'), t('I will not attend'), 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' => t("add star"),
260 'undo' => t("remove star"),
261 'toggle' => t("toggle star status"),
262 'classdo' => $item['starred'] ? "hidden" : "",
263 'classundo' => $item['starred'] ? "" : "hidden",
264 'starred' => t('starred'),
267 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
268 if (DBM::is_result($thread)) {
270 'do' => t("ignore thread"),
271 'undo' => t("unignore thread"),
272 'toggle' => t("toggle ignore status"),
273 'classdo' => $thread['ignored'] ? "hidden" : "",
274 'classundo' => $thread['ignored'] ? "" : "hidden",
275 'ignored' => t('ignored'),
279 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
281 'add' => t("add tag"),
290 if ($conv->isWritable()) {
292 'like' => [t("I like this \x28toggle\x29"), t("like")],
293 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [t("I don't like this \x28toggle\x29"), t("dislike")] : '',
296 $buttons['share'] = [t('Share this'), t('share')];
300 $comment = $this->getCommentBox($indent);
302 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', '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;
315 $title_e = $item['title'];
316 $location_e = $location;
317 $owner_name_e = $this->getOwnerName();
319 // Disable features that aren't available in several networks
320 if (!in_array($item["item_network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
321 unset($buttons["dislike"]);
326 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
327 unset($buttons["like"]);
330 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
331 unset($buttons["like"]);
335 'template' => $this->getTemplate(),
336 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
337 'tags' => $item['tags'],
338 'hashtags' => $item['hashtags'],
339 'mentions' => $item['mentions'],
340 'txt_cats' => t('Categories:'),
341 'txt_folders' => t('Filed under:'),
342 'has_cats' => ((count($categories)) ? 'true' : ''),
343 'has_folders' => ((count($folders)) ? 'true' : ''),
344 'categories' => $categories,
345 'folders' => $folders,
348 'id' => $this->getId(),
349 'guid' => urlencode($item['guid']),
350 'isevent' => $isevent,
352 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
353 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
356 'wall' => t('Wall-to-Wall'),
357 'vwall' => t('via Wall-To-Wall:'),
358 'profile_url' => $profile_link,
359 'item_photo_menu' => item_photo_menu($item),
361 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
362 'osparkle' => $osparkle,
363 'sparkle' => $sparkle,
365 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
366 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
367 'app' => $item['app'],
368 'created' => relative_date($item['created']),
370 'location' => $location_e,
373 'owner_url' => $this->getOwnerUrl(),
374 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
375 'owner_name' => htmlentities($owner_name_e),
376 'plink' => get_plink($item),
377 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
378 'isstarred' => $isstarred,
379 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
380 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
382 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
385 'like' => $responses['like']['output'],
386 'dislike' => $responses['dislike']['output'],
387 'responses' => $responses,
388 'switchcomment' => t('Comment'),
389 'comment' => $comment,
390 'previewing' => $conv->isPreview() ? ' preview ' : '',
391 'wait' => t('Please wait'),
392 'thread_level' => $thread_level,
394 'network' => $item["item_network"],
395 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
396 'received' => $item['received'],
397 'commented' => $item['commented'],
398 'created_date' => $item['created'],
401 $arr = ['item' => $item, 'output' => $tmp_item];
402 Addon::callHooks('display_item', $arr);
404 $result = $arr['output'];
406 $result['children'] = [];
407 $children = $this->getChildren();
408 $nb_children = count($children);
409 if ($nb_children > 0) {
410 foreach ($children as $child) {
411 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
414 if (($nb_children > 2) || ($thread_level > 1)) {
415 $result['children'][0]['comment_firstcollapsed'] = true;
416 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
417 $result['children'][0]['hidden_comments_num'] = $total_children;
418 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
419 $result['children'][0]['hide_text'] = t('show more');
420 if ($thread_level > 1) {
421 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
423 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
428 if ($this->isToplevel()) {
429 $result['total_comments_num'] = "$total_children";
430 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
433 $result['private'] = $item['private'];
434 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
436 if ($this->isThreaded()) {
437 $result['flatten'] = false;
438 $result['threaded'] = true;
440 $result['flatten'] = true;
441 $result['threaded'] = false;
450 public function getId()
452 return $this->getDataValue('id');
458 public function isThreaded()
460 return $this->threaded;
466 * @param object $item The child item to add
470 public function addChild(Post $item)
472 $item_id = $item->getId();
474 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
476 } elseif ($this->getChild($item->getId())) {
477 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
481 * Only add what will be displayed
483 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
485 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
489 $item->setParent($this);
490 $this->children[] = $item;
492 return end($this->children);
496 * Get a child by its ID
498 * @param integer $id The child id
502 public function getChild($id)
504 foreach ($this->getChildren() as $child) {
505 if ($child->getId() == $id) {
514 * Get all our children
518 public function getChildren()
520 return $this->children;
526 * @param object $item The item to set as parent
530 protected function setParent($item)
532 $parent = $this->getParent();
534 $parent->removeChild($this);
537 $this->parent = $item;
538 $this->setThread($item->getThread());
546 protected function removeParent()
548 $this->parent = null;
549 $this->thread = null;
555 * @param object $item The child to be removed
557 * @return boolean Success or failure
559 public function removeChild($item)
561 $id = $item->getId();
562 foreach ($this->getChildren() as $key => $child) {
563 if ($child->getId() == $id) {
564 $child->removeParent();
565 unset($this->children[$key]);
566 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
567 $this->children = array_values($this->children);
571 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
580 protected function getParent()
582 return $this->parent;
588 * @param object $conv The conversation
592 public function setThread($conv)
594 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
596 $this->thread = $conv;
598 // Set it on our children too
599 foreach ($this->getChildren() as $child) {
600 $child->setThread($conv);
609 public function getThread()
611 return $this->thread;
617 * We shouldn't need this
621 public function getData()
629 * @param object $name key
631 * @return mixed value on success
634 public function getDataValue($name)
636 if (!isset($this->data[$name])) {
637 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
641 return $this->data[$name];
647 * @param object $name template name
651 private function setTemplate($name)
653 if (!x($this->available_templates, $name)) {
654 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
658 $this->template = $this->available_templates[$name];
666 private function getTemplate()
668 return $this->template;
672 * Check if this is a toplevel post
676 private function isToplevel()
678 return $this->toplevel;
682 * Check if this is writable
686 private function isWritable()
688 $conv = $this->getThread();
691 // This will allow us to comment on wall-to-wall items owned by our friends
692 // and community forums even if somebody else wrote the post.
693 // bug #517 - this fixes for conversation owner
694 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
698 // this fixes for visitors
699 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
701 return $this->writable;
705 * Count the total of our descendants
709 private function countDescendants()
711 $children = $this->getChildren();
712 $total = count($children);
714 foreach ($children as $child) {
715 $total += $child->countDescendants();
723 * Get the template for the comment box
727 private function getCommentBoxTemplate()
729 return $this->comment_box_template;
733 * Get the comment box
735 * @param string $indent Indent value
737 * @return mixed The comment box string (empty if no comment box)
740 private function getCommentBox($indent)
745 $conv = $this->getThread();
747 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
751 if ($conv->isWritable() && $this->isWritable()) {
752 $qc = $qcomment = null;
755 * Hmmm, code depending on the presence of a particular addon?
756 * This should be better if done by a hook
758 if (in_array('qcomment', $a->addons)) {
759 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
760 $qcomment = (($qc) ? explode("\n", $qc) : null);
763 // Fetch the user id from the parent when the owner user is empty
764 $uid = $conv->getProfileOwner();
765 $parent_uid = $this->getDataValue('uid');
767 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
771 $template = get_markup_template($this->getCommentBoxTemplate());
772 $comment_box = replace_macros($template, [
773 '$return_path' => $a->query_string,
774 '$threaded' => $this->isThreaded(),
776 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
777 '$id' => $this->getId(),
778 '$parent' => $this->getId(),
779 '$qcomment' => $qcomment,
780 '$profile_uid' => $uid,
781 '$mylink' => $a->remove_baseurl($a->contact['url']),
782 '$mytitle' => t('This is you'),
783 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
784 '$comment' => t('Comment'),
785 '$submit' => t('Submit'),
786 '$edbold' => t('Bold'),
787 '$editalic' => t('Italic'),
788 '$eduline' => t('Underline'),
789 '$edquote' => t('Quote'),
790 '$edcode' => t('Code'),
791 '$edimg' => t('Image'),
792 '$edurl' => t('Link'),
793 '$edvideo' => t('Video'),
794 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
795 '$indent' => $indent,
796 '$sourceapp' => t($a->sourcename),
797 '$ww' => $conv->getMode() === 'network' ? $ww : '',
798 '$rand_num' => random_digits(12)
808 private function getRedirectUrl()
810 return $this->redirect_url;
814 * Check if we are a wall to wall item and set the relevant properties
818 protected function checkWallToWall()
821 $conv = $this->getThread();
822 $this->wall_to_wall = false;
824 if ($this->isToplevel()) {
825 if ($conv->getMode() !== 'profile') {
826 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
827 // On the network page, I am the owner. On the display page it will be the profile owner.
828 // This will have been stored in $a->page_contact by our calling page.
829 // Put this person as the wall owner of the wall-to-wall notice.
831 $this->owner_url = Profile::zrl($a->page_contact['url']);
832 $this->owner_photo = $a->page_contact['thumb'];
833 $this->owner_name = $a->page_contact['name'];
834 $this->wall_to_wall = true;
835 } elseif ($this->getDataValue('owner-link')) {
836 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
837 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
838 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
840 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
841 // The author url doesn't match the owner (typically the contact)
842 // and also doesn't match the contact alias.
843 // The name match is a hack to catch several weird cases where URLs are
844 // all over the park. It can be tricked, but this prevents you from
845 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
846 // well that it's the same Bob Smith.
847 // But it could be somebody else with the same name. It just isn't highly likely.
850 $this->owner_photo = $this->getDataValue('owner-avatar');
851 $this->owner_name = $this->getDataValue('owner-name');
852 $this->wall_to_wall = true;
853 // If it is our contact, use a friendly redirect link
854 if ($this->getDataValue('network') === NETWORK_DFRN
855 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
857 $this->owner_url = $this->getRedirectUrl();
859 $this->owner_url = Profile::zrl($this->getDataValue('owner-link'));
866 if (!$this->wall_to_wall) {
867 $this->setTemplate('wall');
868 $this->owner_url = '';
869 $this->owner_photo = '';
870 $this->owner_name = '';
877 private function isWallToWall()
879 return $this->wall_to_wall;
885 private function getOwnerUrl()
887 return $this->owner_url;
893 private function getOwnerName()
895 return $this->owner_name;
901 private function isVisiting()
903 return $this->visiting;