4 * @file include/items.php
7 use \Friendica\ParseUrl;
9 require_once 'include/bbcode.php';
10 require_once 'include/oembed.php';
11 require_once 'include/salmon.php';
12 require_once 'include/crypto.php';
13 require_once 'include/Photo.php';
14 require_once 'include/tags.php';
15 require_once 'include/files.php';
16 require_once 'include/text.php';
17 require_once 'include/email.php';
18 require_once 'include/threads.php';
19 require_once 'include/socgraph.php';
20 require_once 'include/plaintext.php';
21 require_once 'include/ostatus.php';
22 require_once 'include/feed.php';
23 require_once 'include/Contact.php';
24 require_once 'mod/share.php';
25 require_once 'include/enotify.php';
26 require_once 'include/dfrn.php';
27 require_once 'include/group.php';
29 /// @TODO one day with composer autoloader no more needed
30 require_once 'library/defuse/php-encryption-1.2.1/Crypto.php';
32 function construct_verb($item) {
41 * The purpose of this function is to apply system message length limits to
42 * imported messages without including any embedded photos in the length
44 if (! function_exists('limit_body_size')) {
45 function limit_body_size($body) {
47 // logger('limit_body_size: start', LOGGER_DEBUG);
49 $maxlen = get_max_import_size();
51 // If the length of the body, including the embedded images, is smaller
52 // than the maximum, then don't waste time looking for the images
53 if ($maxlen && (strlen($body) > $maxlen)) {
55 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
62 $img_start = strpos($orig_body, '[img');
63 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
64 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
65 while (($img_st_close !== false) && ($img_end !== false)) {
67 $img_st_close++; // make it point to AFTER the closing bracket
68 $img_end += $img_start;
69 $img_end += strlen('[/img]');
71 if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
72 // This is an embedded image
74 if (($textlen + $img_start) > $maxlen ) {
75 if ($textlen < $maxlen) {
76 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
77 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
81 $new_body = $new_body . substr($orig_body, 0, $img_start);
82 $textlen += $img_start;
85 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
88 if (($textlen + $img_end) > $maxlen ) {
89 if ($textlen < $maxlen) {
90 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
91 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
95 $new_body = $new_body . substr($orig_body, 0, $img_end);
99 $orig_body = substr($orig_body, $img_end);
101 if ($orig_body === false) {
102 // in case the body ends on a closing image tag
106 $img_start = strpos($orig_body, '[img');
107 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
108 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
111 if (($textlen + strlen($orig_body)) > $maxlen) {
112 if ($textlen < $maxlen) {
113 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
114 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
118 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
119 $new_body = $new_body . $orig_body;
120 $textlen += strlen($orig_body);
129 function title_is_body($title, $body) {
131 $title = strip_tags($title);
132 $title = trim($title);
133 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
134 $title = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $title);
136 $body = strip_tags($body);
138 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
139 $body = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $body);
141 if (strlen($title) < strlen($body)) {
142 $body = substr($body, 0, strlen($title));
145 if (($title != $body) and (substr($title, -3) == "...")) {
146 $pos = strrpos($title, "...");
148 $title = substr($title, 0, $pos);
149 $body = substr($body, 0, $pos);
153 return ($title == $body);
156 function add_page_info_data($data) {
157 call_hooks('page_info_data', $data);
159 // It maybe is a rich content, but if it does have everything that a link has,
160 // then treat it that way
161 if (($data["type"] == "rich") AND is_string($data["title"]) AND
162 is_string($data["text"]) AND (sizeof($data["images"]) > 0)) {
163 $data["type"] = "link";
166 if ((($data["type"] != "link") AND ($data["type"] != "video") AND ($data["type"] != "photo")) OR ($data["title"] == $data["url"])) {
170 if ($no_photos AND ($data["type"] == "photo")) {
174 if (sizeof($data["images"]) > 0) {
175 $preview = $data["images"][0];
180 // Escape some bad characters
181 $data["url"] = str_replace(array("[", "]"), array("[", "]"), htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
182 $data["title"] = str_replace(array("[", "]"), array("[", "]"), htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
184 $text = "[attachment type='".$data["type"]."'";
186 if ($data["text"] == "") {
187 $data["text"] = $data["title"];
190 if ($data["text"] == "") {
191 $data["text"] = $data["url"];
194 if ($data["url"] != "") {
195 $text .= " url='".$data["url"]."'";
198 if ($data["title"] != "") {
199 $text .= " title='".$data["title"]."'";
202 if (sizeof($data["images"]) > 0) {
203 $preview = str_replace(array("[", "]"), array("[", "]"), htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
204 // if the preview picture is larger than 500 pixels then show it in a larger mode
205 // But only, if the picture isn't higher than large (To prevent huge posts)
206 if (($data["images"][0]["width"] >= 500) AND ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
207 $text .= " image='".$preview."'";
209 $text .= " preview='".$preview."'";
213 $text .= "]".$data["text"]."[/attachment]";
216 if (isset($data["keywords"]) AND count($data["keywords"])) {
218 foreach ($data["keywords"] AS $keyword) {
219 /// @todo make a positive list of allowed characters
220 $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"),
221 array("", "", "", "", "", "", "", "", "", "", "", ""), $keyword);
222 $hashtags .= "#[url=" . App::get_baseurl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
226 return "\n".$text.$hashtags;
229 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
231 $data = ParseUrl::getSiteinfoCached($url, true);
234 $data["images"][0]["src"] = $photo;
237 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
239 if (!$keywords AND isset($data["keywords"])) {
240 unset($data["keywords"]);
243 if (($keyword_blacklist != "") AND isset($data["keywords"])) {
244 $list = explode(", ", $keyword_blacklist);
245 foreach ($list AS $keyword) {
246 $keyword = trim($keyword);
247 $index = array_search($keyword, $data["keywords"]);
248 if ($index !== false) {
249 unset($data["keywords"][$index]);
257 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
258 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
261 if (isset($data["keywords"]) AND count($data["keywords"])) {
262 foreach ($data["keywords"] AS $keyword) {
263 $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
264 array("", "", "", "", "", ""), $keyword);
270 $tags .= "#[url=" . App::get_baseurl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
277 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
278 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
280 $text = add_page_info_data($data);
285 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
287 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
289 $URLSearchString = "^\[\]";
291 // Fix for Mastodon where the mentions are in a different format
292 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
293 '$2[url=$1]$3[/url]', $body);
295 // Adding these spaces is a quick hack due to my problems with regular expressions :)
296 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
299 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
302 // Convert urls without bbcode elements
303 if (!$matches AND $texturl) {
304 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
306 // Yeah, a hack. I really hate regular expressions :)
308 $matches[1] = $matches[2];
313 $footer = add_page_info($matches[1], $no_photos);
316 // Remove the link from the body if the link is attached at the end of the post
317 if (isset($footer) AND (trim($footer) != "") AND (strpos($footer, $matches[1]))) {
318 $removedlink = trim(str_replace($matches[1], "", $body));
319 if (($removedlink == "") OR strstr($body, $removedlink)) {
320 $body = $removedlink;
323 $url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
324 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
325 if (($removedlink == "") OR strstr($body, $removedlink)) {
326 $body = $removedlink;
330 // Add the page information to the bottom
331 if (isset($footer) AND (trim($footer) != "")) {
339 * Adds a "lang" specification in a "postopts" element of given $arr,
340 * if possible and not already present.
341 * Expects "body" element to exist in $arr.
343 * @todo Add a parameter to request forcing override
345 function item_add_language_opt(&$arr) {
347 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
348 // LanguageDetect.php not available ?
352 if (x($arr, 'postopts') ) {
353 if (strstr($arr['postopts'], 'lang=') ) {
355 /// @TODO Add parameter to request overriding
358 $postopts = $arr['postopts'];
363 require_once('library/langdet/Text/LanguageDetect.php');
365 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
366 $l = new Text_LanguageDetect();
367 //$lng = $l->detectConfidence($naked_body);
368 //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
369 $lng = $l->detect($naked_body, 3);
371 if (sizeof($lng) > 0) {
372 if ($postopts != "") $postopts .= '&'; // arbitrary separator, to be reviewed
373 $postopts .= 'lang=';
375 foreach ($lng as $language => $score) {
376 $postopts .= $sep . $language . ";" . $score;
379 $arr['postopts'] = $postopts;
384 * @brief Creates an unique guid out of a given uri
386 * @param string $uri uri of an item entry
387 * @param string $host (Optional) hostname for the GUID prefix
388 * @return string unique guid
390 function uri_to_guid($uri, $host = "") {
392 // Our regular guid routine is using this kind of prefix as well
393 // We have to avoid that different routines could accidentally create the same value
394 $parsed = parse_url($uri);
397 $host = $parsed["host"];
400 $guid_prefix = hash("crc32", $host);
402 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
403 unset($parsed["scheme"]);
405 $host_id = implode("/", $parsed);
407 // We could use any hash algorithm since it isn't a security issue
408 $host_hash = hash("ripemd128", $host_id);
410 return $guid_prefix.$host_hash;
413 /// @TODO Maybe $arr must be called-by-reference? This function modifies it
414 /// @TODO add type-hint array
415 function item_store($arr, $force_parent = false, $notify = false, $dontcache = false) {
419 // If it is a posting where users should get notifications, then define it as wall posting
422 $arr['type'] = 'wall';
424 $arr['last-child'] = 1;
425 $arr['network'] = NETWORK_DFRN;
427 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
428 // In difference to the call to "uri_to_guid" several lines below we add the hash of our own host.
429 // This is done because our host is the original creator of the post.
430 if (!isset($arr['guid'])) {
431 if (isset($arr['plink'])) {
432 $arr['guid'] = uri_to_guid($arr['plink'], $a->get_hostname());
433 } elseif (isset($arr['uri'])) {
434 $arr['guid'] = uri_to_guid($arr['uri'], $a->get_hostname());
440 * If a Diaspora signature structure was passed in, pull it out of the
441 * item array and set it aside for later storage.
445 if (x($arr, 'dsprsig')) {
446 $encoded_signature = $arr['dsprsig'];
447 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
448 unset($arr['dsprsig']);
451 // Converting the plink
452 if ($arr['network'] == NETWORK_OSTATUS) {
453 if (isset($arr['plink'])) {
454 $arr['plink'] = ostatus::convert_href($arr['plink']);
455 } elseif (isset($arr['uri'])) {
456 $arr['plink'] = ostatus::convert_href($arr['uri']);
460 if (x($arr, 'gravity')) {
461 $arr['gravity'] = intval($arr['gravity']);
462 } elseif ($arr['parent-uri'] === $arr['uri']) {
464 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
467 $arr['gravity'] = 6; // extensible catchall
470 if (! x($arr, 'type')) {
471 $arr['type'] = 'remote';
474 // check for create date and expire time
475 $uid = intval($arr['uid']);
476 $r = q("SELECT expire FROM user WHERE uid = %d", intval($uid));
477 if (dbm::is_result($r)) {
478 $expire_interval = $r[0]['expire'];
479 if ($expire_interval>0) {
480 $expire_date = new DateTime( '- '.$expire_interval.' days', new DateTimeZone('UTC'));
481 $created_date = new DateTime($arr['created'], new DateTimeZone('UTC'));
482 if ($created_date < $expire_date) {
483 logger('item-store: item created ('.$arr['created'].') before expiration time ('.$expire_date->format(DateTime::W3C).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
490 * Do we already have this item?
491 * We have to check several networks since Friendica posts could be repeated
492 * via OStatus (maybe Diasporsa as well)
494 if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
495 $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
496 dbesc(trim($arr['uri'])),
498 dbesc(NETWORK_DIASPORA),
500 dbesc(NETWORK_OSTATUS)
502 if (dbm::is_result($r)) {
503 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
505 logger("Item with uri ".$arr['uri']." already existed for user ".$uid." with id ".$r[0]["id"]." target network ".$r[0]["network"]." - new network: ".$arr['network']);
512 /// @TODO old-lost code?
513 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
514 // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
515 //if ((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
516 // $arr['body'] = strip_tags($arr['body']);
518 item_add_language_opt($arr);
522 } elseif ((trim($arr['guid']) == "") AND (trim($arr['plink']) != "")) {
523 $arr['guid'] = uri_to_guid($arr['plink']);
524 } elseif ((trim($arr['guid']) == "") AND (trim($arr['uri']) != "")) {
525 $arr['guid'] = uri_to_guid($arr['uri']);
527 $parsed = parse_url($arr["author-link"]);
528 $guid_prefix = hash("crc32", $parsed["host"]);
531 $arr['wall'] = ((x($arr, 'wall')) ? intval($arr['wall']) : 0);
532 $arr['guid'] = ((x($arr, 'guid')) ? notags(trim($arr['guid'])) : get_guid(32, $guid_prefix));
533 $arr['uri'] = ((x($arr, 'uri')) ? notags(trim($arr['uri'])) : item_new_uri($a->get_hostname(), $uid, $arr['guid']));
534 $arr['extid'] = ((x($arr, 'extid')) ? notags(trim($arr['extid'])) : '');
535 $arr['author-name'] = ((x($arr, 'author-name')) ? trim($arr['author-name']) : '');
536 $arr['author-link'] = ((x($arr, 'author-link')) ? notags(trim($arr['author-link'])) : '');
537 $arr['author-avatar'] = ((x($arr, 'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
538 $arr['owner-name'] = ((x($arr, 'owner-name')) ? trim($arr['owner-name']) : '');
539 $arr['owner-link'] = ((x($arr, 'owner-link')) ? notags(trim($arr['owner-link'])) : '');
540 $arr['owner-avatar'] = ((x($arr, 'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
541 $arr['created'] = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : datetime_convert());
542 $arr['edited'] = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : datetime_convert());
543 $arr['commented'] = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : datetime_convert());
544 $arr['received'] = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
545 $arr['changed'] = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : datetime_convert());
546 $arr['title'] = ((x($arr, 'title')) ? trim($arr['title']) : '');
547 $arr['location'] = ((x($arr, 'location')) ? trim($arr['location']) : '');
548 $arr['coord'] = ((x($arr, 'coord')) ? notags(trim($arr['coord'])) : '');
549 $arr['last-child'] = ((x($arr, 'last-child')) ? intval($arr['last-child']) : 0 );
550 $arr['visible'] = ((x($arr, 'visible') !== false) ? intval($arr['visible']) : 1 );
552 $arr['parent-uri'] = ((x($arr, 'parent-uri')) ? notags(trim($arr['parent-uri'])) : $arr['uri']);
553 $arr['verb'] = ((x($arr, 'verb')) ? notags(trim($arr['verb'])) : '');
554 $arr['object-type'] = ((x($arr, 'object-type')) ? notags(trim($arr['object-type'])) : '');
555 $arr['object'] = ((x($arr, 'object')) ? trim($arr['object']) : '');
556 $arr['target-type'] = ((x($arr, 'target-type')) ? notags(trim($arr['target-type'])) : '');
557 $arr['target'] = ((x($arr, 'target')) ? trim($arr['target']) : '');
558 $arr['plink'] = ((x($arr, 'plink')) ? notags(trim($arr['plink'])) : '');
559 $arr['allow_cid'] = ((x($arr, 'allow_cid')) ? trim($arr['allow_cid']) : '');
560 $arr['allow_gid'] = ((x($arr, 'allow_gid')) ? trim($arr['allow_gid']) : '');
561 $arr['deny_cid'] = ((x($arr, 'deny_cid')) ? trim($arr['deny_cid']) : '');
562 $arr['deny_gid'] = ((x($arr, 'deny_gid')) ? trim($arr['deny_gid']) : '');
563 $arr['private'] = ((x($arr, 'private')) ? intval($arr['private']) : 0 );
564 $arr['bookmark'] = ((x($arr, 'bookmark')) ? intval($arr['bookmark']) : 0 );
565 $arr['body'] = ((x($arr, 'body')) ? trim($arr['body']) : '');
566 $arr['tag'] = ((x($arr, 'tag')) ? notags(trim($arr['tag'])) : '');
567 $arr['attach'] = ((x($arr, 'attach')) ? notags(trim($arr['attach'])) : '');
568 $arr['app'] = ((x($arr, 'app')) ? notags(trim($arr['app'])) : '');
569 $arr['origin'] = ((x($arr, 'origin')) ? intval($arr['origin']) : 0 );
570 $arr['network'] = ((x($arr, 'network')) ? trim($arr['network']) : '');
571 $arr['postopts'] = ((x($arr, 'postopts')) ? trim($arr['postopts']) : '');
572 $arr['resource-id'] = ((x($arr, 'resource-id')) ? trim($arr['resource-id']) : '');
573 $arr['event-id'] = ((x($arr, 'event-id')) ? intval($arr['event-id']) : 0 );
574 $arr['inform'] = ((x($arr, 'inform')) ? trim($arr['inform']) : '');
575 $arr['file'] = ((x($arr, 'file')) ? trim($arr['file']) : '');
577 // Items cannot be stored before they happen ...
578 if ($arr['created'] > datetime_convert()) {
579 $arr['created'] = datetime_convert();
582 // We haven't invented time travel by now.
583 if ($arr['edited'] > datetime_convert()) {
584 $arr['edited'] = datetime_convert();
587 if (($arr['author-link'] == "") AND ($arr['owner-link'] == "")) {
588 logger("Both author-link and owner-link are empty. Called by: " . App::callstack(), LOGGER_DEBUG);
591 if ($arr['plink'] == "") {
592 $arr['plink'] = App::get_baseurl() . '/display/' . urlencode($arr['guid']);
595 if ($arr['network'] == "") {
596 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
597 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
598 dbesc(normalise_link($arr['author-link'])),
602 if (!dbm::is_result($r))
603 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
604 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
605 dbesc(normalise_link($arr['author-link']))
608 if (!dbm::is_result($r)) {
609 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
610 intval($arr['contact-id']),
615 if (dbm::is_result($r)) {
616 $arr['network'] = $r[0]["network"];
619 // Fallback to friendica (why is it empty in some cases?)
620 if ($arr['network'] == "") {
621 $arr['network'] = NETWORK_DFRN;
624 logger("item_store: Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
627 // The contact-id should be set before "item_store" was called - but there seems to be some issues
628 if ($arr["contact-id"] == 0) {
630 * First we are looking for a suitable contact that matches with the author of the post
631 * This is done only for comments (See below explanation at "gcontact-id")
633 if ($arr['parent-uri'] != $arr['uri']) {
634 $arr["contact-id"] = get_contact($arr['author-link'], $uid);
637 // If not present then maybe the owner was found
638 if ($arr["contact-id"] == 0) {
639 $arr["contact-id"] = get_contact($arr['owner-link'], $uid);
642 // Still missing? Then use the "self" contact of the current user
643 if ($arr["contact-id"] == 0) {
644 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
646 if (dbm::is_result($r)) {
647 $arr["contact-id"] = $r[0]["id"];
651 logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
654 if ($arr["gcontact-id"] == 0) {
656 * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
657 * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
658 * On comments the author is the better choice.
660 if ($arr['parent-uri'] === $arr['uri']) {
661 $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['owner-link'], "network" => $arr['network'],
662 "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']));
664 $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'],
665 "photo" => $arr['author-avatar'], "name" => $arr['author-name']));
669 if ($arr["author-id"] == 0) {
670 $arr["author-id"] = get_contact($arr["author-link"], 0);
673 if ($arr["owner-id"] == 0) {
674 $arr["owner-id"] = get_contact($arr["owner-link"], 0);
677 if ($arr['guid'] != "") {
678 // Checking if there is already an item with the same guid
679 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
680 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
681 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
683 if (dbm::is_result($r)) {
684 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
689 // Check for hashtags in the body and repair or add hashtag links
690 item_body_set_hashtags($arr);
692 $arr['thr-parent'] = $arr['parent-uri'];
694 if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
695 $conversation = array('item-uri' => $arr['uri'], 'received' => dbm::date());
697 if (isset($arr['thr-parent'])) {
698 if ($arr['thr-parent'] != $arr['uri']) {
699 $conversation['reply-to-uri'] = $arr['thr-parent'];
703 if (isset($arr['conversation-uri'])) {
704 $conversation['conversation-uri'] = $arr['conversation-uri'];
707 if (isset($arr['conversation-href'])) {
708 $conversation['conversation-href'] = $arr['conversation-href'];
711 if (isset($arr['protocol'])) {
712 $conversation['protocol'] = $arr['protocol'];
715 if (isset($arr['source'])) {
716 $conversation['source'] = $arr['source'];
719 dba::insert('conversation', $conversation);
722 unset($arr['conversation-uri']);
723 unset($arr['conversation-href']);
724 unset($arr['protocol']);
725 unset($arr['source']);
727 if ($arr['parent-uri'] === $arr['uri']) {
730 $allow_cid = $arr['allow_cid'];
731 $allow_gid = $arr['allow_gid'];
732 $deny_cid = $arr['deny_cid'];
733 $deny_gid = $arr['deny_gid'];
734 $notify_type = 'wall-new';
737 // find the parent and snarf the item id and ACLs
738 // and anything else we need to inherit
740 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
741 dbesc($arr['parent-uri']),
745 if (dbm::is_result($r)) {
747 // is the new message multi-level threaded?
748 // even though we don't support it now, preserve the info
749 // and re-attach to the conversation parent.
751 if ($r[0]['uri'] != $r[0]['parent-uri']) {
752 $arr['parent-uri'] = $r[0]['parent-uri'];
753 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
754 ORDER BY `id` ASC LIMIT 1",
755 dbesc($r[0]['parent-uri']),
756 dbesc($r[0]['parent-uri']),
760 if (dbm::is_result($z)) {
765 $parent_id = $r[0]['id'];
766 $parent_deleted = $r[0]['deleted'];
767 $allow_cid = $r[0]['allow_cid'];
768 $allow_gid = $r[0]['allow_gid'];
769 $deny_cid = $r[0]['deny_cid'];
770 $deny_gid = $r[0]['deny_gid'];
771 $arr['wall'] = $r[0]['wall'];
772 $notify_type = 'comment-new';
775 * If the parent is private, force privacy for the entire conversation
776 * This differs from the above settings as it subtly allows comments from
777 * email correspondents to be private even if the overall thread is not.
779 if ($r[0]['private']) {
780 $arr['private'] = $r[0]['private'];
784 * Edge case. We host a public forum that was originally posted to privately.
785 * The original author commented, but as this is a comment, the permissions
786 * weren't fixed up so it will still show the comment as private unless we fix it here.
788 if ((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private'])) {
792 // If its a post from myself then tag the thread as "mention"
793 logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
794 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
795 if (dbm::is_result($u)) {
797 $self = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
798 logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
799 if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
800 q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
801 logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
806 * Allow one to see reply tweets from status.net even when
807 * we don't have or can't see the original post.
810 logger('item_store: $force_parent=true, reply converted to top-level post.');
812 $arr['parent-uri'] = $arr['uri'];
815 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
823 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
825 dbesc($arr['network']),
829 if (dbm::is_result($r)) {
830 logger('duplicated item with the same uri found. '.print_r($arr,true));
834 // On Friendica and Diaspora the GUID is unique
835 if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
836 $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
840 if (dbm::is_result($r)) {
841 logger('duplicated item with the same guid found. '.print_r($arr,true));
845 // Check for an existing post with the same content. There seems to be a problem with OStatus.
846 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
848 dbesc($arr['network']),
849 dbesc($arr['created']),
850 intval($arr['contact-id']),
853 if (dbm::is_result($r)) {
854 logger('duplicated item with the same body found. '.print_r($arr,true));
859 // Is this item available in the global items (with uid=0)?
860 if ($arr["uid"] == 0) {
861 $arr["global"] = true;
863 // Set the global flag on all items if this was a global item entry
864 q("UPDATE `item` SET `global` = 1 WHERE `uri` = '%s'", dbesc($arr["uri"]));
866 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
868 $arr["global"] = (dbm::is_result($isglobal) && count($isglobal) > 0);
872 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
875 $private = $arr['private'];
878 $arr["allow_cid"] = $allow_cid;
879 $arr["allow_gid"] = $allow_gid;
880 $arr["deny_cid"] = $deny_cid;
881 $arr["deny_gid"] = $deny_gid;
882 $arr["private"] = $private;
883 $arr["deleted"] = $parent_deleted;
885 // Fill the cache field
886 put_item_in_cache($arr);
889 call_hooks('post_local', $arr);
891 call_hooks('post_remote', $arr);
894 if (x($arr, 'cancel')) {
895 logger('item_store: post cancelled by plugin.');
900 * Check for already added items.
901 * There is a timing issue here that sometimes creates double postings.
902 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
904 if ($arr["uid"] == 0) {
905 $r = qu("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
906 if (dbm::is_result($r)) {
907 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
912 // Store the unescaped version
915 dbm::esc_array($arr, true);
917 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
920 q("START TRANSACTION;");
922 $r = dbq("INSERT INTO `item` (`"
923 . implode("`, `", array_keys($arr))
925 . implode(", ", array_values($arr))
931 // When the item was successfully stored we fetch the ID of the item.
932 if (dbm::is_result($r)) {
933 $r = q("SELECT LAST_INSERT_ID() AS `item-id`");
934 if (dbm::is_result($r)) {
935 $current_post = $r[0]['item-id'];
937 // This shouldn't happen
941 // This can happen - for example - if there are locking timeouts.
944 // Store the data into a spool file so that we can try again later.
946 // At first we restore the Diaspora signature that we removed above.
947 if (isset($encoded_signature)) {
948 $arr['dsprsig'] = $encoded_signature;
951 // Now we store the data in the spool directory
952 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
953 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
955 $spoolpath = get_spoolpath();
956 if ($spoolpath != "") {
957 $spool = $spoolpath.'/'.$file;
958 file_put_contents($spool, json_encode($arr));
959 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
964 if ($current_post == 0) {
965 // This is one of these error messages that never should occur.
966 logger("couldn't find created item - we better quit now.");
971 // How much entries have we created?
972 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
973 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
976 dbesc($arr['network'])
979 if (!dbm::is_result($r)) {
980 // This shouldn't happen, since COUNT always works when the database connection is there.
981 logger("We couldn't count the stored entries. Very strange ...");
986 if ($r[0]["entries"] > 1) {
987 // There are duplicates. We delete our just created entry.
988 logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
990 // Yes, we could do a rollback here - but we are having many users with MyISAM.
991 q("DELETE FROM `item` WHERE `id` = %d", intval($current_post));
994 } elseif ($r[0]["entries"] == 0) {
995 // This really should never happen since we quit earlier if there were problems.
996 logger("Something is terribly wrong. We haven't found our created entry.");
1001 logger('item_store: created item '.$current_post);
1002 item_set_last_item($arr);
1004 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
1005 $parent_id = $current_post;
1009 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
1011 intval($current_post)
1014 $arr['id'] = $current_post;
1015 $arr['parent'] = $parent_id;
1017 // update the commented timestamp on the parent
1018 // Only update "commented" if it is really a comment
1019 if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment")) {
1020 q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
1021 dbesc(datetime_convert()),
1022 dbesc(datetime_convert()),
1026 q("UPDATE `item` SET `changed` = '%s' WHERE `id` = %d",
1027 dbesc(datetime_convert()),
1035 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1036 * We can check for this condition when we decode and encode the stuff again.
1038 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1039 $dsprsig->signature = base64_decode($dsprsig->signature);
1040 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1043 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1044 intval($current_post),
1045 dbesc($dsprsig->signed_text),
1046 dbesc($dsprsig->signature),
1047 dbesc($dsprsig->signer)
1051 $deleted = tag_deliver($arr['uid'], $current_post);
1054 * current post can be deleted if is for a community page and no mention are
1057 if (!$deleted AND !$dontcache) {
1059 $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
1060 if ((dbm::is_result($r)) && (count($r) == 1)) {
1062 call_hooks('post_local_end', $r[0]);
1064 call_hooks('post_remote_end', $r[0]);
1067 logger('item_store: new item not found in DB, id ' . $current_post);
1071 if ($arr['parent-uri'] === $arr['uri']) {
1072 add_thread($current_post);
1074 update_thread($parent_id);
1080 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1081 * This is not perfect - but a workable solution until we found the reason for the problem.
1083 create_tags_from_item($current_post);
1084 create_files_from_item($current_post);
1087 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1088 * It is done after the transaction to avoid dead locks.
1090 if ($arr['last-child']) {
1091 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1093 intval($arr['uid']),
1094 intval($current_post)
1098 if ($arr['parent-uri'] === $arr['uri']) {
1099 add_shadow_thread($current_post);
1101 add_shadow_entry($current_post);
1104 check_item_notification($current_post, $uid);
1107 proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $current_post);
1110 return $current_post;
1114 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1116 * This can be used to filter for inactive contacts.
1117 * Only do this for public postings to avoid privacy problems, since poco data is public.
1118 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1120 * @param array $arr Contains the just posted item record
1122 function item_set_last_item($arr) {
1124 $update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
1126 // Is it a forum? Then we don't care about the rules from above
1127 if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
1128 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1129 intval($arr['contact-id']));
1130 if (dbm::is_result($isforum)) {
1136 q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1137 dbesc($arr['received']),
1138 dbesc($arr['received']),
1139 intval($arr['contact-id'])
1142 // Now do the same for the system wide contacts with uid=0
1143 if (!$arr['private']) {
1144 q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1145 dbesc($arr['received']),
1146 dbesc($arr['received']),
1147 intval($arr['owner-id'])
1150 if ($arr['owner-id'] != $arr['author-id']) {
1151 q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1152 dbesc($arr['received']),
1153 dbesc($arr['received']),
1154 intval($arr['author-id'])
1160 function item_body_set_hashtags(&$item) {
1162 $tags = get_tags($item["body"]);
1165 if (!count($tags)) {
1169 // This sorting is important when there are hashtags that are part of other hashtags
1170 // Otherwise there could be problems with hashtags like #test and #test2
1175 $URLSearchString = "^\[\]";
1177 /// @TODO old-lost code?
1178 // All hashtags should point to the home server
1179 //$item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1180 // "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["body"]);
1182 //$item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1183 // "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["tag"]);
1185 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1186 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1188 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1191 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1193 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1196 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1198 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1201 // Repair recursive urls
1202 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1203 "#$2", $item["body"]);
1205 foreach ($tags as $tag) {
1206 if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
1210 $basetag = str_replace('_',' ',substr($tag,1));
1212 $newtag = '#[url=' . App::get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1214 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1216 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1217 if (strlen($item["tag"])) {
1218 $item["tag"] = ','.$item["tag"];
1220 $item["tag"] = $newtag.$item["tag"];
1224 // Convert back the masked hashtags
1225 $item["body"] = str_replace("#", "#", $item["body"]);
1228 function get_item_guid($id) {
1229 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1230 if (dbm::is_result($r)) {
1231 return $r[0]["guid"];
1233 /// @TODO This else-block can be elimited again
1238 function get_item_id($guid, $uid = 0) {
1244 $uid == local_user();
1247 // Does the given user have this item?
1249 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1250 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1251 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1252 if (dbm::is_result($r)) {
1254 $nick = $r[0]["nickname"];
1258 // Or is it anywhere on the server?
1260 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1261 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1262 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1263 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1264 AND `item`.`private` = 0 AND `item`.`wall` = 1
1265 AND `item`.`guid` = '%s'", dbesc($guid));
1266 if (dbm::is_result($r)) {
1268 $nick = $r[0]["nickname"];
1271 return array("nick" => $nick, "id" => $id);
1275 function get_item_contact($item, $contacts) {
1276 if (! count($contacts) || (! is_array($item))) {
1279 foreach ($contacts as $contact) {
1280 if ($contact['id'] == $item['contact-id']) {
1282 break; // NOTREACHED
1289 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1291 * @param int $item_id
1292 * @return bool true if item was deleted, else false
1294 function tag_deliver($uid, $item_id) {
1300 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1304 if (! dbm::is_result($u)) {
1308 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1309 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1312 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1316 if (! dbm::is_result($i)) {
1322 $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
1325 * Diaspora uses their own hardwired link URL in @-tags
1326 * instead of the one we supply with webfinger
1328 $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
1330 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1332 foreach ($matches as $mtch) {
1333 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1335 logger('tag_deliver: mention found: ' . $mtch[2]);
1341 if (($community_page || $prvgroup) &&
1342 (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
1343 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1345 logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1346 q("DELETE FROM item WHERE id = %d and uid = %d",
1355 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1357 call_hooks('tagged', $arr);
1359 if ((! $community_page) && (! $prvgroup)) {
1364 * tgroup delivery - setup a second delivery chain
1365 * prevent delivery looping - only proceed
1366 * if the message originated elsewhere and is a top-level post
1368 if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
1372 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1373 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1374 intval($u[0]['uid'])
1376 if (! dbm::is_result($c)) {
1380 // also reset all the privacy bits to the forum default permissions
1382 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1384 $forum_mode = (($prvgroup) ? 2 : 1);
1386 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1387 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
1388 intval($forum_mode),
1389 dbesc($c[0]['name']),
1390 dbesc($c[0]['url']),
1391 dbesc($c[0]['thumb']),
1393 dbesc($u[0]['allow_cid']),
1394 dbesc($u[0]['allow_gid']),
1395 dbesc($u[0]['deny_cid']),
1396 dbesc($u[0]['deny_gid']),
1399 update_thread($item_id);
1401 proc_run(PRIORITY_HIGH,'include/notifier.php', 'tgroup', $item_id);
1407 function tgroup_check($uid, $item) {
1411 // check that the message originated elsewhere and is a top-level post
1413 if (($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri'])) {
1417 /// @TODO Encapsulate this or find it encapsulated and replace all occurrances
1418 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1421 if (! dbm::is_result($u)) {
1425 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1426 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1428 $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
1431 * Diaspora uses their own hardwired link URL in @-tags
1432 * instead of the one we supply with webfinger
1434 $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
1436 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1438 foreach ($matches as $mtch) {
1439 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1441 logger('tgroup_check: mention found: ' . $mtch[2]);
1450 /// @TODO Combine both return statements into one
1451 return (($community_page) || ($prvgroup));
1455 * This function returns true if $update has an edited timestamp newer
1456 * than $existing, i.e. $update contains new data which should override
1457 * what's already there. If there is no timestamp yet, the update is
1458 * assumed to be newer. If the update has no timestamp, the existing
1459 * item is assumed to be up-to-date. If the timestamps are equal it
1460 * assumes the update has been seen before and should be ignored.
1462 * @todo fix type-hints (both array)
1464 function edited_timestamp_is_newer ($existing, $update) {
1465 if (!x($existing, 'edited') || !$existing['edited']) {
1468 if (!x($update, 'edited') || !$update['edited']) {
1472 $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
1473 $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
1474 return (strcmp($existing_edited, $update_edited) < 0);
1479 * consume_feed - process atom feed and update anything/everything we might need to update
1481 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1483 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1484 * It is this person's stuff that is going to be updated.
1485 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1486 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1487 * have a contact record.
1488 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1489 * might not) try and subscribe to it.
1490 * $datedir sorts in reverse order
1491 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1492 * imported prior to its children being seen in the stream unless we are certain
1493 * of how the feed is arranged/ordered.
1494 * With $pass = 1, we only pull parent items out of the stream.
1495 * With $pass = 2, we only pull children (comments/likes).
1497 * So running this twice, first with pass 1 and then with pass 2 will do the right
1498 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1499 * model where comments can have sub-threads. That would require some massive sorting
1500 * to get all the feed items into a mostly linear ordering, and might still require
1503 * @todo find proper type-hints
1505 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
1506 if ($contact['network'] === NETWORK_OSTATUS) {
1508 // Test - remove before flight
1509 //$tempfile = tempnam(get_temppath(), "ostatus2");
1510 //file_put_contents($tempfile, $xml);
1511 logger("Consume OStatus messages ", LOGGER_DEBUG);
1512 ostatus::import($xml, $importer, $contact, $hub);
1517 if ($contact['network'] === NETWORK_FEED) {
1519 logger("Consume feeds", LOGGER_DEBUG);
1520 feed_import($xml, $importer, $contact, $hub);
1525 if ($contact['network'] === NETWORK_DFRN) {
1526 logger("Consume DFRN messages", LOGGER_DEBUG);
1528 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
1529 `contact`.`pubkey` AS `cpubkey`,
1530 `contact`.`prvkey` AS `cprvkey`,
1531 `contact`.`thumb` AS `thumb`,
1532 `contact`.`url` as `url`,
1533 `contact`.`name` as `senderName`,
1536 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
1537 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
1538 dbesc($contact["id"]), dbesc($importer["uid"])
1540 if (dbm::is_result($r)) {
1541 logger("Now import the DFRN feed");
1542 dfrn::import($xml, $r[0], true);
1548 /// @TODO type-hint is array
1549 function item_is_remote_self($contact, &$datarray) {
1552 if (!$contact['remote_self']) {
1556 // Prevent the forwarding of posts that are forwarded
1557 if ($datarray["extid"] == NETWORK_DFRN) {
1561 // Prevent to forward already forwarded posts
1562 if ($datarray["app"] == $a->get_hostname()) {
1566 // Only forward posts
1567 if ($datarray["verb"] != ACTIVITY_POST) {
1571 if (($contact['network'] != NETWORK_FEED) AND $datarray['private']) {
1575 $datarray2 = $datarray;
1576 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1577 if ($contact['remote_self'] == 2) {
1578 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1579 intval($contact['uid']));
1580 if (dbm::is_result($r)) {
1581 $datarray['contact-id'] = $r[0]["id"];
1583 $datarray['owner-name'] = $r[0]["name"];
1584 $datarray['owner-link'] = $r[0]["url"];
1585 $datarray['owner-avatar'] = $r[0]["thumb"];
1587 $datarray['author-name'] = $datarray['owner-name'];
1588 $datarray['author-link'] = $datarray['owner-link'];
1589 $datarray['author-avatar'] = $datarray['owner-avatar'];
1592 if ($contact['network'] != NETWORK_FEED) {
1593 $datarray["guid"] = get_guid(32);
1594 unset($datarray["plink"]);
1595 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1596 $datarray["parent-uri"] = $datarray["uri"];
1597 $datarray["extid"] = $contact['network'];
1598 $urlpart = parse_url($datarray2['author-link']);
1599 $datarray["app"] = $urlpart["host"];
1601 $datarray['private'] = 0;
1605 if ($contact['network'] != NETWORK_FEED) {
1606 // Store the original post
1607 $r = item_store($datarray2, false, false);
1608 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1610 $datarray["app"] = "Feed";
1616 /// @TODO find proper type-hints
1617 function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
1618 $url = notags(trim($datarray['author-link']));
1619 $name = notags(trim($datarray['author-name']));
1620 $photo = notags(trim($datarray['author-avatar']));
1622 if (is_object($item)) {
1623 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1624 if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
1625 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1631 if (is_array($contact)) {
1632 if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
1633 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
1634 $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1635 intval(CONTACT_IS_FRIEND),
1636 intval($contact['id']),
1637 intval($importer['uid'])
1640 // send email notification to owner?
1643 // create contact record
1645 $r = q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1646 `blocked`, `readonly`, `pending`, `writable`)
1647 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1648 intval($importer['uid']),
1649 dbesc(datetime_convert()),
1651 dbesc(normalise_link($url)),
1655 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
1656 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
1658 $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
1659 intval($importer['uid']),
1662 if (dbm::is_result($r)) {
1663 $contact_record = $r[0];
1664 update_contact_avatar($photo, $importer["uid"], $contact_record["id"], true);
1667 /// @TODO Encapsulate this into a function/method
1668 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1669 intval($importer['uid'])
1672 if (dbm::is_result($r) AND !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
1674 // create notification
1675 $hash = random_string();
1677 if (is_array($contact_record)) {
1678 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1679 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1680 intval($importer['uid']),
1681 intval($contact_record['id']),
1683 dbesc(datetime_convert())
1687 $def_gid = get_default_group($importer['uid'], $contact_record["network"]);
1689 if (intval($def_gid)) {
1690 group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
1693 if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
1694 in_array($r[0]['page-flags'], array(PAGE_NORMAL))) {
1697 'type' => NOTIFY_INTRO,
1698 'notify_flags' => $r[0]['notify-flags'],
1699 'language' => $r[0]['language'],
1700 'to_name' => $r[0]['username'],
1701 'to_email' => $r[0]['email'],
1702 'uid' => $r[0]['uid'],
1703 'link' => App::get_baseurl() . '/notifications/intro',
1704 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
1705 'source_link' => $contact_record['url'],
1706 'source_photo' => $contact_record['photo'],
1707 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1712 } elseif (dbm::is_result($r) AND in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
1713 $r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
1714 intval($importer['uid']),
1722 function lose_follower($importer, $contact, array $datarray = array(), $item = "") {
1724 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1725 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
1726 intval(CONTACT_IS_SHARING),
1727 intval($contact['id'])
1730 contact_remove($contact['id']);
1734 function lose_sharer($importer, $contact, array $datarray = array(), $item = "") {
1736 if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
1737 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
1738 intval(CONTACT_IS_FOLLOWER),
1739 intval($contact['id'])
1742 contact_remove($contact['id']);
1746 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
1750 if (is_array($importer)) {
1751 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1752 intval($importer['uid'])
1757 * Diaspora has different message-ids in feeds than they do
1758 * through the direct Diaspora protocol. If we try and use
1759 * the feed, we'll get duplicates. So don't.
1761 if ((! dbm::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
1765 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1767 // Use a single verify token, even if multiple hubs
1768 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1770 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1772 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
1774 if (!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
1775 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
1776 dbesc($verify_token),
1777 intval($contact['id'])
1781 post_url($url, $params);
1783 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
1789 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
1791 if (get_config('system','disable_embedded')) {
1797 logger('fix_private_photos: check for photos', LOGGER_DEBUG);
1798 $site = substr(App::get_baseurl(),strpos(App::get_baseurl(),'://'));
1803 $img_start = strpos($orig_body, '[img');
1804 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1805 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1806 while ( ($img_st_close !== false) && ($img_len !== false) ) {
1808 $img_st_close++; // make it point to AFTER the closing bracket
1809 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1811 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
1814 if (stristr($image , $site . '/photo/')) {
1815 // Only embed locally hosted photos
1817 $i = basename($image);
1818 $i = str_replace(array('.jpg', '.png', '.gif'),array('', '',''), $i);
1819 $x = strpos($i, '-');
1822 $res = substr($i, $x + 1);
1823 $i = substr($i, 0, $x);
1824 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1830 if (dbm::is_result($r)) {
1832 * Check to see if we should replace this photo link with an embedded image
1833 * 1. No need to do so if the photo is public
1834 * 2. If there's a contact-id provided, see if they're in the access list
1835 * for the photo. If so, embed it.
1836 * 3. Otherwise, if we have an item, see if the item permissions match the photo
1837 * permissions, regardless of order but first check to see if they're an exact
1838 * match to save some processing overhead.
1840 if (has_permissions($r[0])) {
1842 $recips = enumerate_permissions($r[0]);
1843 if (in_array($cid, $recips)) {
1847 if (compare_permissions($item, $r[0])) {
1853 $data = $r[0]['data'];
1854 $type = $r[0]['type'];
1856 // If a custom width and height were specified, apply before embedding
1857 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1858 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
1860 $width = intval($match[1]);
1861 $height = intval($match[2]);
1863 $ph = new Photo($data, $type);
1864 if ($ph->is_valid()) {
1865 $ph->scaleImage(max($width, $height));
1866 $data = $ph->imageString();
1867 $type = $ph->getType();
1871 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
1872 $image = 'data:' . $type . ';base64,' . base64_encode($data);
1873 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
1879 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1880 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1881 if ($orig_body === false) {
1885 $img_start = strpos($orig_body, '[img');
1886 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1887 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1890 $new_body = $new_body . $orig_body;
1895 /// @TODO type-hint is array
1896 function has_permissions($obj) {
1899 x($obj, 'allow_cid')
1901 x($obj, 'allow_gid')
1910 /// @TODO type-hint is array
1911 function compare_permissions($obj1, $obj2) {
1912 // first part is easy. Check that these are exactly the same.
1913 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1914 && ($obj1['allow_gid'] == $obj2['allow_gid'])
1915 && ($obj1['deny_cid'] == $obj2['deny_cid'])
1916 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1920 // This is harder. Parse all the permissions and compare the resulting set.
1921 $recipients1 = enumerate_permissions($obj1);
1922 $recipients2 = enumerate_permissions($obj2);
1926 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1927 return ($recipients1 == $recipients2);
1930 // returns an array of contact-ids that are allowed to see this object
1931 /// @TODO type-hint is array
1932 function enumerate_permissions($obj) {
1933 $allow_people = expand_acl($obj['allow_cid']);
1934 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
1935 $deny_people = expand_acl($obj['deny_cid']);
1936 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
1937 $recipients = array_unique(array_merge($allow_people, $allow_groups));
1938 $deny = array_unique(array_merge($deny_people, $deny_groups));
1939 $recipients = array_diff($recipients, $deny);
1943 function item_getfeedtags($item) {
1946 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1948 for ($x = 0; $x < $cnt; $x ++) {
1949 if ($matches[1][$x]) {
1950 $ret[$matches[2][$x]] = array('#', $matches[1][$x], $matches[2][$x]);
1955 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1957 for ($x = 0; $x < $cnt; $x ++) {
1958 if ($matches[1][$x]) {
1959 $ret[] = array('@', $matches[1][$x], $matches[2][$x]);
1966 function item_expire($uid, $days, $network = "", $force = false) {
1968 if ((! $uid) || ($days < 1)) {
1973 * $expire_network_only = save your own wall posts
1974 * and just expire conversations started by others
1976 $expire_network_only = get_pconfig($uid,'expire', 'network_only');
1977 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
1979 if ($network != "") {
1980 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1983 * There is an index "uid_network_received" but not "uid_network_created"
1984 * This avoids the creation of another index just for one purpose.
1985 * And it doesn't really matter wether to look at "received" or "created"
1987 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1989 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1992 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1993 WHERE `uid` = %d $range
2001 if (! dbm::is_result($r)) {
2005 $expire_items = get_pconfig($uid, 'expire', 'items');
2006 $expire_items = (($expire_items === false) ? 1 : intval($expire_items)); // default if not set: 1
2008 // Forcing expiring of items - but not notes and marked items
2010 $expire_items = true;
2013 $expire_notes = get_pconfig($uid, 'expire', 'notes');
2014 $expire_notes = (($expire_notes === false) ? 1 : intval($expire_notes)); // default if not set: 1
2016 $expire_starred = get_pconfig($uid, 'expire', 'starred');
2017 $expire_starred = (($expire_starred === false) ? 1 : intval($expire_starred)); // default if not set: 1
2019 $expire_photos = get_pconfig($uid, 'expire', 'photos');
2020 $expire_photos = (($expire_photos === false) ? 0 : intval($expire_photos)); // default if not set: 0
2022 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2024 foreach ($r as $item) {
2026 // don't expire filed items
2028 if (strpos($item['file'],'[') !== false) {
2032 // Only expire posts, not photos and photo comments
2034 if ($expire_photos == 0 && strlen($item['resource-id'])) {
2036 } elseif ($expire_starred == 0 && intval($item['starred'])) {
2038 } elseif ($expire_notes == 0 && $item['type'] == 'note') {
2040 } elseif ($expire_items == 0 && $item['type'] != 'note') {
2044 drop_item($item['id'], false);
2047 proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
2051 /// @TODO type-hint is array
2052 function drop_items($items) {
2055 if (! local_user() && ! remote_user()) {
2059 if (count($items)) {
2060 foreach ($items as $item) {
2061 $owner = drop_item($item,false);
2062 if ($owner && ! $uid)
2067 // multiple threads may have been deleted, send an expire notification
2070 proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
2075 function drop_item($id, $interactive = true) {
2079 // locate item to be deleted
2081 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2085 if (! dbm::is_result($r)) {
2086 if (! $interactive) {
2089 notice( t('Item not found.') . EOL);
2090 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2095 $owner = $item['uid'];
2099 // check if logged in user is either the author or owner of this item
2101 if (is_array($_SESSION['remote'])) {
2102 foreach ($_SESSION['remote'] as $visitor) {
2103 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
2104 $contact_id = $visitor['cid'];
2111 if ((local_user() == $item['uid']) || ($contact_id) || (! $interactive)) {
2113 // Check if we should do HTML-based delete confirmation
2114 if ($_REQUEST['confirm']) {
2115 // <form> can't take arguments in its "action" parameter
2116 // so add any arguments as hidden inputs
2117 $query = explode_querystring($a->query_string);
2119 foreach ($query['args'] as $arg) {
2120 if (strpos($arg, 'confirm=') === false) {
2121 $arg_parts = explode('=', $arg);
2122 $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
2126 return replace_macros(get_markup_template('confirm.tpl'), array(
2128 '$message' => t('Do you really want to delete this item?'),
2129 '$extra_inputs' => $inputs,
2130 '$confirm' => t('Yes'),
2131 '$confirm_url' => $query['base'],
2132 '$confirm_name' => 'confirmed',
2133 '$cancel' => t('Cancel'),
2136 // Now check how the user responded to the confirmation query
2137 if ($_REQUEST['canceled']) {
2138 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2141 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
2144 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
2145 dbesc(datetime_convert()),
2146 dbesc(datetime_convert()),
2149 create_tags_from_item($item['id']);
2150 create_files_from_item($item['id']);
2151 delete_thread($item['id'], $item['parent-uri']);
2153 // clean up categories and tags so they don't end up as orphans
2156 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
2158 foreach ($matches as $mtch) {
2159 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
2165 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
2167 foreach ($matches as $mtch) {
2168 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
2173 * If item is a link to a photo resource, nuke all the associated photos
2174 * (visitors will not have photo resources)
2175 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2176 * generate a resource-id and therefore aren't intimately linked to the item.
2178 if (strlen($item['resource-id'])) {
2179 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2180 dbesc($item['resource-id']),
2181 intval($item['uid'])
2183 // ignore the result
2186 // If item is a link to an event, nuke the event record.
2187 if (intval($item['event-id'])) {
2188 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
2189 intval($item['event-id']),
2190 intval($item['uid'])
2192 // ignore the result
2195 // If item has attachments, drop them
2196 foreach (explode(", ", $item['attach']) as $attach) {
2197 preg_match("|attach/(\d+)|", $attach, $matches);
2198 q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
2199 intval($matches[1]),
2202 // ignore the result
2206 // clean up item_id and sign meta-data tables
2209 /// @TODO Old code - caused very long queries and warning entries in the mysql logfiles:
2211 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
2212 intval($item['id']),
2213 intval($item['uid'])
2216 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
2217 intval($item['id']),
2218 intval($item['uid'])
2222 // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
2224 // Creating list of parents
2225 $r = q("SELECT `id` FROM `item` WHERE `parent` = %d AND `uid` = %d",
2226 intval($item['id']),
2227 intval($item['uid'])
2232 foreach ($r as $row) {
2233 if ($parentid != "") {
2237 $parentid .= $row["id"];
2241 if ($parentid != "") {
2242 $r = q("DELETE FROM `item_id` WHERE `iid` IN (%s)", dbesc($parentid));
2243 $r = q("DELETE FROM `sign` WHERE `iid` IN (%s)", dbesc($parentid));
2246 // If it's the parent of a comment thread, kill all the kids
2247 if ($item['uri'] == $item['parent-uri']) {
2248 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
2249 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2250 dbesc(datetime_convert()),
2251 dbesc(datetime_convert()),
2252 dbesc($item['parent-uri']),
2253 intval($item['uid'])
2255 create_tags_from_itemuri($item['parent-uri'], $item['uid']);
2256 create_files_from_itemuri($item['parent-uri'], $item['uid']);
2257 delete_thread_uri($item['parent-uri'], $item['uid']);
2258 // ignore the result
2260 // ensure that last-child is set in case the comment that had it just got wiped.
2261 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2262 dbesc(datetime_convert()),
2263 dbesc($item['parent-uri']),
2264 intval($item['uid'])
2266 // who is the last child now?
2267 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
2268 dbesc($item['parent-uri']),
2269 intval($item['uid'])
2271 if (dbm::is_result($r)) {
2272 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2278 $drop_id = intval($item['id']);
2280 // send the notification upstream/downstream as the case may be
2282 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
2284 if (! $interactive) {
2287 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2290 if (! $interactive) {
2293 notice( t('Permission denied.') . EOL);
2294 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
2301 function first_post_date($uid, $wall = false) {
2302 $r = q("SELECT `id`, `created` FROM `item`
2303 WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
2305 ORDER BY `created` ASC LIMIT 1",
2307 intval($wall ? 1 : 0)
2309 if (dbm::is_result($r)) {
2310 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
2311 return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
2316 /* modified posted_dates() {below} to arrange the list in years */
2317 function list_post_dates($uid, $wall) {
2318 $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
2320 $dthen = first_post_date($uid, $wall);
2325 // Set the start and end date to the beginning of the month
2326 $dnow = substr($dnow, 0, 8) . '01';
2327 $dthen = substr($dthen, 0, 8) . '01';
2332 * Starting with the current month, get the first and last days of every
2333 * month down to and including the month of the first post
2335 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2336 $dyear = intval(substr($dnow, 0, 4));
2337 $dstart = substr($dnow, 0, 8) . '01';
2338 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2339 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2340 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2341 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
2342 if (!$ret[$dyear]) {
2343 $ret[$dyear] = array();
2345 $ret[$dyear][] = array($str, $end_month, $start_month);
2346 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2351 function posted_dates($uid, $wall) {
2352 $dnow = datetime_convert('', date_default_timezone_get(), 'now', 'Y-m-d');
2354 $dthen = first_post_date($uid, $wall);
2359 // Set the start and end date to the beginning of the month
2360 $dnow = substr($dnow, 0, 8) . '01';
2361 $dthen = substr($dthen, 0, 8) . '01';
2365 * Starting with the current month, get the first and last days of every
2366 * month down to and including the month of the first post
2368 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
2369 $dstart = substr($dnow, 0, 8) . '01';
2370 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
2371 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
2372 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
2373 $str = day_translate(datetime_convert('', '', $dnow, 'F Y'));
2374 $ret[] = array($str, $end_month, $start_month);
2375 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
2381 function posted_date_widget($url, $uid, $wall) {
2384 if (! feature_enabled($uid, 'archives')) {
2388 // For former Facebook folks that left because of "timeline"
2390 * @TODO old-lost code?
2391 if ($wall && intval(get_pconfig($uid, 'system', 'no_wall_archive_widget')))
2395 $visible_years = get_pconfig($uid,'system','archive_visible_years');
2396 if (! $visible_years) {
2400 $ret = list_post_dates($uid, $wall);
2402 if (! dbm::is_result($ret)) {
2406 $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
2407 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
2409 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
2410 '$title' => t('Archives'),
2411 '$size' => $visible_years,
2412 '$cutoff_year' => $cutoff_year,
2413 '$cutoff' => $cutoff,
2416 '$showmore' => t('show more')