3 * @file src/Object/Post.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
14 require_once 'include/text.php';
15 require_once 'boot.php';
16 require_once 'include/conversation.php';
21 class Post extends BaseObject
23 private $data = array();
24 private $template = null;
25 private $available_templates = array(
26 'wall' => 'wall_thread.tpl',
27 'wall2wall' => 'wallwall_thread.tpl'
29 private $comment_box_template = 'comment_item.tpl';
30 private $toplevel = false;
31 private $writable = false;
32 private $children = array();
33 private $parent = null;
34 private $thread = null;
35 private $redirect_url = null;
36 private $owner_url = '';
37 private $owner_photo = '';
38 private $owner_name = '';
39 private $wall_to_wall = false;
40 private $threaded = false;
41 private $visiting = false;
46 * @param array $data data array
48 public function __construct($data)
53 $this->setTemplate('wall');
54 $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
56 if (is_array($_SESSION['remote'])) {
57 foreach ($_SESSION['remote'] as $visitor) {
58 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
59 $this->visiting = true;
65 $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
67 $ssl_state = ((local_user()) ? true : false);
68 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
70 if (!$this->isToplevel()) {
71 $this->threaded = true;
74 // Prepare the children
75 if (count($data['children'])) {
76 foreach ($data['children'] as $item) {
78 * 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 items
87 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
88 $item['writable'] = true;
91 $item['pagedrop'] = $data['pagedrop'];
92 $child = new Item($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 = ((($conv->getProfileOwner() == local_user()) && ($item['private'] != 1)) ? true : false);
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'])) ? false : true);
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));
215 /*foreach(explode(',',$item['tag']) as $tag){
227 // process action responses - e.g. like/dislike/attend/agree/whatever
228 $response_verbs = array('like', 'dislike');
230 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
231 $response_verbs[] = 'attendyes';
232 $response_verbs[] = 'attendno';
233 $response_verbs[] = 'attendmaybe';
234 if ($conv->isWritable()) {
236 $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
240 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
242 foreach ($response_verbs as $value => $verbs) {
243 $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']) : '');
247 * We should avoid doing this all the time, but it depends on the conversation mode
248 * And the conv mode may change when we change the conv, or it changes its mode
249 * Maybe we should establish a way to be notified about conversation changes
251 $this->checkWallToWall();
253 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
254 $osparkle = ' sparkle';
257 if ($this->isToplevel()) {
258 if ($conv->getProfileOwner() == local_user()) {
259 $isstarred = (($item['starred']) ? "starred" : "unstarred");
262 'do' => t("add star"),
263 'undo' => t("remove star"),
264 'toggle' => t("toggle star status"),
265 'classdo' => (($item['starred']) ? "hidden" : ""),
266 'classundo' => (($item['starred']) ? "" : "hidden"),
267 'starred' => t('starred'),
269 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
270 if (DBM::is_result($r)) {
272 'do' => t("ignore thread"),
273 'undo' => t("unignore thread"),
274 'toggle' => t("toggle ignore status"),
275 'classdo' => (($r['ignored']) ? "hidden" : ""),
276 'classundo' => (($r['ignored']) ? "" : "hidden"),
277 'ignored' => t('ignored'),
282 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
284 'add' => t("add tag"),
293 if ($conv->isWritable()) {
295 'like' => array( t("I like this \x28toggle\x29"), t("like")),
296 'dislike' => ((Feature::isEnabled($conv->getProfileOwner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
299 $buttons['share'] = array( t('Share this'), t('share'));
303 $comment = $this->getCommentBox($indent);
305 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
309 localize_item($item);
311 $body = prepare_body($item, true);
313 list($categories, $folders) = get_cats_and_terms($item);
316 $text_e = strip_tags($body);
317 $name_e = $profile_name;
318 $title_e = $item['title'];
319 $location_e = $location;
320 $owner_name_e = $this->getOwnerName();
322 // Disable features that aren't available in several networks
324 /// @todo Add NETWORK_DIASPORA when it will pass this information
325 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
326 unset($buttons["dislike"], $isevent);
330 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
331 unset($buttons["like"]);
334 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
335 unset($buttons["like"]);
339 'template' => $this->getTemplate(),
340 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
341 'tags' => $item['tags'],
342 'hashtags' => $item['hashtags'],
343 'mentions' => $item['mentions'],
344 'txt_cats' => t('Categories:'),
345 'txt_folders' => t('Filed under:'),
346 'has_cats' => ((count($categories)) ? 'true' : ''),
347 'has_folders' => ((count($folders)) ? 'true' : ''),
348 'categories' => $categories,
349 'folders' => $folders,
352 'id' => $this->getId(),
353 'guid' => urlencode($item['guid']),
354 'isevent' => $isevent,
356 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
357 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
360 'wall' => t('Wall-to-Wall'),
361 'vwall' => t('via Wall-To-Wall:'),
362 'profile_url' => $profile_link,
363 'item_photo_menu' => item_photo_menu($item),
365 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
366 'osparkle' => $osparkle,
367 'sparkle' => $sparkle,
369 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
370 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
371 'app' => $item['app'],
372 'created' => relative_date($item['created']),
374 'location' => $location_e,
377 'owner_url' => $this->getOwnerUrl(),
378 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
379 'owner_name' => htmlentities($owner_name_e),
380 'plink' => get_plink($item),
381 'edpost' => ((Feature::isEnabled($conv->getProfileOwner(), 'edit_posts')) ? $edpost : ''),
382 'isstarred' => $isstarred,
383 'star' => ((Feature::isEnabled($conv->getProfileOwner(), 'star_posts')) ? $star : ''),
384 'ignore' => ((Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts')) ? $ignore : ''),
386 'filer' => ((Feature::isEnabled($conv->getProfileOwner(), 'filing')) ? $filer : ''),
389 'like' => $responses['like']['output'],
390 'dislike' => $responses['dislike']['output'],
391 'responses' => $responses,
392 'switchcomment' => t('Comment'),
393 'comment' => $comment,
394 'previewing' => ($conv->isPreview() ? ' preview ' : ''),
395 'wait' => t('Please wait'),
396 'thread_level' => $thread_level,
398 'network' => $item["item_network"],
399 'network_name' => network_to_name($item['item_network'], $profile_link),
400 'received' => $item['received'],
401 'commented' => $item['commented'],
402 'created_date' => $item['created'],
405 $arr = array('item' => $item, 'output' => $tmp_item);
406 call_hooks('display_item', $arr);
408 $result = $arr['output'];
410 $result['children'] = array();
411 $children = $this->getChildren();
412 $nb_children = count($children);
413 if ($nb_children > 0) {
414 foreach ($children as $child) {
415 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
418 if (($nb_children > 2) || ($thread_level > 1)) {
419 $result['children'][0]['comment_firstcollapsed'] = true;
420 $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
421 $result['children'][0]['hidden_comments_num'] = $total_children;
422 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
423 $result['children'][0]['hide_text'] = t('show more');
424 if ($thread_level > 1) {
425 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
427 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
432 if ($this->isToplevel()) {
433 $result['total_comments_num'] = "$total_children";
434 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
437 $result['private'] = $item['private'];
438 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
440 if ($this->isThreaded()) {
441 $result['flatten'] = false;
442 $result['threaded'] = true;
444 $result['flatten'] = true;
445 $result['threaded'] = false;
454 public function getId()
456 return $this->getDataValue('id');
462 public function isThreaded()
464 return $this->threaded;
470 * @param object $item The child item to add
474 public function addChild(Item $item)
476 $item_id = $item->getId();
478 logger('[ERROR] Item::addChild : Item has no ID!!', LOGGER_DEBUG);
480 } elseif ($this->getChild($item->getId())) {
481 logger('[WARN] Item::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
485 * Only add what will be displayed
487 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
489 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
493 $item->setParent($this);
494 $this->children[] = $item;
496 return end($this->children);
500 * Get a child by its ID
502 * @param integer $id The child id
506 public function getChild($id)
508 foreach ($this->getChildren() as $child) {
509 if ($child->getId() == $id) {
518 * Get all our children
522 public function getChildren()
524 return $this->children;
530 * @param object $item The item to set as parent
534 protected function setParent($item)
536 $parent = $this->getParent();
538 $parent->removeChild($this);
541 $this->parent = $item;
542 $this->setThread($item->getThread());
550 protected function removeParent()
552 $this->parent = null;
553 $this->thread = null;
559 * @param object $item The child to be removed
561 * @return boolean Success or failure
563 public function removeChild($item)
565 $id = $item->getId();
566 foreach ($this->getChildren() as $key => $child) {
567 if ($child->getId() == $id) {
568 $child->removeParent();
569 unset($this->children[$key]);
570 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
571 $this->children = array_values($this->children);
575 logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
584 protected function getParent()
586 return $this->parent;
592 * @param object $conv The conversation
596 public function setThread($conv)
598 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
600 $this->thread = $conv;
602 // Set it on our children too
603 foreach ($this->getChildren() as $child) {
604 $child->setThread($conv);
613 public function getThread()
615 return $this->thread;
621 * We shouldn't need this
625 public function getData()
633 * @param object $name key
635 * @return mixed value on success
638 public function getDataValue($name)
640 if (!isset($this->data[$name])) {
641 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
645 return $this->data[$name];
651 * @param object $name template name
655 private function setTemplate($name)
657 if (!x($this->available_templates, $name)) {
658 logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
662 $this->template = $this->available_templates[$name];
670 private function getTemplate()
672 return $this->template;
676 * Check if this is a toplevel post
680 private function isToplevel()
682 return $this->toplevel;
686 * Check if this is writable
690 private function isWritable()
692 $conv = $this->getThread();
695 // This will allow us to comment on wall-to-wall items owned by our friends
696 // and community forums even if somebody else wrote the post.
698 // bug #517 - this fixes for conversation owner
699 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
703 // this fixes for visitors
704 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
706 return $this->writable;
710 * Count the total of our descendants
714 private function countDescendants()
716 $children = $this->getChildren();
717 $total = count($children);
719 foreach ($children as $child) {
720 $total += $child->countDescendants();
728 * Get the template for the comment box
732 private function getCommentBoxTemplate()
734 return $this->comment_box_template;
738 * Get the comment box
740 * @param string $indent Indent value
742 * @return mixed The comment box string (empty if no comment box)
745 private function getCommentBox($indent)
750 $conv = $this->getThread();
751 $template = get_markup_template($this->getCommentBoxTemplate());
753 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
757 if ($conv->isWritable() && $this->isWritable()) {
758 $qc = $qcomment = null;
761 * Hmmm, code depending on the presence of a particular plugin?
762 * This should be better if done by a hook
764 if (in_array('qcomment', $a->plugins)) {
765 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
766 $qcomment = (($qc) ? explode("\n", $qc) : null);
769 $comment_box = replace_macros(
772 '$return_path' => $a->query_string,
773 '$threaded' => $this->isThreaded(),
774 // '$jsreload' => (($conv->getMode() === 'display') ? $_SESSION['return_url'] : ''),
776 '$type' => (($conv->getMode() === 'profile') ? 'wall-comment' : 'net-comment'),
777 '$id' => $this->getId(),
778 '$parent' => $this->getId(),
779 '$qcomment' => $qcomment,
780 '$profile_uid' => $conv->getProfileOwner(),
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 = 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.
848 // But it could be somebody else with the same name. It just isn't highly likely.
851 $this->owner_photo = $this->getDataValue('owner-avatar');
852 $this->owner_name = $this->getDataValue('owner-name');
853 $this->wall_to_wall = true;
854 // If it is our contact, use a friendly redirect link
855 if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
856 && ($this->getDataValue('network') === NETWORK_DFRN)
858 $this->owner_url = $this->getRedirectUrl();
860 $this->owner_url = zrl($this->getDataValue('owner-link'));
867 if (!$this->wall_to_wall) {
868 $this->setTemplate('wall');
869 $this->owner_url = '';
870 $this->owner_photo = '';
871 $this->owner_name = '';
878 private function isWallToWall()
880 return $this->wall_to_wall;
886 private function getOwnerUrl()
888 return $this->owner_url;
894 private function getOwnerName()
896 return $this->owner_name;
902 private function isVisiting()
904 return $this->visiting;