4 * @file src/Object/Post.php
7 namespace Friendica\Object;
9 use Friendica\BaseObject;
10 use Friendica\Content\Feature;
11 use Friendica\Core\PConfig;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
18 require_once 'boot.php';
19 require_once 'include/conversation.php';
24 class Post extends BaseObject
26 private $data = array();
27 private $template = null;
28 private $available_templates = array(
29 'wall' => 'wall_thread.tpl',
30 'wall2wall' => 'wallwall_thread.tpl'
32 private $comment_box_template = 'comment_item.tpl';
33 private $toplevel = false;
34 private $writable = false;
35 private $children = array();
36 private $parent = null;
37 private $thread = null;
38 private $redirect_url = null;
39 private $owner_url = '';
40 private $owner_photo = '';
41 private $owner_name = '';
42 private $wall_to_wall = false;
43 private $threaded = false;
44 private $visiting = false;
49 * @param array $data data array
51 public function __construct(array $data)
56 $this->setTemplate('wall');
57 $this->toplevel = $this->getId() == $this->getDataValue('parent');
59 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
60 foreach ($_SESSION['remote'] as $visitor) {
61 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
62 $this->visiting = true;
68 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
69 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
71 if (!$this->isToplevel()) {
72 $this->threaded = true;
75 // Prepare the children
76 if (count($data['children'])) {
77 foreach ($data['children'] as $item) {
78 // Only add will be displayed
79 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
81 } elseif (!visible_activity($item)) {
85 // You can always comment on Diaspora items
86 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
87 $item['writable'] = true;
90 $item['pagedrop'] = $data['pagedrop'];
91 $child = new Post($item);
92 $this->addChild($child);
98 * Get data in a form usable by a conversation template
100 * @param object $conv_responses conversation responses
101 * @param integer $thread_level default = 1
103 * @return mixed The data requested on success
106 public function getTemplateData($conv_responses, $thread_level = 1)
108 require_once "mod/proxy.php";
114 $item = $this->getData();
116 // If the time between "created" and "edited" differs we add
117 // a notice that the post was edited.
118 // Note: In some networks reshared items seem to have (sometimes) a difference
119 // between creation time and edit time of a second. Thats why we add the notice
120 // only if the difference is more than 1 second.
121 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
123 'label' => t('This entry was edited'),
124 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
125 'relative' => relative_date($item['edited'])
134 $isstarred = "unstarred";
138 $total_children = $this->countDescendants();
140 $conv = $this->getThread();
142 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
143 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
144 ? t('Private Message')
146 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
148 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
149 if ($item["event-id"] != 0) {
150 $edpost = array("events/event/" . $item['event-id'], t("Edit"));
152 $edpost = array("editpost/" . $item['id'], t("Edit"));
158 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
163 'dropping' => $dropping,
164 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
165 'select' => t('Select'),
166 'delete' => t('Delete'),
169 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
171 $diff_author = !link_compare($item['url'], $item['author-link']);
172 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
173 if ($item['author-link'] && (!$item['author-name'])) {
174 $profile_name = $item['author-link'];
178 $profile_link = best_link_url($item, $sp);
179 if ($profile_link === 'mailbox') {
184 $sparkle = ' sparkle';
186 $profile_link = zrl($profile_link);
189 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
190 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
191 if ($author_contact["thumb"]) {
192 $item['author-thumb'] = $author_contact["thumb"];
194 $item['author-thumb'] = $item['author-avatar'];
198 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
199 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
200 if ($owner_contact["thumb"]) {
201 $item['owner-thumb'] = $owner_contact["thumb"];
203 $item['owner-thumb'] = $item['owner-avatar'];
207 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
208 call_hooks('render_location', $locate);
209 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
211 // process action responses - e.g. like/dislike/attend/agree/whatever
212 $response_verbs = array('like', 'dislike');
216 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
217 $response_verbs[] = 'attendyes';
218 $response_verbs[] = 'attendno';
219 $response_verbs[] = 'attendmaybe';
220 if ($conv->isWritable()) {
222 $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
226 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
228 foreach ($response_verbs as $value => $verbs) {
229 $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']) : '';
233 * We should avoid doing this all the time, but it depends on the conversation mode
234 * And the conv mode may change when we change the conv, or it changes its mode
235 * Maybe we should establish a way to be notified about conversation changes
237 $this->checkWallToWall();
239 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
240 $osparkle = ' sparkle';
245 if ($this->isToplevel()) {
246 if ($conv->getProfileOwner() == local_user()) {
247 $isstarred = (($item['starred']) ? "starred" : "unstarred");
250 'do' => t("add star"),
251 'undo' => t("remove star"),
252 'toggle' => t("toggle star status"),
253 'classdo' => $item['starred'] ? "hidden" : "",
254 'classundo' => $item['starred'] ? "" : "hidden",
255 'starred' => t('starred'),
257 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
258 if (DBM::is_result($r)) {
260 'do' => t("ignore thread"),
261 'undo' => t("unignore thread"),
262 'toggle' => t("toggle ignore status"),
263 'classdo' => $r['ignored'] ? "hidden" : "",
264 'classundo' => $r['ignored'] ? "" : "hidden",
265 'ignored' => t('ignored'),
269 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
271 'add' => t("add tag"),
280 if ($conv->isWritable()) {
282 'like' => array(t("I like this \x28toggle\x29"), t("like")),
283 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
286 $buttons['share'] = array(t('Share this'), t('share'));
290 $comment = $this->getCommentBox($indent);
292 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
296 localize_item($item);
298 $body = prepare_body($item, true);
300 list($categories, $folders) = get_cats_and_terms($item);
303 $text_e = strip_tags($body);
304 $name_e = $profile_name;
305 $title_e = $item['title'];
306 $location_e = $location;
307 $owner_name_e = $this->getOwnerName();
309 // Disable features that aren't available in several networks
310 /// @todo Add NETWORK_DIASPORA when it will pass this information
311 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
312 unset($buttons["dislike"]);
317 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
318 unset($buttons["like"]);
321 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
322 unset($buttons["like"]);
326 'template' => $this->getTemplate(),
327 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
328 'tags' => $item['tags'],
329 'hashtags' => $item['hashtags'],
330 'mentions' => $item['mentions'],
331 'txt_cats' => t('Categories:'),
332 'txt_folders' => t('Filed under:'),
333 'has_cats' => ((count($categories)) ? 'true' : ''),
334 'has_folders' => ((count($folders)) ? 'true' : ''),
335 'categories' => $categories,
336 'folders' => $folders,
339 'id' => $this->getId(),
340 'guid' => urlencode($item['guid']),
341 'isevent' => $isevent,
343 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
344 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
347 'wall' => t('Wall-to-Wall'),
348 'vwall' => t('via Wall-To-Wall:'),
349 'profile_url' => $profile_link,
350 'item_photo_menu' => item_photo_menu($item),
352 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
353 'osparkle' => $osparkle,
354 'sparkle' => $sparkle,
356 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
357 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
358 'app' => $item['app'],
359 'created' => relative_date($item['created']),
361 'location' => $location_e,
364 'owner_url' => $this->getOwnerUrl(),
365 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
366 'owner_name' => htmlentities($owner_name_e),
367 'plink' => get_plink($item),
368 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
369 'isstarred' => $isstarred,
370 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
371 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
373 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
376 'like' => $responses['like']['output'],
377 'dislike' => $responses['dislike']['output'],
378 'responses' => $responses,
379 'switchcomment' => t('Comment'),
380 'comment' => $comment,
381 'previewing' => $conv->isPreview() ? ' preview ' : '',
382 'wait' => t('Please wait'),
383 'thread_level' => $thread_level,
385 'network' => $item["item_network"],
386 'network_name' => network_to_name($item['item_network'], $profile_link),
387 'received' => $item['received'],
388 'commented' => $item['commented'],
389 'created_date' => $item['created'],
392 $arr = array('item' => $item, 'output' => $tmp_item);
393 call_hooks('display_item', $arr);
395 $result = $arr['output'];
397 $result['children'] = array();
398 $children = $this->getChildren();
399 $nb_children = count($children);
400 if ($nb_children > 0) {
401 foreach ($children as $child) {
402 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
405 if (($nb_children > 2) || ($thread_level > 1)) {
406 $result['children'][0]['comment_firstcollapsed'] = true;
407 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
408 $result['children'][0]['hidden_comments_num'] = $total_children;
409 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
410 $result['children'][0]['hide_text'] = t('show more');
411 if ($thread_level > 1) {
412 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
414 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
419 if ($this->isToplevel()) {
420 $result['total_comments_num'] = "$total_children";
421 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
424 $result['private'] = $item['private'];
425 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
427 if ($this->isThreaded()) {
428 $result['flatten'] = false;
429 $result['threaded'] = true;
431 $result['flatten'] = true;
432 $result['threaded'] = false;
441 public function getId()
443 return $this->getDataValue('id');
449 public function isThreaded()
451 return $this->threaded;
457 * @param object $item The child item to add
461 public function addChild(Post $item)
463 $item_id = $item->getId();
465 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
467 } elseif ($this->getChild($item->getId())) {
468 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
472 * Only add what will be displayed
474 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
476 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
480 $item->setParent($this);
481 $this->children[] = $item;
483 return end($this->children);
487 * Get a child by its ID
489 * @param integer $id The child id
493 public function getChild($id)
495 foreach ($this->getChildren() as $child) {
496 if ($child->getId() == $id) {
505 * Get all our children
509 public function getChildren()
511 return $this->children;
517 * @param object $item The item to set as parent
521 protected function setParent($item)
523 $parent = $this->getParent();
525 $parent->removeChild($this);
528 $this->parent = $item;
529 $this->setThread($item->getThread());
537 protected function removeParent()
539 $this->parent = null;
540 $this->thread = null;
546 * @param object $item The child to be removed
548 * @return boolean Success or failure
550 public function removeChild($item)
552 $id = $item->getId();
553 foreach ($this->getChildren() as $key => $child) {
554 if ($child->getId() == $id) {
555 $child->removeParent();
556 unset($this->children[$key]);
557 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
558 $this->children = array_values($this->children);
562 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
571 protected function getParent()
573 return $this->parent;
579 * @param object $conv The conversation
583 public function setThread($conv)
585 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
587 $this->thread = $conv;
589 // Set it on our children too
590 foreach ($this->getChildren() as $child) {
591 $child->setThread($conv);
600 public function getThread()
602 return $this->thread;
608 * We shouldn't need this
612 public function getData()
620 * @param object $name key
622 * @return mixed value on success
625 public function getDataValue($name)
627 if (!isset($this->data[$name])) {
628 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
632 return $this->data[$name];
638 * @param object $name template name
642 private function setTemplate($name)
644 if (!x($this->available_templates, $name)) {
645 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
649 $this->template = $this->available_templates[$name];
657 private function getTemplate()
659 return $this->template;
663 * Check if this is a toplevel post
667 private function isToplevel()
669 return $this->toplevel;
673 * Check if this is writable
677 private function isWritable()
679 $conv = $this->getThread();
682 // This will allow us to comment on wall-to-wall items owned by our friends
683 // and community forums even if somebody else wrote the post.
684 // bug #517 - this fixes for conversation owner
685 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
689 // this fixes for visitors
690 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
692 return $this->writable;
696 * Count the total of our descendants
700 private function countDescendants()
702 $children = $this->getChildren();
703 $total = count($children);
705 foreach ($children as $child) {
706 $total += $child->countDescendants();
714 * Get the template for the comment box
718 private function getCommentBoxTemplate()
720 return $this->comment_box_template;
724 * Get the comment box
726 * @param string $indent Indent value
728 * @return mixed The comment box string (empty if no comment box)
731 private function getCommentBox($indent)
736 $conv = $this->getThread();
738 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
742 if ($conv->isWritable() && $this->isWritable()) {
743 $qc = $qcomment = null;
746 * Hmmm, code depending on the presence of a particular plugin?
747 * This should be better if done by a hook
749 if (in_array('qcomment', $a->plugins)) {
750 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
751 $qcomment = (($qc) ? explode("\n", $qc) : null);
754 $template = get_markup_template($this->getCommentBoxTemplate());
755 $comment_box = replace_macros($template, array(
756 '$return_path' => $a->query_string,
757 '$threaded' => $this->isThreaded(),
759 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
760 '$id' => $this->getId(),
761 '$parent' => $this->getId(),
762 '$qcomment' => $qcomment,
763 '$profile_uid' => $conv->getProfileOwner(),
764 '$mylink' => $a->remove_baseurl($a->contact['url']),
765 '$mytitle' => t('This is you'),
766 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
767 '$comment' => t('Comment'),
768 '$submit' => t('Submit'),
769 '$edbold' => t('Bold'),
770 '$editalic' => t('Italic'),
771 '$eduline' => t('Underline'),
772 '$edquote' => t('Quote'),
773 '$edcode' => t('Code'),
774 '$edimg' => t('Image'),
775 '$edurl' => t('Link'),
776 '$edvideo' => t('Video'),
777 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
778 '$indent' => $indent,
779 '$sourceapp' => t($a->sourcename),
780 '$ww' => $conv->getMode() === 'network' ? $ww : '',
781 '$rand_num' => random_digits(12)
791 private function getRedirectUrl()
793 return $this->redirect_url;
797 * Check if we are a wall to wall item and set the relevant properties
801 protected function checkWallToWall()
804 $conv = $this->getThread();
805 $this->wall_to_wall = false;
807 if ($this->isToplevel()) {
808 if ($conv->getMode() !== 'profile') {
809 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
810 // On the network page, I am the owner. On the display page it will be the profile owner.
811 // This will have been stored in $a->page_contact by our calling page.
812 // Put this person as the wall owner of the wall-to-wall notice.
814 $this->owner_url = zrl($a->page_contact['url']);
815 $this->owner_photo = $a->page_contact['thumb'];
816 $this->owner_name = $a->page_contact['name'];
817 $this->wall_to_wall = true;
818 } elseif ($this->getDataValue('owner-link')) {
819 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
820 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
821 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
823 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
824 // The author url doesn't match the owner (typically the contact)
825 // and also doesn't match the contact alias.
826 // The name match is a hack to catch several weird cases where URLs are
827 // all over the park. It can be tricked, but this prevents you from
828 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
829 // well that it's the same Bob Smith.
830 // But it could be somebody else with the same name. It just isn't highly likely.
833 $this->owner_photo = $this->getDataValue('owner-avatar');
834 $this->owner_name = $this->getDataValue('owner-name');
835 $this->wall_to_wall = true;
836 // If it is our contact, use a friendly redirect link
837 if ($this->getDataValue('network') === NETWORK_DFRN
838 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
840 $this->owner_url = $this->getRedirectUrl();
842 $this->owner_url = zrl($this->getDataValue('owner-link'));
849 if (!$this->wall_to_wall) {
850 $this->setTemplate('wall');
851 $this->owner_url = '';
852 $this->owner_photo = '';
853 $this->owner_name = '';
860 private function isWallToWall()
862 return $this->wall_to_wall;
868 private function getOwnerUrl()
870 return $this->owner_url;
876 private function getOwnerName()
878 return $this->owner_name;
884 private function isVisiting()
886 return $this->visiting;