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\Temporal;
26 require_once 'include/dba.php';
27 require_once 'include/text.php';
28 require_once 'boot.php';
29 require_once 'include/conversation.php';
34 class Post extends BaseObject
37 private $template = null;
38 private $available_templates = [
39 'wall' => 'wall_thread.tpl',
40 'wall2wall' => 'wallwall_thread.tpl'
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;
59 * @param array $data data array
61 public function __construct(array $data)
66 $this->setTemplate('wall');
67 $this->toplevel = $this->getId() == $this->getDataValue('parent');
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;
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;
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']) {
93 } elseif (!visible_activity($item)) {
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;
102 $item['pagedrop'] = $data['pagedrop'];
103 $child = new Post($item);
104 $this->addChild($child);
110 * Get data in a form usable by a conversation template
112 * @param object $conv_responses conversation responses
113 * @param integer $thread_level default = 1
115 * @return mixed The data requested on success
118 public function getTemplateData($conv_responses, $thread_level = 1)
124 $item = $this->getData();
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) {
133 'label' => L10n::t('This entry was edited'),
134 'date' => DateTimeFormat::local($item['edited'], 'r'),
135 'relative' => Temporal::getRelativeDate($item['edited'])
144 $isstarred = "unstarred";
148 $total_children = $this->countDescendants();
150 $conv = $this->getThread();
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')
157 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
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")];
163 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
165 $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 // 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');
196 'dropping' => $dropping,
197 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
198 'select' => L10n::t('Select'),
202 if (!local_user() || ($item['uid'] == 0)) {
206 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
208 $profile_name = htmlentities($item['author-name']);
209 if (!empty($item['author-link']) && empty($item['author-name'])) {
210 $profile_name = $item['author-link'];
213 $author = ['uid' => 0, 'id' => $item['author-id'],
214 'network' => $item['author-network'], 'url' => $item['author-link']];
216 if (local_user() || remote_user()) {
217 $profile_link = Contact::magicLinkbyContact($author);
219 $profile_link = $item['author-link'];
222 if (strpos($profile_link, 'redir/') === 0) {
223 $sparkle = ' sparkle';
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));
230 // process action responses - e.g. like/dislike/attend/agree/whatever
231 $response_verbs = ['like', 'dislike'];
235 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
236 $response_verbs[] = 'attendyes';
237 $response_verbs[] = 'attendno';
238 $response_verbs[] = 'attendmaybe';
239 if ($conv->isWritable()) {
241 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
245 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
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']) : '';
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
256 $this->checkWallToWall();
258 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
259 $osparkle = ' sparkle';
264 if ($this->isToplevel()) {
265 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
266 if (DBA::isResult($thread)) {
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'),
277 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
278 $isstarred = (($item['starred']) ? "starred" : "unstarred");
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'),
289 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
291 'add' => L10n::t("add tag"),
300 if ($conv->isWritable()) {
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")] : '',
306 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
310 $comment = $this->getCommentBox($indent);
312 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
316 localize_item($item);
318 $body = Item::prepareBody($item, true);
320 list($categories, $folders) = get_cats_and_terms($item);
323 $text_e = strip_tags($body);
324 $name_e = $profile_name;
326 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
327 $title_e = ucfirst($item['content-warning']);
329 $title_e = $item['title'];
332 $location_e = $location;
333 $owner_name_e = $this->getOwnerName();
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"]);
342 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
343 unset($buttons["like"]);
346 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
347 unset($buttons["like"]);
350 $tags = Term::populateTagsFromItem($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,
367 'id' => $this->getId(),
368 'guid' => urlencode($item['guid']),
369 'isevent' => $isevent,
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),
380 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
381 'osparkle' => $osparkle,
382 'sparkle' => $sparkle,
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']),
389 'location' => $location_e,
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' => Item::getPlink($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 : '',
401 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
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,
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) : '',
421 $arr = ['item' => $item, 'output' => $tmp_item];
422 Addon::callHooks('display_item', $arr);
424 $result = $arr['output'];
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);
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;
443 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
448 if ($this->isToplevel()) {
449 $result['total_comments_num'] = "$total_children";
450 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
453 $result['private'] = $item['private'];
454 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
456 if ($this->isThreaded()) {
457 $result['flatten'] = false;
458 $result['threaded'] = true;
460 $result['flatten'] = true;
461 $result['threaded'] = false;
470 public function getId()
472 return $this->getDataValue('id');
478 public function isThreaded()
480 return $this->threaded;
486 * @param object $item The child item to add
490 public function addChild(Post $item)
492 $item_id = $item->getId();
494 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
496 } elseif ($this->getChild($item->getId())) {
497 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
501 * Only add what will be displayed
503 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
505 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
509 $item->setParent($this);
510 $this->children[] = $item;
512 return end($this->children);
516 * Get a child by its ID
518 * @param integer $id The child id
522 public function getChild($id)
524 foreach ($this->getChildren() as $child) {
525 if ($child->getId() == $id) {
534 * Get all our children
538 public function getChildren()
540 return $this->children;
546 * @param object $item The item to set as parent
550 protected function setParent($item)
552 $parent = $this->getParent();
554 $parent->removeChild($this);
557 $this->parent = $item;
558 $this->setThread($item->getThread());
566 protected function removeParent()
568 $this->parent = null;
569 $this->thread = null;
575 * @param object $item The child to be removed
577 * @return boolean Success or failure
579 public function removeChild($item)
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);
591 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
600 protected function getParent()
602 return $this->parent;
608 * @param object $conv The conversation
612 public function setThread($conv)
614 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
616 $this->thread = $conv;
618 // Set it on our children too
619 foreach ($this->getChildren() as $child) {
620 $child->setThread($conv);
629 public function getThread()
631 return $this->thread;
637 * We shouldn't need this
641 public function getData()
649 * @param object $name key
651 * @return mixed value on success
654 public function getDataValue($name)
656 if (!isset($this->data[$name])) {
657 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
661 return $this->data[$name];
667 * @param object $name template name
671 private function setTemplate($name)
673 if (!x($this->available_templates, $name)) {
674 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
678 $this->template = $this->available_templates[$name];
686 private function getTemplate()
688 return $this->template;
692 * Check if this is a toplevel post
696 private function isToplevel()
698 return $this->toplevel;
702 * Check if this is writable
706 private function isWritable()
708 $conv = $this->getThread();
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()) {
718 // this fixes for visitors
719 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
721 return $this->writable;
725 * Count the total of our descendants
729 private function countDescendants()
731 $children = $this->getChildren();
732 $total = count($children);
734 foreach ($children as $child) {
735 $total += $child->countDescendants();
743 * Get the template for the comment box
747 private function getCommentBoxTemplate()
749 return $this->comment_box_template;
753 * Get the comment box
755 * @param string $indent Indent value
757 * @return mixed The comment box string (empty if no comment box)
760 private function getCommentBox($indent)
765 $conv = $this->getThread();
767 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
771 if ($conv->isWritable() && $this->isWritable()) {
772 $qc = $qcomment = null;
775 * Hmmm, code depending on the presence of a particular addon?
776 * This should be better if done by a hook
778 if (Addon::isEnabled('qcomment')) {
779 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
780 $qcomment = (($qc) ? explode("\n", $qc) : null);
783 // Fetch the user id from the parent when the owner user is empty
784 $uid = $conv->getProfileOwner();
785 $parent_uid = $this->getDataValue('uid');
787 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
791 $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
792 $comment_box = Renderer::replaceMacros($template, [
793 '$return_path' => $a->query_string,
794 '$threaded' => $this->isThreaded(),
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)
829 private function getRedirectUrl()
831 return $this->redirect_url;
835 * Check if we are a wall to wall item and set the relevant properties
839 protected function checkWallToWall()
842 $conv = $this->getThread();
843 $this->wall_to_wall = false;
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.
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'));
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.
871 $this->owner_photo = $this->getDataValue('owner-avatar');
872 $this->owner_name = $this->getDataValue('owner-name');
873 $this->wall_to_wall = true;
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);
884 if (!$this->wall_to_wall) {
885 $this->setTemplate('wall');
886 $this->owner_url = '';
887 $this->owner_photo = '';
888 $this->owner_name = '';
895 private function isWallToWall()
897 return $this->wall_to_wall;
903 private function getOwnerUrl()
905 return $this->owner_url;
911 private function getOwnerName()
913 return $this->owner_name;
919 private function isVisiting()
921 return $this->visiting;