]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
18606e16902e2bb2d0dd3f25b15ce81e343f3d56
[friendica.git] / src / Model / Item.php
1 <?php
2
3 /**
4  * @file src/Model/Item.php
5  */
6
7 namespace Friendica\Model;
8
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Worker;
13 use Friendica\Core\System;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Database\DBM;
21 use Friendica\Protocol\OStatus;
22 use dba;
23 use Text_LanguageDetect;
24
25 require_once 'include/tags.php';
26 require_once 'include/threads.php';
27 require_once 'include/items.php';
28 require_once 'include/text.php';
29
30 class Item
31 {
32         /**
33          * @brief Update existing item entries
34          *
35          * @param array $fields The fields that are to be changed
36          * @param array $condition The condition for finding the item entries
37          *
38          * In the future we may have to change permissions as well.
39          * Then we had to add the user id as third parameter.
40          *
41          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
42          *
43          * @return integer|boolean number of affected rows - or "false" if there was an error
44          */
45         public static function update(array $fields, array $condition)
46         {
47                 if (empty($condition) || empty($fields)) {
48                         return false;
49                 }
50
51                 $success = dba::update('item', $fields, $condition);
52
53                 if (!$success) {
54                         return false;
55                 }
56
57                 $rows = dba::affected_rows();
58
59                 // We cannot simply expand the condition to check for origin entries
60                 // The condition needn't to be a simple array but could be a complex condition.
61                 $items = dba::select('item', ['id', 'origin'], $condition);
62                 while ($item = dba::fetch($items)) {
63                         // We only need to notfiy others when it is an original entry from us
64                         if (!$item['origin']) {
65                                 continue;
66                         }
67
68                         create_tags_from_item($item['id']);
69                         Term::createFromItem($item['id']);
70                         update_thread($item['id']);
71
72                         Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
73                 }
74
75                 return $rows;
76         }
77
78         /**
79          * @brief Delete an item and notify others about it - if it was ours
80          *
81          * @param integer $item_id Item ID that should be delete
82          *
83          * @return $boolean success
84          */
85         public static function delete($item_id, $priority = PRIORITY_HIGH)
86         {
87                 // locate item to be deleted
88                 $fields = ['id', 'uid', 'parent', 'parent-uri', 'origin', 'deleted', 'file', 'resource-id', 'event-id', 'attach'];
89                 $item = dba::selectFirst('item', $fields, ['id' => $item_id]);
90                 if (!DBM::is_result($item)) {
91                         return false;
92                 }
93
94                 if ($item['deleted']) {
95                         return false;
96                 }
97
98                 $parent = dba::selectFirst('item', ['origin'], ['id' => $item['parent']]);
99                 if (!DBM::is_result($parent)) {
100                         $parent = ['origin' => false];
101                 }
102
103                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
104
105                 // clean up categories and tags so they don't end up as orphans
106
107                 $matches = false;
108                 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
109                 if ($cnt) {
110                         foreach ($matches as $mtch) {
111                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
112                         }
113                 }
114
115                 $matches = false;
116
117                 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
118                 if ($cnt) {
119                         foreach ($matches as $mtch) {
120                                 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
121                         }
122                 }
123
124                 /*
125                  * If item is a link to a photo resource, nuke all the associated photos
126                  * (visitors will not have photo resources)
127                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
128                  * generate a resource-id and therefore aren't intimately linked to the item.
129                  */
130                 if (strlen($item['resource-id'])) {
131                         dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
132                 }
133
134                 // If item is a link to an event, nuke the event record.
135                 if (intval($item['event-id'])) {
136                         dba::delete('event', ['id' => $item['event-id'], 'uid' => $item['uid']]);
137                 }
138
139                 // If item has attachments, drop them
140                 foreach (explode(", ", $item['attach']) as $attach) {
141                         preg_match("|attach/(\d+)|", $attach, $matches);
142                         dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
143                 }
144
145                 // Set the item to "deleted"
146                 dba::update('item', ['deleted' => true, 'title' => '', 'body' => '',
147                                         'edited' => datetime_convert(), 'changed' => datetime_convert()],
148                                 ['id' => $item['id']]);
149
150                 create_tags_from_item($item['id']);
151                 Term::createFromItem($item['id']);
152                 delete_thread($item['id'], $item['parent-uri']);
153
154                 // If it's the parent of a comment thread, kill all the kids
155                 if ($item['id'] == $item['parent']) {
156                         $items = dba::select('item', ['id'], ['parent' => $item['parent']]);
157                         while ($row = dba::fetch($items)) {
158                                 self::delete($row['id'], $priority);
159                         }
160                 }
161
162                 // send the notification upstream/downstream
163                 if ($item['origin'] || $parent['origin']) {
164                         Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
165                 }
166
167                 return true;
168         }
169
170         public static function insert($arr, $force_parent = false, $notify = false, $dontcache = false)
171         {
172                 $a = get_app();
173
174                 // If it is a posting where users should get notifications, then define it as wall posting
175                 if ($notify) {
176                         $arr['wall'] = 1;
177                         $arr['type'] = 'wall';
178                         $arr['origin'] = 1;
179                         $arr['network'] = NETWORK_DFRN;
180                         $arr['protocol'] = PROTOCOL_DFRN;
181
182                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
183                         // In difference to the call to "self::guidFromUri" several lines below we add the hash of our own host.
184                         // This is done because our host is the original creator of the post.
185                         if (!isset($arr['guid'])) {
186                                 if (isset($arr['plink'])) {
187                                         $arr['guid'] = self::guidFromUri($arr['plink'], $a->get_hostname());
188                                 } elseif (isset($arr['uri'])) {
189                                         $arr['guid'] = self::guidFromUri($arr['uri'], $a->get_hostname());
190                                 }
191                         }
192                 } else {
193                         $arr['network'] = trim(defaults($arr, 'network', NETWORK_PHANTOM));
194                 }
195
196                 if ($notify) {
197                         $guid_prefix = "";
198                 } elseif ((trim($arr['guid']) == "") && (trim($arr['plink']) != "")) {
199                         $arr['guid'] = self::guidFromUri($arr['plink']);
200                 } elseif ((trim($arr['guid']) == "") && (trim($arr['uri']) != "")) {
201                         $arr['guid'] = self::guidFromUri($arr['uri']);
202                 } else {
203                         $parsed = parse_url($arr["author-link"]);
204                         $guid_prefix = hash("crc32", $parsed["host"]);
205                 }
206
207                 $arr['guid']          = ((x($arr, 'guid'))          ? notags(trim($arr['guid']))          : get_guid(32, $guid_prefix));
208                 $arr['uri']           = ((x($arr, 'uri'))           ? notags(trim($arr['uri']))           : item_new_uri($a->get_hostname(), $uid, $arr['guid']));
209
210                 // Store conversation data
211                 $arr = Conversation::insert($arr);
212
213                 /*
214                  * If a Diaspora signature structure was passed in, pull it out of the
215                  * item array and set it aside for later storage.
216                  */
217
218                 $dsprsig = null;
219                 if (x($arr, 'dsprsig')) {
220                         $encoded_signature = $arr['dsprsig'];
221                         $dsprsig = json_decode(base64_decode($arr['dsprsig']));
222                         unset($arr['dsprsig']);
223                 }
224
225                 // Converting the plink
226                 /// @TODO Check if this is really still needed
227                 if ($arr['network'] == NETWORK_OSTATUS) {
228                         if (isset($arr['plink'])) {
229                                 $arr['plink'] = OStatus::convertHref($arr['plink']);
230                         } elseif (isset($arr['uri'])) {
231                                 $arr['plink'] = OStatus::convertHref($arr['uri']);
232                         }
233                 }
234
235                 if (x($arr, 'gravity')) {
236                         $arr['gravity'] = intval($arr['gravity']);
237                 } elseif ($arr['parent-uri'] === $arr['uri']) {
238                         $arr['gravity'] = 0;
239                 } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
240                         $arr['gravity'] = 6;
241                 } else {
242                         $arr['gravity'] = 6;   // extensible catchall
243                 }
244
245                 if (!x($arr, 'type')) {
246                         $arr['type']      = 'remote';
247                 }
248
249                 $uid = intval($arr['uid']);
250
251                 // check for create date and expire time
252                 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
253
254                 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
255                 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
256                         $expire_interval = $user['expire'];
257                 }
258
259                 if (($expire_interval > 0) && !empty($arr['created'])) {
260                         $expire_date = time() - ($expire_interval * 86400);
261                         $created_date = strtotime($arr['created']);
262                         if ($created_date < $expire_date) {
263                                 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
264                                 return 0;
265                         }
266                 }
267
268                 /*
269                  * Do we already have this item?
270                  * We have to check several networks since Friendica posts could be repeated
271                  * via OStatus (maybe Diasporsa as well)
272                  */
273                 if (in_array($arr['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
274                         $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s')  LIMIT 1",
275                                         dbesc(trim($arr['uri'])),
276                                         intval($uid),
277                                         dbesc(NETWORK_DIASPORA),
278                                         dbesc(NETWORK_DFRN),
279                                         dbesc(NETWORK_OSTATUS)
280                                 );
281                         if (DBM::is_result($r)) {
282                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
283                                 if ($uid != 0) {
284                                         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']);
285                                 }
286
287                                 return $r[0]["id"];
288                         }
289                 }
290
291                 self::addLanguageInPostopts($arr);
292
293                 $arr['wall']          = ((x($arr, 'wall'))          ? intval($arr['wall'])                : 0);
294                 $arr['extid']         = ((x($arr, 'extid'))         ? notags(trim($arr['extid']))         : '');
295                 $arr['author-name']   = ((x($arr, 'author-name'))   ? trim($arr['author-name'])   : '');
296                 $arr['author-link']   = ((x($arr, 'author-link'))   ? notags(trim($arr['author-link']))   : '');
297                 $arr['author-avatar'] = ((x($arr, 'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
298                 $arr['owner-name']    = ((x($arr, 'owner-name'))    ? trim($arr['owner-name'])    : '');
299                 $arr['owner-link']    = ((x($arr, 'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
300                 $arr['owner-avatar']  = ((x($arr, 'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
301                 $arr['received']      = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
302                 $arr['created']       = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : $arr['received']);
303                 $arr['edited']        = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : $arr['created']);
304                 $arr['changed']       = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : $arr['created']);
305                 $arr['commented']     = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : $arr['created']);
306                 $arr['title']         = ((x($arr, 'title'))         ? trim($arr['title'])         : '');
307                 $arr['location']      = ((x($arr, 'location'))      ? trim($arr['location'])      : '');
308                 $arr['coord']         = ((x($arr, 'coord'))         ? notags(trim($arr['coord']))         : '');
309                 $arr['visible']       = ((x($arr, 'visible') !== false) ? intval($arr['visible'])         : 1);
310                 $arr['deleted']       = 0;
311                 $arr['parent-uri']    = ((x($arr, 'parent-uri'))    ? notags(trim($arr['parent-uri']))    : $arr['uri']);
312                 $arr['verb']          = ((x($arr, 'verb'))          ? notags(trim($arr['verb']))          : '');
313                 $arr['object-type']   = ((x($arr, 'object-type'))   ? notags(trim($arr['object-type']))   : '');
314                 $arr['object']        = ((x($arr, 'object'))        ? trim($arr['object'])                : '');
315                 $arr['target-type']   = ((x($arr, 'target-type'))   ? notags(trim($arr['target-type']))   : '');
316                 $arr['target']        = ((x($arr, 'target'))        ? trim($arr['target'])                : '');
317                 $arr['plink']         = ((x($arr, 'plink'))         ? notags(trim($arr['plink']))         : '');
318                 $arr['allow_cid']     = ((x($arr, 'allow_cid'))     ? trim($arr['allow_cid'])             : '');
319                 $arr['allow_gid']     = ((x($arr, 'allow_gid'))     ? trim($arr['allow_gid'])             : '');
320                 $arr['deny_cid']      = ((x($arr, 'deny_cid'))      ? trim($arr['deny_cid'])              : '');
321                 $arr['deny_gid']      = ((x($arr, 'deny_gid'))      ? trim($arr['deny_gid'])              : '');
322                 $arr['private']       = ((x($arr, 'private'))       ? intval($arr['private'])             : 0);
323                 $arr['bookmark']      = ((x($arr, 'bookmark'))      ? intval($arr['bookmark'])            : 0);
324                 $arr['body']          = ((x($arr, 'body'))          ? trim($arr['body'])                  : '');
325                 $arr['tag']           = ((x($arr, 'tag'))           ? notags(trim($arr['tag']))           : '');
326                 $arr['attach']        = ((x($arr, 'attach'))        ? notags(trim($arr['attach']))        : '');
327                 $arr['app']           = ((x($arr, 'app'))           ? notags(trim($arr['app']))           : '');
328                 $arr['origin']        = ((x($arr, 'origin'))        ? intval($arr['origin'])              : 0);
329                 $arr['postopts']      = ((x($arr, 'postopts'))      ? trim($arr['postopts'])              : '');
330                 $arr['resource-id']   = ((x($arr, 'resource-id'))   ? trim($arr['resource-id'])           : '');
331                 $arr['event-id']      = ((x($arr, 'event-id'))      ? intval($arr['event-id'])            : 0);
332                 $arr['inform']        = ((x($arr, 'inform'))        ? trim($arr['inform'])                : '');
333                 $arr['file']          = ((x($arr, 'file'))          ? trim($arr['file'])                  : '');
334
335                 // When there is no content then we don't post it
336                 if ($arr['body'].$arr['title'] == '') {
337                         return 0;
338                 }
339
340                 // Items cannot be stored before they happen ...
341                 if ($arr['created'] > datetime_convert()) {
342                         $arr['created'] = datetime_convert();
343                 }
344
345                 // We haven't invented time travel by now.
346                 if ($arr['edited'] > datetime_convert()) {
347                         $arr['edited'] = datetime_convert();
348                 }
349
350                 if (($arr['author-link'] == "") && ($arr['owner-link'] == "")) {
351                         logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
352                 }
353
354                 if ($arr['plink'] == "") {
355                         $arr['plink'] = System::baseUrl() . '/display/' . urlencode($arr['guid']);
356                 }
357
358                 if ($arr['network'] == NETWORK_PHANTOM) {
359                         $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
360                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
361                                 dbesc(normalise_link($arr['author-link'])),
362                                 intval($arr['uid'])
363                         );
364
365                         if (!DBM::is_result($r)) {
366                                 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
367                                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
368                                         dbesc(normalise_link($arr['author-link']))
369                                 );
370                         }
371
372                         if (!DBM::is_result($r)) {
373                                 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
374                                         intval($arr['contact-id']),
375                                         intval($arr['uid'])
376                                 );
377                         }
378
379                         if (DBM::is_result($r)) {
380                                 $arr['network'] = $r[0]["network"];
381                         }
382
383                         // Fallback to friendica (why is it empty in some cases?)
384                         if ($arr['network'] == "") {
385                                 $arr['network'] = NETWORK_DFRN;
386                         }
387
388                         logger("Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
389                 }
390
391                 // The contact-id should be set before "self::insert" was called - but there seems to be some issues
392                 if ($arr["contact-id"] == 0) {
393                         /*
394                          * First we are looking for a suitable contact that matches with the author of the post
395                          * This is done only for comments (See below explanation at "gcontact-id")
396                          */
397                         if ($arr['parent-uri'] != $arr['uri']) {
398                                 $arr["contact-id"] = Contact::getIdForURL($arr['author-link'], $uid);
399                         }
400
401                         // If not present then maybe the owner was found
402                         if ($arr["contact-id"] == 0) {
403                                 $arr["contact-id"] = Contact::getIdForURL($arr['owner-link'], $uid);
404                         }
405
406                         // Still missing? Then use the "self" contact of the current user
407                         if ($arr["contact-id"] == 0) {
408                                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
409
410                                 if (DBM::is_result($r)) {
411                                         $arr["contact-id"] = $r[0]["id"];
412                                 }
413                         }
414
415                         logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
416                 }
417
418                 if (!x($arr, "gcontact-id")) {
419                         /*
420                          * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
421                          * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
422                          * On comments the author is the better choice.
423                          */
424                         if ($arr['parent-uri'] === $arr['uri']) {
425                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['owner-link'], "network" => $arr['network'],
426                                                                          "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']]);
427                         } else {
428                                 $arr["gcontact-id"] = GContact::getId(["url" => $arr['author-link'], "network" => $arr['network'],
429                                                                          "photo" => $arr['author-avatar'], "name" => $arr['author-name']]);
430                         }
431                 }
432
433                 if ($arr["author-id"] == 0) {
434                         $arr["author-id"] = Contact::getIdForURL($arr["author-link"], 0);
435                 }
436
437                 if (Contact::isBlocked($arr["author-id"])) {
438                         logger('Contact '.$arr["author-id"].' is blocked, item '.$arr["uri"].' will not be stored');
439                         return 0;
440                 }
441
442                 if ($arr["owner-id"] == 0) {
443                         $arr["owner-id"] = Contact::getIdForURL($arr["owner-link"], 0);
444                 }
445
446                 if (Contact::isBlocked($arr["owner-id"])) {
447                         logger('Contact '.$arr["owner-id"].' is blocked, item '.$arr["uri"].' will not be stored');
448                         return 0;
449                 }
450
451                 if ($arr['guid'] != "") {
452                         // Checking if there is already an item with the same guid
453                         logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
454                         $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
455                                 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
456
457                         if (DBM::is_result($r)) {
458                                 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
459                                 return 0;
460                         }
461                 }
462
463                 // Check for hashtags in the body and repair or add hashtag links
464                 self::setHashtags($arr);
465
466                 $arr['thr-parent'] = $arr['parent-uri'];
467
468                 if ($arr['parent-uri'] === $arr['uri']) {
469                         $parent_id = 0;
470                         $parent_deleted = 0;
471                         $allow_cid = $arr['allow_cid'];
472                         $allow_gid = $arr['allow_gid'];
473                         $deny_cid  = $arr['deny_cid'];
474                         $deny_gid  = $arr['deny_gid'];
475                         $notify_type = 'wall-new';
476                 } else {
477
478                         // find the parent and snarf the item id and ACLs
479                         // and anything else we need to inherit
480
481                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
482                                 dbesc($arr['parent-uri']),
483                                 intval($arr['uid'])
484                         );
485
486                         if (DBM::is_result($r)) {
487
488                                 // is the new message multi-level threaded?
489                                 // even though we don't support it now, preserve the info
490                                 // and re-attach to the conversation parent.
491
492                                 if ($r[0]['uri'] != $r[0]['parent-uri']) {
493                                         $arr['parent-uri'] = $r[0]['parent-uri'];
494                                         $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
495                                                 ORDER BY `id` ASC LIMIT 1",
496                                                 dbesc($r[0]['parent-uri']),
497                                                 dbesc($r[0]['parent-uri']),
498                                                 intval($arr['uid'])
499                                         );
500
501                                         if (DBM::is_result($z)) {
502                                                 $r = $z;
503                                         }
504                                 }
505
506                                 $parent_id      = $r[0]['id'];
507                                 $parent_deleted = $r[0]['deleted'];
508                                 $allow_cid      = $r[0]['allow_cid'];
509                                 $allow_gid      = $r[0]['allow_gid'];
510                                 $deny_cid       = $r[0]['deny_cid'];
511                                 $deny_gid       = $r[0]['deny_gid'];
512                                 $arr['wall']    = $r[0]['wall'];
513                                 $notify_type    = 'comment-new';
514
515                                 /*
516                                  * If the parent is private, force privacy for the entire conversation
517                                  * This differs from the above settings as it subtly allows comments from
518                                  * email correspondents to be private even if the overall thread is not.
519                                  */
520                                 if ($r[0]['private']) {
521                                         $arr['private'] = $r[0]['private'];
522                                 }
523
524                                 /*
525                                  * Edge case. We host a public forum that was originally posted to privately.
526                                  * The original author commented, but as this is a comment, the permissions
527                                  * weren't fixed up so it will still show the comment as private unless we fix it here.
528                                  */
529                                 if ((intval($r[0]['forum_mode']) == 1) && $r[0]['private']) {
530                                         $arr['private'] = 0;
531                                 }
532
533                                 // If its a post from myself then tag the thread as "mention"
534                                 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
535                                 $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
536                                 if (DBM::is_result($u)) {
537                                         $self = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
538                                         logger("'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
539                                         if ((normalise_link($arr['author-link']) == $self) || (normalise_link($arr['owner-link']) == $self)) {
540                                                 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
541                                                 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
542                                         }
543                                 }
544                         } else {
545                                 /*
546                                  * Allow one to see reply tweets from status.net even when
547                                  * we don't have or can't see the original post.
548                                  */
549                                 if ($force_parent) {
550                                         logger('$force_parent=true, reply converted to top-level post.');
551                                         $parent_id = 0;
552                                         $arr['parent-uri'] = $arr['uri'];
553                                         $arr['gravity'] = 0;
554                                 } else {
555                                         logger('item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
556                                         return 0;
557                                 }
558
559                                 $parent_deleted = 0;
560                         }
561                 }
562
563                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
564                         dbesc($arr['uri']),
565                         dbesc($arr['network']),
566                         dbesc(NETWORK_DFRN),
567                         intval($arr['uid'])
568                 );
569                 if (DBM::is_result($r)) {
570                         logger('duplicated item with the same uri found. '.print_r($arr,true));
571                         return 0;
572                 }
573
574                 // On Friendica and Diaspora the GUID is unique
575                 if (in_array($arr['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
576                         $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
577                                 dbesc($arr['guid']),
578                                 intval($arr['uid'])
579                         );
580                         if (DBM::is_result($r)) {
581                                 logger('duplicated item with the same guid found. '.print_r($arr,true));
582                                 return 0;
583                         }
584                 } else {
585                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
586                         $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
587                                 dbesc($arr['body']),
588                                 dbesc($arr['network']),
589                                 dbesc($arr['created']),
590                                 intval($arr['contact-id']),
591                                 intval($arr['uid'])
592                         );
593                         if (DBM::is_result($r)) {
594                                 logger('duplicated item with the same body found. '.print_r($arr,true));
595                                 return 0;
596                         }
597                 }
598
599                 // Is this item available in the global items (with uid=0)?
600                 if ($arr["uid"] == 0) {
601                         $arr["global"] = true;
602
603                         // Set the global flag on all items if this was a global item entry
604                         dba::update('item', ['global' => true], ['uri' => $arr["uri"]]);
605                 } else {
606                         $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
607
608                         $arr["global"] = (DBM::is_result($isglobal) && count($isglobal) > 0);
609                 }
610
611                 // ACL settings
612                 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
613                         $private = 1;
614                 } else {
615                         $private = $arr['private'];
616                 }
617
618                 $arr["allow_cid"] = $allow_cid;
619                 $arr["allow_gid"] = $allow_gid;
620                 $arr["deny_cid"] = $deny_cid;
621                 $arr["deny_gid"] = $deny_gid;
622                 $arr["private"] = $private;
623                 $arr["deleted"] = $parent_deleted;
624
625                 // Fill the cache field
626                 put_item_in_cache($arr);
627
628                 if ($notify) {
629                         Addon::callHooks('post_local', $arr);
630                 } else {
631                         Addon::callHooks('post_remote', $arr);
632                 }
633
634                 // This array field is used to trigger some automatic reactions
635                 // It is mainly used in the "post_local" hook.
636                 unset($arr['api_source']);
637
638                 if (x($arr, 'cancel')) {
639                         logger('post cancelled by addon.');
640                         return 0;
641                 }
642
643                 /*
644                  * Check for already added items.
645                  * There is a timing issue here that sometimes creates double postings.
646                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
647                  */
648                 if ($arr["uid"] == 0) {
649                         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
650                         if (DBM::is_result($r)) {
651                                 logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
652                                 return 0;
653                         }
654                 }
655
656                 logger('' . print_r($arr,true), LOGGER_DATA);
657
658                 dba::transaction();
659                 $r = dba::insert('item', $arr);
660
661                 // When the item was successfully stored we fetch the ID of the item.
662                 if (DBM::is_result($r)) {
663                         $current_post = dba::lastInsertId();
664                 } else {
665                         // This can happen - for example - if there are locking timeouts.
666                         dba::rollback();
667
668                         // Store the data into a spool file so that we can try again later.
669
670                         // At first we restore the Diaspora signature that we removed above.
671                         if (isset($encoded_signature)) {
672                                 $arr['dsprsig'] = $encoded_signature;
673                         }
674
675                         // Now we store the data in the spool directory
676                         // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
677                         $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
678
679                         $spoolpath = get_spoolpath();
680                         if ($spoolpath != "") {
681                                 $spool = $spoolpath.'/'.$file;
682                                 file_put_contents($spool, json_encode($arr));
683                                 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
684                         }
685                         return 0;
686                 }
687
688                 if ($current_post == 0) {
689                         // This is one of these error messages that never should occur.
690                         logger("couldn't find created item - we better quit now.");
691                         dba::rollback();
692                         return 0;
693                 }
694
695                 // How much entries have we created?
696                 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
697                 $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
698                         dbesc($arr['uri']),
699                         intval($arr['uid']),
700                         dbesc($arr['network'])
701                 );
702
703                 if (!DBM::is_result($r)) {
704                         // This shouldn't happen, since COUNT always works when the database connection is there.
705                         logger("We couldn't count the stored entries. Very strange ...");
706                         dba::rollback();
707                         return 0;
708                 }
709
710                 if ($r[0]["entries"] > 1) {
711                         // There are duplicates. We delete our just created entry.
712                         logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
713
714                         // Yes, we could do a rollback here - but we are having many users with MyISAM.
715                         dba::delete('item', ['id' => $current_post]);
716                         dba::commit();
717                         return 0;
718                 } elseif ($r[0]["entries"] == 0) {
719                         // This really should never happen since we quit earlier if there were problems.
720                         logger("Something is terribly wrong. We haven't found our created entry.");
721                         dba::rollback();
722                         return 0;
723                 }
724
725                 logger('created item '.$current_post);
726                 self::updateContact($arr);
727
728                 if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
729                         $parent_id = $current_post;
730                 }
731
732                 // Set parent id
733                 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
734
735                 $arr['id'] = $current_post;
736                 $arr['parent'] = $parent_id;
737
738                 // update the commented timestamp on the parent
739                 // Only update "commented" if it is really a comment
740                 if (($arr['verb'] == ACTIVITY_POST) || !Config::get("system", "like_no_comment")) {
741                         dba::update('item', ['commented' => datetime_convert(), 'changed' => datetime_convert()], ['id' => $parent_id]);
742                 } else {
743                         dba::update('item', ['changed' => datetime_convert()], ['id' => $parent_id]);
744                 }
745
746                 if ($dsprsig) {
747                         /*
748                          * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
749                          * We can check for this condition when we decode and encode the stuff again.
750                          */
751                         if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
752                                 $dsprsig->signature = base64_decode($dsprsig->signature);
753                                 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
754                         }
755
756                         dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
757                                                 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
758                 }
759
760                 $deleted = self::tagDeliver($arr['uid'], $current_post);
761
762                 /*
763                  * current post can be deleted if is for a community page and no mention are
764                  * in it.
765                  */
766                 if (!$deleted && !$dontcache) {
767                         $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
768                         if (DBM::is_result($r) && (count($r) == 1)) {
769                                 if ($notify) {
770                                         Addon::callHooks('post_local_end', $r[0]);
771                                 } else {
772                                         Addon::callHooks('post_remote_end', $r[0]);
773                                 }
774                         } else {
775                                 logger('new item not found in DB, id ' . $current_post);
776                         }
777                 }
778
779                 if ($arr['parent-uri'] === $arr['uri']) {
780                         add_thread($current_post);
781                 } else {
782                         update_thread($parent_id);
783                 }
784
785                 dba::commit();
786
787                 /*
788                  * Due to deadlock issues with the "term" table we are doing these steps after the commit.
789                  * This is not perfect - but a workable solution until we found the reason for the problem.
790                  */
791                 create_tags_from_item($current_post);
792                 Term::createFromItem($current_post);
793
794                 if ($arr['parent-uri'] === $arr['uri']) {
795                         self::addShadow($current_post);
796                 } else {
797                         self::addShadowPost($current_post);
798                 }
799
800                 check_user_notification($current_post);
801
802                 if ($notify) {
803                         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
804                 }
805
806                 return $current_post;
807         }
808
809         /**
810          * @brief Add a shadow entry for a given item id that is a thread starter
811          *
812          * We store every public item entry additionally with the user id "0".
813          * This is used for the community page and for the search.
814          * It is planned that in the future we will store public item entries only once.
815          *
816          * @param integer $itemid Item ID that should be added
817          */
818         public static function addShadow($itemid)
819         {
820                 $fields = ['uid', 'wall', 'private', 'moderated', 'visible', 'contact-id', 'deleted', 'network', 'author-id', 'owner-id'];
821                 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
822                 $item = dba::selectFirst('item', $fields, $condition);
823
824                 if (!DBM::is_result($item)) {
825                         return;
826                 }
827
828                 // is it already a copy?
829                 if (($itemid == 0) || ($item['uid'] == 0)) {
830                         return;
831                 }
832
833                 // Is it a visible public post?
834                 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
835                         return;
836                 }
837
838                 // is it an entry from a connector? Only add an entry for natively connected networks
839                 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
840                         return;
841                 }
842
843                 // Is the public contact configured as hidden?
844                 if (Contact::isHidden($item["owner-id"]) || Contact::isHidden($item["author-id"])) {
845                         return;
846                 }
847
848                 // Only do these checks if the post isn't a wall post
849                 if (!$item["wall"]) {
850                         // Check, if hide-friends is activated - then don't do a shadow entry
851                         if (dba::exists('profile', ['is-default' => true, 'uid' => $item['uid'], 'hide-friends' => true])) {
852                                 return;
853                         }
854
855                         // Check if the contact is hidden or blocked
856                         if (!dba::exists('contact', ['hidden' => false, 'blocked' => false, 'id' => $item['contact-id']])) {
857                                 return;
858                         }
859                 }
860
861                 // Only add a shadow, if the profile isn't hidden
862                 if (dba::exists('user', ['uid' => $item['uid'], 'hidewall' => true])) {
863                         return;
864                 }
865
866                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
867
868                 if (DBM::is_result($item) && ($item["allow_cid"] == '')  && ($item["allow_gid"] == '') &&
869                         ($item["deny_cid"] == '') && ($item["deny_gid"] == '')) {
870
871                         if (!dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
872                                 // Preparing public shadow (removing user specific data)
873                                 unset($item['id']);
874                                 $item['uid'] = 0;
875                                 $item['origin'] = 0;
876                                 $item['wall'] = 0;
877                                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
878
879                                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
880                                         $item['type'] = 'remote-comment';
881                                 } elseif ($item['type'] == 'wall') {
882                                         $item['type'] = 'remote';
883                                 }
884
885                                 $public_shadow = self::insert($item, false, false, true);
886
887                                 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
888                         }
889                 }
890         }
891
892         /**
893          * @brief Add a shadow entry for a given item id that is a comment
894          *
895          * This function does the same like the function above - but for comments
896          *
897          * @param integer $itemid Item ID that should be added
898          */
899         public static function addShadowPost($itemid)
900         {
901                 $item = dba::selectFirst('item', [], ['id' => $itemid]);
902                 if (!DBM::is_result($item)) {
903                         return;
904                 }
905
906                 // Is it a toplevel post?
907                 if ($item['id'] == $item['parent']) {
908                         self::addShadow($itemid);
909                         return;
910                 }
911
912                 // Is this a shadow entry?
913                 if ($item['uid'] == 0)
914                         return;
915
916                 // Is there a shadow parent?
917                 if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
918                         return;
919                 }
920
921                 // Is there already a shadow entry?
922                 if (dba::exists('item', ['uri' => $item['uri'], 'uid' => 0])) {
923                         return;
924                 }
925
926                 // Preparing public shadow (removing user specific data)
927                 unset($item['id']);
928                 $item['uid'] = 0;
929                 $item['origin'] = 0;
930                 $item['wall'] = 0;
931                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], 0);
932
933                 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
934                         $item['type'] = 'remote-comment';
935                 } elseif ($item['type'] == 'wall') {
936                         $item['type'] = 'remote';
937                 }
938
939                 $public_shadow = self::insert($item, false, false, true);
940
941                 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
942         }
943
944          /**
945          * Adds a "lang" specification in a "postopts" element of given $arr,
946          * if possible and not already present.
947          * Expects "body" element to exist in $arr.
948          */
949         private static function addLanguageInPostopts(&$arr)
950         {
951                 if (x($arr, 'postopts')) {
952                         if (strstr($arr['postopts'], 'lang=')) {
953                                 // do not override
954                                 return;
955                         }
956                         $postopts = $arr['postopts'];
957                 } else {
958                         $postopts = "";
959                 }
960
961                 $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
962                 $l = new Text_LanguageDetect();
963                 $lng = $l->detect($naked_body, 3);
964
965                 if (sizeof($lng) > 0) {
966                         if ($postopts != "") {
967                                 $postopts .= '&'; // arbitrary separator, to be reviewed
968                         }
969
970                         $postopts .= 'lang=';
971                         $sep = "";
972
973                         foreach ($lng as $language => $score) {
974                                 $postopts .= $sep . $language . ";" . $score;
975                                 $sep = ':';
976                         }
977                         $arr['postopts'] = $postopts;
978                 }
979         }
980
981         /**
982          * @brief Creates an unique guid out of a given uri
983          *
984          * @param string $uri uri of an item entry
985          * @param string $host (Optional) hostname for the GUID prefix
986          * @return string unique guid
987          */
988         public static function guidFromUri($uri, $host = "")
989         {
990                 // Our regular guid routine is using this kind of prefix as well
991                 // We have to avoid that different routines could accidentally create the same value
992                 $parsed = parse_url($uri);
993
994                 // When the hostname isn't given, we take it from the uri
995                 if ($host == "") {
996                         // Is it in the format data@host.tld?
997                         if ((count($parsed) == 1) && strstr($uri, '@')) {
998                                 $mailparts = explode('@', $uri);
999                                 $host = array_pop($mailparts);
1000                         } else {
1001                                 $host = $parsed["host"];
1002                         }
1003                 }
1004
1005                 // We use a hash of the hostname as prefix for the guid
1006                 $guid_prefix = hash("crc32", $host);
1007
1008                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1009                 unset($parsed["scheme"]);
1010
1011                 // Glue it together to be able to make a hash from it
1012                 $host_id = implode("/", $parsed);
1013
1014                 // We could use any hash algorithm since it isn't a security issue
1015                 $host_hash = hash("ripemd128", $host_id);
1016
1017                 return $guid_prefix.$host_hash;
1018         }
1019
1020         /**
1021          * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
1022          *
1023          * This can be used to filter for inactive contacts.
1024          * Only do this for public postings to avoid privacy problems, since poco data is public.
1025          * Don't set this value if it isn't from the owner (could be an author that we don't know)
1026          *
1027          * @param array $arr Contains the just posted item record
1028          */
1029         private static function updateContact($arr) {
1030                 // Unarchive the author
1031                 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]);
1032                 if ($contact['term-date'] > NULL_DATE) {
1033                          Contact::unmarkForArchival($contact);
1034                 }
1035
1036                 // Unarchive the contact if it is a toplevel posting
1037                 if ($arr["parent-uri"] === $arr["uri"]) {
1038                         $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]);
1039                         if ($contact['term-date'] > NULL_DATE) {
1040                                  Contact::unmarkForArchival($contact);
1041                         }
1042                 }
1043
1044                 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
1045
1046                 // Is it a forum? Then we don't care about the rules from above
1047                 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
1048                         $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1049                                         intval($arr['contact-id']));
1050                         if (DBM::is_result($isforum)) {
1051                                 $update = true;
1052                         }
1053                 }
1054
1055                 if ($update) {
1056                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1057                                 ['id' => $arr['contact-id']]);
1058                 }
1059                 // Now do the same for the system wide contacts with uid=0
1060                 if (!$arr['private']) {
1061                         dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1062                                 ['id' => $arr['owner-id']]);
1063
1064                         if ($arr['owner-id'] != $arr['author-id']) {
1065                                 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
1066                                         ['id' => $arr['author-id']]);
1067                         }
1068                 }
1069         }
1070
1071         /**
1072          * The purpose of this function is to apply system message length limits to
1073          * imported messages without including any embedded photos in the length
1074          *
1075          * @brief Truncates imported message body string length to max_import_size
1076          * @param string $body
1077          * @return string
1078          */
1079         public static function limitBodySize($body)
1080         {
1081                 $maxlen = get_max_import_size();
1082
1083                 // If the length of the body, including the embedded images, is smaller
1084                 // than the maximum, then don't waste time looking for the images
1085                 if ($maxlen && (strlen($body) > $maxlen)) {
1086
1087                         logger('the total body length exceeds the limit', LOGGER_DEBUG);
1088
1089                         $orig_body = $body;
1090                         $new_body = '';
1091                         $textlen = 0;
1092
1093                         $img_start = strpos($orig_body, '[img');
1094                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1095                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
1096                         while (($img_st_close !== false) && ($img_end !== false)) {
1097
1098                                 $img_st_close++; // make it point to AFTER the closing bracket
1099                                 $img_end += $img_start;
1100                                 $img_end += strlen('[/img]');
1101
1102                                 if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
1103                                         // This is an embedded image
1104
1105                                         if (($textlen + $img_start) > $maxlen) {
1106                                                 if ($textlen < $maxlen) {
1107                                                         logger('the limit happens before an embedded image', LOGGER_DEBUG);
1108                                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
1109                                                         $textlen = $maxlen;
1110                                                 }
1111                                         } else {
1112                                                 $new_body = $new_body . substr($orig_body, 0, $img_start);
1113                                                 $textlen += $img_start;
1114                                         }
1115
1116                                         $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
1117                                 } else {
1118
1119                                         if (($textlen + $img_end) > $maxlen) {
1120                                                 if ($textlen < $maxlen) {
1121                                                         logger('the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
1122                                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
1123                                                         $textlen = $maxlen;
1124                                                 }
1125                                         } else {
1126                                                 $new_body = $new_body . substr($orig_body, 0, $img_end);
1127                                                 $textlen += $img_end;
1128                                         }
1129                                 }
1130                                 $orig_body = substr($orig_body, $img_end);
1131
1132                                 if ($orig_body === false) {
1133                                         // in case the body ends on a closing image tag
1134                                         $orig_body = '';
1135                                 }
1136
1137                                 $img_start = strpos($orig_body, '[img');
1138                                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1139                                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
1140                         }
1141
1142                         if (($textlen + strlen($orig_body)) > $maxlen) {
1143                                 if ($textlen < $maxlen) {
1144                                         logger('the limit happens after the end of the last image', LOGGER_DEBUG);
1145                                         $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
1146                                 }
1147                         } else {
1148                                 logger('the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
1149                                 $new_body = $new_body . $orig_body;
1150                         }
1151
1152                         return $new_body;
1153                 } else {
1154                         return $body;
1155                 }
1156         }
1157
1158         private static function setHashtags(&$item) {
1159
1160                 $tags = get_tags($item["body"]);
1161
1162                 // No hashtags?
1163                 if (!count($tags)) {
1164                         return false;
1165                 }
1166
1167                 // This sorting is important when there are hashtags that are part of other hashtags
1168                 // Otherwise there could be problems with hashtags like #test and #test2
1169                 rsort($tags);
1170
1171                 $URLSearchString = "^\[\]";
1172
1173                 // All hashtags should point to the home server if "local_tags" is activated
1174                 if (Config::get('system', 'local_tags')) {
1175                         $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1176                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
1177
1178                         $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1179                                         "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
1180                 }
1181
1182                 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1183                 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1184                         function ($match) {
1185                                 return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1186                         }, $item["body"]);
1187
1188                 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1189                         function ($match) {
1190                                 return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1191                         }, $item["body"]);
1192
1193                 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1194                         function ($match) {
1195                                 return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1196                         }, $item["body"]);
1197
1198                 // Repair recursive urls
1199                 $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1200                                 "&num;$2", $item["body"]);
1201
1202                 foreach ($tags as $tag) {
1203                         if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
1204                                 continue;
1205                         }
1206
1207                         $basetag = str_replace('_',' ',substr($tag,1));
1208
1209                         $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1210
1211                         $item["body"] = str_replace($tag, $newtag, $item["body"]);
1212
1213                         if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
1214                                 if (strlen($item["tag"])) {
1215                                         $item["tag"] = ','.$item["tag"];
1216                                 }
1217                                 $item["tag"] = $newtag.$item["tag"];
1218                         }
1219                 }
1220
1221                 // Convert back the masked hashtags
1222                 $item["body"] = str_replace("&num;", "#", $item["body"]);
1223         }
1224
1225         public static function getGuidById($id) {
1226                 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1227                 if (DBM::is_result($r)) {
1228                         return $r[0]["guid"];
1229                 } else {
1230                         return "";
1231                 }
1232         }
1233
1234         public static function getIdAndNickByGuid($guid, $uid = 0) {
1235
1236                 $nick = "";
1237                 $id = 0;
1238
1239                 if ($uid == 0) {
1240                         $uid == local_user();
1241                 }
1242
1243                 // Does the given user have this item?
1244                 if ($uid) {
1245                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1246                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1247                                         AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1248                         if (DBM::is_result($r)) {
1249                                 $id = $r[0]["id"];
1250                                 $nick = $r[0]["nickname"];
1251                         }
1252                 }
1253
1254                 // Or is it anywhere on the server?
1255                 if ($nick == "") {
1256                         $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1257                                 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 AND `item`.`moderated` = 0
1258                                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1259                                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1260                                         AND `item`.`private` = 0 AND `item`.`wall` = 1
1261                                         AND `item`.`guid` = '%s'", dbesc($guid));
1262                         if (DBM::is_result($r)) {
1263                                 $id = $r[0]["id"];
1264                                 $nick = $r[0]["nickname"];
1265                         }
1266                 }
1267                 return ["nick" => $nick, "id" => $id];
1268         }
1269
1270         /**
1271          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1272          * @param int $uid
1273          * @param int $item_id
1274          * @return bool true if item was deleted, else false
1275          */
1276         private static function tagDeliver($uid, $item_id)
1277         {
1278                 $mention = false;
1279
1280                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1281                         intval($uid)
1282                 );
1283                 if (!DBM::is_result($u)) {
1284                         return;
1285                 }
1286
1287                 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1288                 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1289
1290                 $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1291                         intval($item_id),
1292                         intval($uid)
1293                 );
1294                 if (!DBM::is_result($i)) {
1295                         return;
1296                 }
1297
1298                 $item = $i[0];
1299
1300                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
1301
1302                 /*
1303                  * Diaspora uses their own hardwired link URL in @-tags
1304                  * instead of the one we supply with webfinger
1305                  */
1306                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
1307
1308                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1309                 if ($cnt) {
1310                         foreach ($matches as $mtch) {
1311                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
1312                                         $mention = true;
1313                                         logger('mention found: ' . $mtch[2]);
1314                                 }
1315                         }
1316                 }
1317
1318                 if (!$mention) {
1319                         if (($community_page || $prvgroup) &&
1320                                   !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
1321                                 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1322                                 // delete it!
1323                                 logger("no-mention top-level post to communuty or private group. delete.");
1324                                 dba::delete('item', ['id' => $item_id]);
1325                                 return true;
1326                         }
1327                         return;
1328                 }
1329
1330                 $arr = ['item' => $item, 'user' => $u[0], 'contact' => $r[0]];
1331
1332                 Addon::callHooks('tagged', $arr);
1333
1334                 if (!$community_page && !$prvgroup) {
1335                         return;
1336                 }
1337
1338                 /*
1339                  * tgroup delivery - setup a second delivery chain
1340                  * prevent delivery looping - only proceed
1341                  * if the message originated elsewhere and is a top-level post
1342                  */
1343                 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1344                         return;
1345                 }
1346
1347                 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1348                 $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1349                         intval($u[0]['uid'])
1350                 );
1351                 if (!DBM::is_result($c)) {
1352                         return;
1353                 }
1354
1355                 // also reset all the privacy bits to the forum default permissions
1356
1357                 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1358
1359                 $forum_mode = (($prvgroup) ? 2 : 1);
1360
1361                 q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1362                         `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  WHERE `id` = %d",
1363                         intval($forum_mode),
1364                         dbesc($c[0]['name']),
1365                         dbesc($c[0]['url']),
1366                         dbesc($c[0]['thumb']),
1367                         intval($private),
1368                         dbesc($u[0]['allow_cid']),
1369                         dbesc($u[0]['allow_gid']),
1370                         dbesc($u[0]['deny_cid']),
1371                         dbesc($u[0]['deny_gid']),
1372                         intval($item_id)
1373                 );
1374                 update_thread($item_id);
1375
1376                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
1377
1378         }
1379
1380         public static function isRemoteSelf($contact, &$datarray) {
1381                 $a = get_app();
1382
1383                 if (!$contact['remote_self']) {
1384                         return false;
1385                 }
1386
1387                 // Prevent the forwarding of posts that are forwarded
1388                 if ($datarray["extid"] == NETWORK_DFRN) {
1389                         return false;
1390                 }
1391
1392                 // Prevent to forward already forwarded posts
1393                 if ($datarray["app"] == $a->get_hostname()) {
1394                         return false;
1395                 }
1396
1397                 // Only forward posts
1398                 if ($datarray["verb"] != ACTIVITY_POST) {
1399                         return false;
1400                 }
1401
1402                 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
1403                         return false;
1404                 }
1405
1406                 $datarray2 = $datarray;
1407                 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
1408                 if ($contact['remote_self'] == 2) {
1409                         $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
1410                                 intval($contact['uid']));
1411                         if (DBM::is_result($r)) {
1412                                 $datarray['contact-id'] = $r[0]["id"];
1413
1414                                 $datarray['owner-name'] = $r[0]["name"];
1415                                 $datarray['owner-link'] = $r[0]["url"];
1416                                 $datarray['owner-avatar'] = $r[0]["thumb"];
1417
1418                                 $datarray['author-name']   = $datarray['owner-name'];
1419                                 $datarray['author-link']   = $datarray['owner-link'];
1420                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
1421
1422                                 unset($datarray['created']);
1423                                 unset($datarray['edited']);
1424                         }
1425
1426                         if ($contact['network'] != NETWORK_FEED) {
1427                                 $datarray["guid"] = get_guid(32);
1428                                 unset($datarray["plink"]);
1429                                 $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
1430                                 $datarray["parent-uri"] = $datarray["uri"];
1431                                 $datarray["extid"] = $contact['network'];
1432                                 $urlpart = parse_url($datarray2['author-link']);
1433                                 $datarray["app"] = $urlpart["host"];
1434                         } else {
1435                                 $datarray['private'] = 0;
1436                         }
1437                 }
1438
1439                 if ($contact['network'] != NETWORK_FEED) {
1440                         // Store the original post
1441                         $r = self::insert($datarray2, false, false);
1442                         logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
1443                 } else {
1444                         $datarray["app"] = "Feed";
1445                 }
1446
1447                 // Trigger automatic reactions for addons
1448                 $datarray['api_source'] = true;
1449
1450                 // We have to tell the hooks who we are - this really should be improved
1451                 $_SESSION["authenticated"] = true;
1452                 $_SESSION["uid"] = $contact['uid'];
1453
1454                 return true;
1455         }
1456
1457         /**
1458          *
1459          * @param string $s
1460          * @param int    $uid
1461          * @param array  $item
1462          * @param int    $cid
1463          * @return string
1464          */
1465         public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
1466         {
1467                 if (Config::get('system', 'disable_embedded')) {
1468                         return $s;
1469                 }
1470
1471                 logger('check for photos', LOGGER_DEBUG);
1472                 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
1473
1474                 $orig_body = $s;
1475                 $new_body = '';
1476
1477                 $img_start = strpos($orig_body, '[img');
1478                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1479                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1480
1481                 while (($img_st_close !== false) && ($img_len !== false)) {
1482                         $img_st_close++; // make it point to AFTER the closing bracket
1483                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
1484
1485                         logger('found photo ' . $image, LOGGER_DEBUG);
1486
1487                         if (stristr($image, $site . '/photo/')) {
1488                                 // Only embed locally hosted photos
1489                                 $replace = false;
1490                                 $i = basename($image);
1491                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
1492                                 $x = strpos($i, '-');
1493
1494                                 if ($x) {
1495                                         $res = substr($i, $x + 1);
1496                                         $i = substr($i, 0, $x);
1497                                         $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1498                                                 dbesc($i),
1499                                                 intval($res),
1500                                                 intval($uid)
1501                                         );
1502                                         if (DBM::is_result($r)) {
1503                                                 /*
1504                                                  * Check to see if we should replace this photo link with an embedded image
1505                                                  * 1. No need to do so if the photo is public
1506                                                  * 2. If there's a contact-id provided, see if they're in the access list
1507                                                  *    for the photo. If so, embed it.
1508                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
1509                                                  *    permissions, regardless of order but first check to see if they're an exact
1510                                                  *    match to save some processing overhead.
1511                                                  */
1512                                                 if (self::hasPermissions($r[0])) {
1513                                                         if ($cid) {
1514                                                                 $recips = self::enumeratePermissions($r[0]);
1515                                                                 if (in_array($cid, $recips)) {
1516                                                                         $replace = true;
1517                                                                 }
1518                                                         } elseif ($item) {
1519                                                                 if (self::samePermissions($item, $r[0])) {
1520                                                                         $replace = true;
1521                                                                 }
1522                                                         }
1523                                                 }
1524                                                 if ($replace) {
1525                                                         $data = $r[0]['data'];
1526                                                         $type = $r[0]['type'];
1527
1528                                                         // If a custom width and height were specified, apply before embedding
1529                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
1530                                                                 logger('scaling photo', LOGGER_DEBUG);
1531
1532                                                                 $width = intval($match[1]);
1533                                                                 $height = intval($match[2]);
1534
1535                                                                 $Image = new Image($data, $type);
1536                                                                 if ($Image->isValid()) {
1537                                                                         $Image->scaleDown(max($width, $height));
1538                                                                         $data = $Image->asString();
1539                                                                         $type = $Image->getType();
1540                                                                 }
1541                                                         }
1542
1543                                                         logger('replacing photo', LOGGER_DEBUG);
1544                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
1545                                                         logger('replaced: ' . $image, LOGGER_DATA);
1546                                                 }
1547                                         }
1548                                 }
1549                         }
1550
1551                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
1552                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
1553                         if ($orig_body === false) {
1554                                 $orig_body = '';
1555                         }
1556
1557                         $img_start = strpos($orig_body, '[img');
1558                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
1559                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
1560                 }
1561
1562                 $new_body = $new_body . $orig_body;
1563
1564                 return $new_body;
1565         }
1566
1567         private static function hasPermissions($obj) {
1568                 return (
1569                         (
1570                                 x($obj, 'allow_cid')
1571                         ) || (
1572                                 x($obj, 'allow_gid')
1573                         ) || (
1574                                 x($obj, 'deny_cid')
1575                         ) || (
1576                                 x($obj, 'deny_gid')
1577                         )
1578                 );
1579         }
1580
1581         private static function samePermissions($obj1, $obj2) {
1582                 // first part is easy. Check that these are exactly the same.
1583                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
1584                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
1585                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
1586                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
1587                         return true;
1588                 }
1589
1590                 // This is harder. Parse all the permissions and compare the resulting set.
1591                 $recipients1 = self::enumeratePermissions($obj1);
1592                 $recipients2 = self::enumeratePermissions($obj2);
1593                 sort($recipients1);
1594                 sort($recipients2);
1595
1596                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
1597                 return ($recipients1 == $recipients2);
1598         }
1599
1600         // returns an array of contact-ids that are allowed to see this object
1601         private static function enumeratePermissions($obj) {
1602                 $allow_people = expand_acl($obj['allow_cid']);
1603                 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
1604                 $deny_people  = expand_acl($obj['deny_cid']);
1605                 $deny_groups  = Group::expand(expand_acl($obj['deny_gid']));
1606                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
1607                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
1608                 $recipients   = array_diff($recipients, $deny);
1609                 return $recipients;
1610         }
1611
1612         public static function getFeedTags($item) {
1613                 $ret = [];
1614                 $matches = false;
1615                 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1616                 if ($cnt) {
1617                         for ($x = 0; $x < $cnt; $x ++) {
1618                                 if ($matches[1][$x]) {
1619                                         $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
1620                                 }
1621                         }
1622                 }
1623                 $matches = false;
1624                 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
1625                 if ($cnt) {
1626                         for ($x = 0; $x < $cnt; $x ++) {
1627                                 if ($matches[1][$x]) {
1628                                         $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
1629                                 }
1630                         }
1631                 }
1632                 return $ret;
1633         }
1634
1635         public static function expire($uid, $days, $network = "", $force = false) {
1636
1637                 if (!$uid || ($days < 1)) {
1638                         return;
1639                 }
1640
1641                 /*
1642                  * $expire_network_only = save your own wall posts
1643                  * and just expire conversations started by others
1644                  */
1645                 $expire_network_only = PConfig::get($uid,'expire', 'network_only');
1646                 $sql_extra = (intval($expire_network_only) ? " AND wall = 0 " : "");
1647
1648                 if ($network != "") {
1649                         $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
1650
1651                         /*
1652                          * There is an index "uid_network_received" but not "uid_network_created"
1653                          * This avoids the creation of another index just for one purpose.
1654                          * And it doesn't really matter wether to look at "received" or "created"
1655                          */
1656                         $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1657                 } else {
1658                         $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
1659                 }
1660
1661                 $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
1662                         WHERE `uid` = %d $range
1663                         AND `id` = `parent`
1664                         $sql_extra
1665                         AND `deleted` = 0",
1666                         intval($uid),
1667                         intval($days)
1668                 );
1669
1670                 if (!DBM::is_result($r)) {
1671                         return;
1672                 }
1673
1674                 $expire_items = PConfig::get($uid, 'expire', 'items', 1);
1675
1676                 // Forcing expiring of items - but not notes and marked items
1677                 if ($force) {
1678                         $expire_items = true;
1679                 }
1680
1681                 $expire_notes = PConfig::get($uid, 'expire', 'notes', 1);
1682                 $expire_starred = PConfig::get($uid, 'expire', 'starred', 1);
1683                 $expire_photos = PConfig::get($uid, 'expire', 'photos', 0);
1684
1685                 logger('User '.$uid.': expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
1686
1687                 foreach ($r as $item) {
1688
1689                         // don't expire filed items
1690
1691                         if (strpos($item['file'],'[') !== false) {
1692                                 continue;
1693                         }
1694
1695                         // Only expire posts, not photos and photo comments
1696
1697                         if ($expire_photos == 0 && strlen($item['resource-id'])) {
1698                                 continue;
1699                         } elseif ($expire_starred == 0 && intval($item['starred'])) {
1700                                 continue;
1701                         } elseif ($expire_notes == 0 && $item['type'] == 'note') {
1702                                 continue;
1703                         } elseif ($expire_items == 0 && $item['type'] != 'note') {
1704                                 continue;
1705                         }
1706
1707                         self::delete($item['id'], PRIORITY_LOW);
1708                 }
1709         }
1710
1711         /// @TODO: This query seems to be really slow
1712         public static function firstPostDate($uid, $wall = false) {
1713                 $r = q("SELECT `id`, `created` FROM `item`
1714                         WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
1715                         AND `id` = `parent`
1716                         ORDER BY `created` ASC LIMIT 1",
1717                         intval($uid),
1718                         intval($wall ? 1 : 0)
1719                 );
1720                 if (DBM::is_result($r)) {
1721                         return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
1722                 }
1723                 return false;
1724         }
1725 }