function sync_files($channel, $files) { require_once 'include/attach.php'; if ($channel && $files) { foreach ($files as $f) { if (!$f) { continue; } $fetch_url = $f['fetch_url']; $oldbase = dirname($fetch_url); $original_channel = $f['original_channel']; if (!($fetch_url && $original_channel)) { continue; } if ($f['attach']) { $attachment_stored = false; foreach ($f['attach'] as $att) { convert_oldfields($att, 'data', 'content'); if ($att['deleted']) { attach_delete($channel, $att['hash']); continue; } $attach_exists = false; $x = attach_by_hash($att['hash']); logger('sync_files duplicate check: attach_exists=' . $attach_exists, LOGGER_DEBUG); logger('sync_files duplicate check: att=' . print_r($att, true), LOGGER_DEBUG); logger('sync_files duplicate check: attach_by_hash() returned ' . print_r($x, true), LOGGER_DEBUG); if ($x['success']) { $attach_exists = true; $attach_id = $x[0]['id']; } $newfname = 'store/' . $channel['channel_address'] . '/' . get_attach_binname($att['content']); unset($att['id']); $att['aid'] = $channel['channel_account_id']; $att['uid'] = $channel['channel_id']; // check for duplicate folder names with the same parent. // If we have a duplicate that doesn't match this hash value // change the name so that the contents won't be "covered over" // by the existing directory. Use the same logic we use for // duplicate files. if (strpos($att['filename'], '.') !== false) { $basename = substr($att['filename'], 0, strrpos($att['filename'], '.')); $ext = substr($att['filename'], strrpos($att['filename'], '.')); } else { $basename = $att['filename']; $ext = ''; } $r = q("select filename from attach where ( filename = '%s' OR filename like '%s' ) and folder = '%s' and hash != '%s' ", dbesc($basename . $ext), dbesc($basename . '(%)' . $ext), dbesc($att['folder']), dbesc($att['hash'])); if ($r) { $x = 1; do { $found = false; foreach ($r as $rr) { if ($rr['filename'] === $basename . '(' . $x . ')' . $ext) { $found = true; break; } } if ($found) { $x++; } } while ($found); $att['filename'] = $basename . '(' . $x . ')' . $ext; } else { $att['filename'] = $basename . $ext; } // end duplicate detection // @fixme - update attachment structures if they are modified rather than created $att['content'] = $newfname; // Note: we use $att['hash'] below after it has been escaped to // fetch the file contents. // If the hash ever contains any escapable chars this could cause // problems. Currently it does not. dbesc_array($att); if ($attach_exists) { logger('sync_files attach exists: ' . print_r($att, true), LOGGER_DEBUG); $str = ''; foreach ($att as $k => $v) { if ($str) { $str .= ","; } $str .= " `" . $k . "` = '" . $v . "' "; } $r = dbq("update `attach` set " . $str . " where id = " . intval($attach_id)); } else { logger('sync_files attach does not exists: ' . print_r($att, true), LOGGER_DEBUG); $r = dbq("INSERT INTO attach (`" . implode("`, `", array_keys($att)) . "`) VALUES ('" . implode("', '", array_values($att)) . "')"); } // is this a directory? if ($att['filetype'] === 'multipart/mixed' && $att['is_dir']) { os_mkdir($newfname, STORAGE_DEFAULT_PERMISSIONS, true); $attachment_stored = true; continue; } else { // it's a file // for the sync version of this algorithm (as opposed to 'offline import') // we will fetch the actual file from the source server so it can be // streamed directly to disk and avoid consuming PHP memory if it's a huge // audio/video file or something. $time = datetime_convert(); $parr = array('hash' => $channel['channel_hash'], 'time' => $time, 'resource' => $att['hash'], 'revision' => 0, 'signature' => base64url_encode(rsa_sign($channel['channel_hash'] . '.' . $time, $channel['channel_prvkey']))); $store_path = $newfname; $fp = fopen($newfname, 'w'); if (!$fp) { logger('failed to open storage file.', LOGGER_NORMAL, LOG_ERR); continue; } $redirects = 0; $x = z_post_url($fetch_url, $parr, $redirects, array('filep' => $fp)); fclose($fp); if ($x['success']) { $attachment_stored = true; } continue; } } } if (!$attachment_stored) { // @TODO should we queue this and retry or delete everything or what? logger('attachment store failed', LOGGER_NORMAL, LOG_ERR); } if ($f['photo']) { foreach ($f['photo'] as $p) { unset($p['id']); $p['aid'] = $channel['channel_account_id']; $p['uid'] = $channel['channel_id']; convert_oldfields($p, 'data', 'content'); convert_oldfields($p, 'scale', 'imgscale'); convert_oldfields($p, 'size', 'filesize'); convert_oldfields($p, 'type', 'mimetype'); // if this is a profile photo, undo the profile photo bit // for any other photo which previously held it. if ($p['photo_usage'] == PHOTO_PROFILE) { $e = q("update photo set photo_usage = %d where photo_usage = %d\n\t\t\t\t\t\t\tand resource_id != '%s' and uid = %d ", intval(PHOTO_NORMAL), intval(PHOTO_PROFILE), dbesc($p['resource_id']), intval($channel['channel_id'])); } // same for cover photos if ($p['photo_usage'] == PHOTO_COVER) { $e = q("update photo set photo_usage = %d where photo_usage = %d\n\t\t\t\t\t\t\tand resource_id != '%s' and uid = %d ", intval(PHOTO_NORMAL), intval(PHOTO_COVER), dbesc($p['resource_id']), intval($channel['channel_id'])); } if ($p['imgscale'] === 0 && $p['os_storage']) { $p['content'] = $store_path; } else { $p['content'] = base64_decode($p['content']); } $exists = q("select * from photo where resource_id = '%s' and imgscale = %d and uid = %d limit 1", dbesc($p['resource_id']), intval($p['imgscale']), intval($channel['channel_id'])); dbesc_array($p); if ($exists) { $str = ''; foreach ($p as $k => $v) { if ($str) { $str .= ","; } $str .= " `" . $k . "` = '" . $v . "' "; } $r = dbq("update `photo` set " . $str . " where id = " . intval($exists[0]['id'])); } else { $r = dbq("INSERT INTO photo (`" . implode("`, `", array_keys($p)) . "`) VALUES ('" . implode("', '", array_values($p)) . "')"); } } } if ($f['item']) { sync_items($channel, $f['item'], ['channel_address' => $original_channel, 'url' => $oldbase]); } } } }
function dfrn_notify_post(&$a) { $dfrn_id = notags(trim($_POST['dfrn_id'])); $challenge = notags(trim($_POST['challenge'])); $data = $_POST['data']; $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1", dbesc($dfrn_id), dbesc($challenge)); if (!count($r)) { xml_status(3); } $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1", dbesc($dfrn_id), dbesc($challenge)); // find the local user who owns this relationship. $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` on `user`.`uid` = 1 \n\t\tWHERE ( `issued-id` = '%s' OR ( `duplex` = 1 AND `dfrn-id` = '%s' )) LIMIT 1", dbesc($dfrn_id), dbesc($dfrn_id)); if (!count($r)) { xml_status(3); return; //NOTREACHED } $importer = $r[0]; $feed = new SimplePie(); $feed->set_raw_data($data); $feed->enable_order_by_date(false); $feed->init(); $ismail = false; $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail'); if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) { if ($importer['readonly']) { // We aren't receiving email from this person. But we will quietly ignore them // rather than a blatant "go away" message. xml_status(0); return; //NOTREACHED } $ismail = true; $base = $rawmail[0]['child'][NAMESPACE_DFRN]; $msg = array(); $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data'])); $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data'])); $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])); $msg['contact-id'] = $importer['id']; $msg['title'] = notags(unxmlify($base['subject'][0]['data'])); $msg['body'] = escape_tags(unxmlify($base['content'][0]['data'])); $msg['delivered'] = 1; $msg['seen'] = 0; $msg['replied'] = 0; $msg['uri'] = notags(unxmlify($base['id'][0]['data'])); $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data'])); $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data']))); dbesc_array($msg); $r = q("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')"); require_once 'bbcode.php'; if ($importer['notify-flags'] & NOTIFY_MAIL) { $tpl = file_get_contents('view/mail_received_eml.tpl'); $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $msg['from-name'], '$title' => $msg['title'], '$body' => strip_tags(bbcode($msg['body'])))); $res = mail($importer['email'], t("New mail received at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname()); } xml_status(0); return; // NOTREACHED } if ($importer['readonly'] && !x($a->config['rockstar'])) { // This contact is readonly and we're going to ignore him/her, except if we're in // RockStar configuration. Us rockstars wan't people to talk about us. We just don't // want to have to deal with them individually. So our "readonly" fans can post to // our wall and comment, but they can't send us email. xml_status(0); return; // NOTREACHED } foreach ($feed->get_items() as $item) { $deleted = false; $rawdelete = $item->get_item_tags("http://purl.org/atompub/tombstones/1.0", 'deleted-entry'); if (isset($rawdelete[0]['attribs']['']['ref'])) { $uri = $rawthread[0]['attribs']['']['ref']; $deleted = true; if (isset($rawdelete[0]['attribs']['']['when'])) { $when = $rawthread[0]['attribs']['']['when']; $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s'); } else { $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s'); } } if ($deleted) { $r = q("SELECT * FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($uri)); if (count($r)) { $item = $r[0]; if ($item['uri'] == $item['parent-uri']) { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s' , `changed` = '%s'\n\t\t\t\t\t\tWHERE `parent-uri` = '%s'", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri'])); } else { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s' , `changed` = '%s' \n\t\t\t\t\t\tWHERE `uri` = '%s' LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri)); } if ($item['last-child']) { // ensure that last-child is set in case the comment that had it just got wiped. $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' ", dbesc(datetime_convert()), dbesc($item['parent-uri'])); // who is the last child now? $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 \n\t\t\t\t\t\tORDER BY `edited` DESC LIMIT 1", dbesc($item['parent-uri'])); if (count($r)) { q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id'])); } } } continue; } $is_reply = false; $item_id = $item->get_id(); $rawthread = $item->get_item_tags("http://purl.org/syndication/thread/1.0", 'in-reply-to'); if (isset($rawthread[0]['attribs']['']['ref'])) { $is_reply = true; $parent_uri = $rawthread[0]['attribs']['']['ref']; } if ($is_reply) { if ($feed->get_item_quantity() == 1) { // remote reply to our post. Import and then notify everybody else. $datarray = get_atom_elements($item); $datarray['wall'] = 1; $datarray['type'] = 'remote-comment'; $datarray['parent-uri'] = $parent_uri; $datarray['contact-id'] = $importer['id']; $posted_id = post_remote($a, $datarray); if ($posted_id) { $r = q("SELECT `parent` FROM `item` WHERE `id` = %d LIMIT 1", intval($posted_id)); if (count($r)) { $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d", dbesc(datetime_convert()), intval($r[0]['parent'])); } $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($posted_id)); $php_path = strlen($a->config['php_path']) ? $a->config['php_path'] : 'php'; proc_close(proc_open("\"{$php_path}\" \"include/notifier.php\" \"comment-import\" \"{$posted_id}\" &", array(), $foo)); if ($importer['notify-flags'] & NOTIFY_COMMENT && !$importer['self']) { require_once 'bbcode.php'; $from = stripslashes($datarray['author-name']); $tpl = file_get_contents('view/cmnt_received_eml.tpl'); $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $from, '$body' => strip_tags(bbcode(stripslashes($datarray['body']))))); $res = mail($importer['email'], $from . t(" commented on your item at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname()); } } xml_status(0); return; } else { // regular comment that is part of this total conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id)); // FIXME update content if 'updated' changes if (count($r)) { $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id)); } continue; } $datarray = get_atom_elements($item); $datarray['parent-uri'] = $parent_uri; $datarray['contact-id'] = $importer['id']; $r = post_remote($a, $datarray); // find out if our user is involved in this conversation and wants to be notified. if ($importer['notify-flags'] & NOTIFY_COMMENT) { $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s'", dbesc($parent_uri)); if (count($myconv)) { foreach ($myconv as $conv) { if ($conv['author-link'] != $importer['url']) { continue; } require_once 'bbcode.php'; $from = stripslashes($datarray['author-name']); $tpl = file_get_contents('view/cmnt_received_eml.tpl'); $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $from, '$body' => strip_tags(bbcode(stripslashes($datarray['body']))))); $res = mail($importer['email'], $from . t(" commented on an item at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname()); break; } } } continue; } } else { // Head post of a conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id)); if (count($r)) { $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id)); } continue; } $datarray = get_atom_elements($item); $datarray['parent-uri'] = $item_id; $datarray['contact-id'] = $importer['id']; $r = post_remote($a, $datarray); continue; } } xml_status(0); killme(); }
function import_post(&$a) { if (!get_account_id()) { return; } $data = null; $seize = x($_REQUEST, 'make_primary') ? intval($_REQUEST['make_primary']) : 0; $src = $_FILES['filename']['tmp_name']; $filename = basename($_FILES['filename']['name']); $filesize = intval($_FILES['filename']['size']); $filetype = $_FILES['filename']['type']; if ($src) { if ($filesize) { $data = @file_get_contents($src); } unlink($src); } if (!$src) { $old_address = x($_REQUEST, 'old_address') ? $_REQUEST['old_address'] : ''; if (!$old_address) { logger('mod_import: nothing to import.'); notice(t('Nothing to import.') . EOL); return; } $email = x($_REQUEST, 'email') ? $_REQUEST['email'] : ''; $password = x($_REQUEST, 'password') ? $_REQUEST['password'] : ''; $channelname = substr($old_address, 0, strpos($old_address, '@')); $servername = substr($old_address, strpos($old_address, '@') + 1); $scheme = 'https://'; $api_path = '/api/red/channel/export/basic?f=&channel=' . $channelname; $binary = false; $redirects = 0; $opts = array('http_auth' => $email . ':' . $password); $url = $scheme . $servername . $api_path; $ret = z_fetch_url($url, $binary, $redirects, $opts); if (!$ret['success']) { $ret = z_fetch_url('http://' . $servername . $api_path, $binary, $redirects, $opts); } if ($ret['success']) { $data = $ret['body']; } else { notice(t('Unable to download data from old server') . EOL); } } if (!$data) { logger('mod_import: empty file.'); notice(t('Imported file is empty.') . EOL); return; } $data = json_decode($data, true); // logger('import: data: ' . print_r($data,true)); // print_r($data); // import channel $channel = $data['channel']; $r = q("select * from channel where (channel_guid = '%s' or channel_hash = '%s' or channel_address = '%s' ) limit 1", dbesc($channel['channel_guid']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'])); // We should probably also verify the hash if ($r) { logger('mod_import: duplicate channel. ', print_r($channel, true)); notice(t('Cannot create a duplicate channel identifier on this system. Import failed.') . EOL); return; } unset($channel['channel_id']); $channel['channel_account_id'] = get_account_id(); $channel['channel_primary'] = $seize ? 1 : 0; dbesc_array($channel); $r = dbq("INSERT INTO channel (`" . implode("`, `", array_keys($channel)) . "`) VALUES ('" . implode("', '", array_values($channel)) . "')"); if (!$r) { logger('mod_import: channel clone failed. ', print_r($channel, true)); notice(t('Channel clone failed. Import failed.') . EOL); return; } $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", intval(get_account_id()), $channel['channel_guid']); if (!$r) { logger('mod_import: channel not found. ', print_r($channel, true)); notice(t('Cloned channel not found. Import failed.') . EOL); return; } // reset $channel = $r[0]; set_default_login_identity(get_account_id(), $channel['channel_id'], false); if ($data['photo']) { require_once 'include/photo/photo_driver.php'; import_channel_photo(base64url_decode($data['photo']['data']), $data['photo']['type'], get_account_id(), $channel['channel_id']); } $profiles = $data['profile']; if ($profiles) { foreach ($profiles as $profile) { unset($profile['id']); $profile['aid'] = get_account_id(); $profile['uid'] = $channel['channel_id']; // we are going to reset all profile photos to the original // somebody will have to fix this later and put all the applicable photos into the export $profile['photo'] = z_root() . '/photo/profile/l/' . $channel['channel_id']; $profile['thumb'] = z_root() . '/photo/profile/m/' . $channel['channel_id']; dbesc_array($profile); $r = dbq("INSERT INTO profile (`" . implode("`, `", array_keys($profile)) . "`) VALUES ('" . implode("', '", array_values($profile)) . "')"); } } $hublocs = $data['hubloc']; if ($hublocs) { foreach ($hublocs as $hubloc) { $arr = array('guid' => $hubloc['hubloc_guid'], 'guid_sig' => $hubloc['guid_sig'], 'url' => $hubloc['hubloc_url'], 'url_sig' => $hubloc['hubloc_url_sig']); if ($hubloc['hubloc_hash'] === $channel['channel_hash'] && $hubloc['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY && $seize) { $hubloc['hubloc_flags'] = $hubloc['hubloc_flags'] ^ HUBLOC_FLAGS_PRIMARY; } if (!zot_gethub($arr)) { unset($hubloc['hubloc_id']); dbesc_array($hubloc); $r = dbq("INSERT INTO hubloc (`" . implode("`, `", array_keys($hubloc)) . "`) VALUES ('" . implode("', '", array_values($hubloc)) . "')"); } } } // create new hubloc for the new channel at this site $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_flags, \n\t\thubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey )\n\t\tvalues ( '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'] . '@' . get_app()->get_hostname()), dbesc('zot'), intval($seize ? HUBLOC_FLAGS_PRIMARY : 0), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $channel['channel_prvkey']))), dbesc(get_app()->get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system', 'pubkey'))); // reset the original primary hubloc if it is being seized if ($seize) { $r = q("update hubloc set hubloc_flags = (hubloc_flags ^ %d) where (hubloc_flags & %d) and hubloc_hash = '%s' and hubloc_url != '%s' ", intval(HUBLOC_FLAGS_PRIMARY), intval(HUBLOC_FLAGS_PRIMARY), dbesc($channel['channel_hash']), dbesc(z_root())); } // import xchans and contact photos if ($seize) { // replace our existing xchan if we're seizing control $r = q("delete from xchan where xchan_hash = '%s' limit 1", dbesc($channel['channel_hash'])); $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", dbesc($channel['channel_hash']), dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_pubkey']), dbesc($a->get_baseurl() . "/photo/profile/l/" . $channel['channel_id']), dbesc($a->get_baseurl() . "/photo/profile/m/" . $channel['channel_id']), dbesc($a->get_baseurl() . "/photo/profile/s/" . $channel['channel_id']), dbesc($channel['channel_address'] . '@' . get_app()->get_hostname()), dbesc(z_root() . '/channel/' . $channel['channel_address']), dbesc(z_root() . '/follow?f=&url=%s'), dbesc(z_root() . '/poco/' . $channel['channel_address']), dbesc($channel['channel_name']), dbesc('zot'), dbesc(datetime_convert()), dbesc(datetime_convert())); } $xchans = $data['xchan']; if ($xchans) { foreach ($xchans as $xchan) { $r = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($xchan['xchan_hash'])); if ($r) { continue; } dbesc_array($xchan); $r = dbq("INSERT INTO xchan (`" . implode("`, `", array_keys($xchan)) . "`) VALUES ('" . implode("', '", array_values($xchan)) . "')"); require_once 'include/photo/photo_driver.php'; $photos = import_profile_photo($xchan['xchan_photo_l'], $xchan['xchan_hash']); if ($photos[4]) { $photodate = NULL_DATE; } else { $photodate = $xchan['xchan_photo_date']; } $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s', xchan_photo_date = '%s'\n\t\t\t\twhere xchan_hash = '%s' limit 1", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($photodate), dbesc($xchan_hash)); } } // FIXME - ensure we have an xchan if somebody is trying to pull a fast one // import contacts $abooks = $data['abook']; if ($abooks) { foreach ($abooks as $abook) { unset($abook['abook_id']); $abook['abook_account'] = get_account_id(); $abook['abook_channel'] = $channel['channel_id']; dbesc_array($abook); $r = dbq("INSERT INTO abook (`" . implode("`, `", array_keys($abook)) . "`) VALUES ('" . implode("', '", array_values($abook)) . "')"); } } $configs = $data['config']; if ($configs) { foreach ($configs as $config) { unset($config['id']); $config['uid'] = $channel['channel_id']; dbesc_array($config); $r = dbq("INSERT INTO pconfig (`" . implode("`, `", array_keys($config)) . "`) VALUES ('" . implode("', '", array_values($config)) . "')"); } } $groups = $data['group']; if ($groups) { $saved = array(); foreach ($groups as $group) { $saved[$group['hash']] = array('old' => $group['id']); unset($group['id']); $group['uid'] = $channel['channel_id']; dbesc_array($group); $r = dbq("INSERT INTO group (`" . implode("`, `", array_keys($group)) . "`) VALUES ('" . implode("', '", array_values($group)) . "')"); } $r = q("select * from `groups` where uid = %d", intval($channel['channel_id'])); if ($r) { foreach ($r as $rr) { $saved[$rr['hash']]['new'] = $rr['id']; } } } $group_members = $data['group_member']; if ($groups_members) { foreach ($group_members as $group_member) { unset($group_member['id']); $group_member['uid'] = $channel['channel_id']; foreach ($saved as $x) { if ($x['old'] == $group_member['gid']) { $group_member['gid'] = $x['new']; } } dbesc_array($group_member); $r = dbq("INSERT INTO group_member (`" . implode("`, `", array_keys($group_member)) . "`) VALUES ('" . implode("', '", array_values($group_member)) . "')"); } } // FIXME - ensure we have a self entry if somebody is trying to pull a fast one if ($seize) { // notify old server that it is no longer primary. } // This will indirectly perform a refresh_all *and* update the directory proc_run('php', 'include/directory.php', $channel['channel_id']); // send out refresh requests notice(t('Import completed.') . EOL); change_channel($channel['channel_id']); goaway(z_root() . '/network'); }
function init() { nav_set_selected('profiles'); if (!local_channel()) { return; } if (argc() > 2 && argv(1) === "drop" && intval(argv(2))) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d AND `is_default` = 0 LIMIT 1", intval(argv(2)), intval(local_channel())); if (!count($r)) { notice(t('Profile not found.') . EOL); goaway(z_root() . '/profiles'); return; // NOTREACHED } $profile_guid = $r['profile_guid']; check_form_security_token_redirectOnErr('/profiles', 'profile_drop', 't'); // move every contact using this profile as their default to the user default $r = q("UPDATE abook SET abook_profile = (SELECT profile_guid AS FROM profile WHERE is_default = 1 AND uid = %d LIMIT 1) WHERE abook_profile = '%s' AND abook_channel = %d ", intval(local_channel()), dbesc($profile_guid), intval(local_channel())); $r = q("DELETE FROM `profile` WHERE `id` = %d AND `uid` = %d", intval(argv(2)), intval(local_channel())); if ($r) { info(t('Profile deleted.') . EOL); } // @fixme this is a much more complicated sync - add any changed abook entries and // also add deleted flag to profile structure // profiles_build_sync is just here as a placeholder - it doesn't work at all here // profiles_build_sync(local_channel()); goaway(z_root() . '/profiles'); return; // NOTREACHED } if (argc() > 1 && argv(1) === 'new') { // check_form_security_token_redirectOnErr('/profiles', 'profile_new', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_channel())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT `fullname`, `photo`, `thumb` FROM `profile` WHERE `uid` = %d AND `is_default` = 1 LIMIT 1", intval(local_channel())); $r2 = q("INSERT INTO `profile` (`aid`, `uid` , `profile_guid`, `profile_name` , `fullname`, `photo`, `thumb`)\n\t\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s' )", intval(get_account_id()), intval(local_channel()), dbesc(random_string()), dbesc($name), dbesc($r1[0]['fullname']), dbesc($r1[0]['photo']), dbesc($r1[0]['thumb'])); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile_name` = '%s' LIMIT 1", intval(local_channel()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway(z_root() . '/profiles/' . $r3[0]['id']); } goaway(z_root() . '/profiles'); } if (argc() > 2 && argv(1) === 'clone') { check_form_security_token_redirectOnErr('/profiles', 'profile_clone', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_channel())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_channel()), intval(\App::$argv[2])); if (!count($r1)) { notice(t('Profile unavailable to clone.') . EOL); \App::$error = 404; return; } unset($r1[0]['id']); $r1[0]['is_default'] = 0; $r1[0]['publish'] = 0; $r1[0]['profile_name'] = dbesc($name); $r1[0]['profile_guid'] = dbesc(random_string()); dbesc_array($r1[0]); $r2 = dbq("INSERT INTO `profile` (`" . implode("`, `", array_keys($r1[0])) . "`) VALUES ('" . implode("', '", array_values($r1[0])) . "')"); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile_name` = '%s' LIMIT 1", intval(local_channel()), dbesc($name)); info(t('New profile created.') . EOL); profiles_build_sync(local_channel()); if ($r3 && count($r3) == 1) { goaway(z_root() . '/profiles/' . $r3[0]['id']); } goaway(z_root() . '/profiles'); return; // NOTREACHED } if (argc() > 2 && argv(1) === 'export') { $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_channel()), intval(argv(2))); if (!$r1) { notice(t('Profile unavailable to export.') . EOL); \App::$error = 404; return; } header('content-type: application/octet_stream'); header('content-disposition: attachment; filename="' . $r1[0]['profile_name'] . '.json"'); unset($r1[0]['id']); unset($r1[0]['aid']); unset($r1[0]['uid']); unset($r1[0]['is_default']); unset($r1[0]['publish']); unset($r1[0]['profile_name']); unset($r1[0]['profile_guid']); echo json_encode($r1[0]); killme(); } // Run profile_load() here to make sure the theme is set before // we start loading content if (argc() > 1 && intval(argv(1)) || !feature_enabled(local_channel(), 'multi_profiles')) { if (feature_enabled(local_channel(), 'multi_profiles')) { $id = \App::$argv[1]; } else { $x = q("select id from profile where uid = %d and is_default = 1", intval(local_channel())); if ($x) { $id = $x[0]['id']; } } $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($id), intval(local_channel())); if (!count($r)) { notice(t('Profile not found.') . EOL); \App::$error = 404; return; } $chan = \App::get_channel(); profile_load($chan['channel_address'], $r[0]['id']); } }
$args['photo_usage'] = PHOTO_PROFILE; } if (array_key_exists('photo_usage', $args)) { $args['photo_usage'] = $j['photo']['photo_usage']; } $args['type'] = $j['photo']['type']; $args['item'] = $j['item'] ? $j['item'] : false; // logger('redphotohelper: ' . print_r($j,true)); $r = q("select id from photo where resource_id = '%s' and uid = %d limit 1", dbesc($args['hash']), intval($channel['channel_id'])); if ($r) { killme(); } $ret = attach_store($channel, $channel['channel_hash'], 'import', $args); $r = q("select * from item where resource_id = '%s' and resource_type = 'photo' and uid = %d limit 1", dbesc($args['hash']), intval($channel['channel_id'])); if ($r) { $item = $r[0]; item_url_replace($channel, $item, $fr_server, z_root(), $fr_username); dbesc_array($item); $item_id = $item['id']; unset($item['id']); $str = ''; foreach ($item as $k => $v) { if ($str) { $str .= ","; } $str .= " `" . $k . "` = '" . $v . "' "; } $r = dbq("update `item` set " . $str . " where id = " . $item_id); } // logger('photo_import: ' . print_r($ret,true)); killme();
function profiles_init(&$a) { nav_set_selected('profiles'); if (!local_user()) { return; } if (argc() > 2 && argv(1) === "drop" && intval(argv(2))) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d AND `is_default` = 0 LIMIT 1", intval($a->argv[2]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } $profile_guid = $r['profile_guid']; check_form_security_token_redirectOnErr('/profiles', 'profile_drop', 't'); // move every contact using this profile as their default to the user default $r = q("UPDATE abook SET abook_profile = (SELECT profile_guid AS FROM profile WHERE is_default = 1 AND uid = %d LIMIT 1) WHERE abook_profile = '%s' AND abook_channel = %d ", intval(local_user()), dbesc($profile_guid), intval(local_user())); $r = q("DELETE FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval(argv(2)), intval(local_user())); if ($r) { info(t('Profile deleted.') . EOL); } goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } if (argc() > 1 && argv(1) === 'new') { // check_form_security_token_redirectOnErr('/profiles', 'profile_new', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT `name`, `photo`, `thumb` FROM `profile` WHERE `uid` = %d AND `is_default` = 1 LIMIT 1", intval(local_user())); $r2 = q("INSERT INTO `profile` (`aid`, `uid` , `profile_guid`, `profile_name` , `name`, `photo`, `thumb`)\n\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s' )", intval(get_account_id()), intval(local_user()), dbesc(random_string()), dbesc($name), dbesc($r1[0]['name']), dbesc($r1[0]['photo']), dbesc($r1[0]['thumb'])); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile_name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl(true) . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl(true) . '/profiles'); } if (argc() > 2 && argv(1) === 'clone') { check_form_security_token_redirectOnErr('/profiles', 'profile_clone', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_user()), intval($a->argv[2])); if (!count($r1)) { notice(t('Profile unavailable to clone.') . EOL); $a->error = 404; return; } unset($r1[0]['id']); $r1[0]['is_default'] = 0; $r1[0]['publish'] = 0; $r1[0]['profile_name'] = dbesc($name); $r1[0]['profile_guid'] = dbesc(random_string()); dbesc_array($r1[0]); $r2 = dbq("INSERT INTO `profile` (`" . implode("`, `", array_keys($r1[0])) . "`) VALUES ('" . implode("', '", array_values($r1[0])) . "')"); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile_name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl(true) . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } if (argc() > 2 && argv(1) === 'export') { $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_user()), intval(argv(2))); if (!$r1) { notice(t('Profile unavailable to export.') . EOL); $a->error = 404; return; } header('content-type: application/octet_stream'); header('content-disposition: attachment; filename="' . $r1[0]['profile_name'] . '.json"'); unset($r1[0]['id']); unset($r1[0]['aid']); unset($r1[0]['uid']); unset($r1[0]['is_default']); unset($r1[0]['publish']); unset($r1[0]['profile_name']); unset($r1[0]['profile_guid']); echo json_encode($r1[0]); killme(); } // Run profile_load() here to make sure the theme is set before // we start loading content if (argc() > 1 && intval(argv(1))) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($a->argv[1]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); $a->error = 404; return; } $chan = $a->get_channel(); profile_load($a, $chan['channel_address'], $r[0]['id']); } }
function local_delivery($importer, $data) { $a = get_app(); if ($importer['readonly']) { // We aren't receiving stuff from this person. But we will quietly ignore them // rather than a blatant "go away" message. logger('local_delivery: ignoring'); return 0; //NOTREACHED } // Consume notification feed. This may differ from consuming a public feed in several ways // - might contain email or friend suggestions // - might contain remote followup to our message // - in which case we need to accept it and then notify other conversants // - we may need to send various email notifications $feed = new SimplePie(); $feed->set_raw_data($data); $feed->enable_order_by_date(false); $feed->init(); /* // Currently unsupported - needs a lot of work $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' ); if(isset($reloc[0]['child'][NAMESPACE_DFRN])) { $base = $reloc[0]['child'][NAMESPACE_DFRN]; $newloc = array(); $newloc['uid'] = $importer['importer_uid']; $newloc['cid'] = $importer['id']; $newloc['name'] = notags(unxmlify($base['name'][0]['data'])); $newloc['photo'] = notags(unxmlify($base['photo'][0]['data'])); $newloc['url'] = notags(unxmlify($base['url'][0]['data'])); $newloc['request'] = notags(unxmlify($base['request'][0]['data'])); $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data'])); $newloc['notify'] = notags(unxmlify($base['notify'][0]['data'])); $newloc['poll'] = notags(unxmlify($base['poll'][0]['data'])); $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data'])); $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data'])); $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data'])); // TODO // merge with current record, current contents have priority // update record, set url-updated // update profile photos // schedule a scan? } */ // handle friend suggestion notification $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest'); if (isset($sugg[0]['child'][NAMESPACE_DFRN])) { $base = $sugg[0]['child'][NAMESPACE_DFRN]; $fsugg = array(); $fsugg['uid'] = $importer['importer_uid']; $fsugg['cid'] = $importer['id']; $fsugg['name'] = notags(unxmlify($base['name'][0]['data'])); $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data'])); $fsugg['url'] = notags(unxmlify($base['url'][0]['data'])); $fsugg['request'] = notags(unxmlify($base['request'][0]['data'])); $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data'])); // Does our member already have a friend matching this description? $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid'])); if (count($r)) { return 0; } // Do we already have an fcontact record for this person? $fid = 0; $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; // OK, we do. Do we already have an introduction for this person ? $r = q("select id from intro where uid = %d and fid = %d limit 1", intval($fsugg['uid']), intval($fid)); if (count($r)) { return 0; } } if (!$fid) { $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request'])); } $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; } else { return 0; } $hash = random_string(); $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0)); notification(array('type' => NOTIFY_SUGGEST, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $fsugg, 'link' => $a->get_baseurl() . '/notifications/intros', 'source_name' => $importer['name'], 'source_link' => $importer['url'], 'source_photo' => $importer['photo'], 'verb' => ACTIVITY_REQ_FRIEND, 'otype' => 'intro')); return 0; } $ismail = false; $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail'); if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) { logger('local_delivery: private message received'); $ismail = true; $base = $rawmail[0]['child'][NAMESPACE_DFRN]; $msg = array(); $msg['uid'] = $importer['importer_uid']; $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data'])); $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data'])); $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])); $msg['contact-id'] = $importer['id']; $msg['title'] = notags(unxmlify($base['subject'][0]['data'])); $msg['body'] = escape_tags(unxmlify($base['content'][0]['data'])); $msg['seen'] = 0; $msg['replied'] = 0; $msg['uri'] = notags(unxmlify($base['id'][0]['data'])); $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data'])); $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data']))); dbesc_array($msg); $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')"); // send notifications. require_once 'include/enotify.php'; $notif_params = array('type' => NOTIFY_MAIL, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $msg, 'source_name' => $msg['from-name'], 'source_link' => $importer['url'], 'source_photo' => $importer['thumb'], 'verb' => ACTIVITY_POST, 'otype' => 'mail'); notification($notif_params); return 0; // NOTREACHED } $community_page = 0; $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community'); if ($rawtags) { $community_page = intval($rawtags[0]['data']); } if (intval($importer['forum']) != $community_page) { q("update contact set forum = %d where id = %d limit 1", intval($community_page), intval($importer['id'])); $importer['forum'] = (string) $community_page; } logger('local_delivery: feed item count = ' . $feed->get_item_quantity()); // process any deleted entries $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry'); if (is_array($del_entries) && count($del_entries)) { foreach ($del_entries as $dentry) { $deleted = false; if (isset($dentry['attribs']['']['ref'])) { $uri = $dentry['attribs']['']['ref']; $deleted = true; if (isset($dentry['attribs']['']['when'])) { $when = $dentry['attribs']['']['when']; $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s'); } else { $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s'); } } if ($deleted) { $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`\n\t\t\t\t\tWHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1", dbesc($uri), intval($importer['importer_uid']), intval($importer['id'])); if (count($r)) { $item = $r[0]; if ($item['deleted']) { continue; } logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG); if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($item['object'], false); $xt = parse_xml_string($item['target'], false); if ($xt->type === ACTIVITY_OBJ_NOTE) { $i = q("select * from `item` where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (count($i)) { // For tags, the owner cannot remove the tag on the author's copy of the post. $owner_remove = $item['contact-id'] == $i[0]['contact-id'] ? true : false; $author_remove = $item['origin'] && $item['self'] ? true : false; $author_copy = $item['origin'] ? true : false; if ($owner_remove && $author_copy) { continue; } if ($author_remove || $owner_remove) { $tags = explode(',', $i[0]['tag']); $newtags = array(); if (count($tags)) { foreach ($tags as $tag) { if (trim($tag) !== trim($xo->body)) { $newtags[] = trim($tag); } } } q("update item set tag = '%s' where id = %d limit 1", dbesc(implode(',', $newtags)), intval($i[0]['id'])); } } } } if ($item['uri'] == $item['parent-uri']) { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'\n\t\t\t\t\t\t\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['importer_uid'])); } else { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' \n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['importer_uid'])); if ($item['last-child']) { // ensure that last-child is set in case the comment that had it just got wiped. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), dbesc($item['parent-uri']), intval($item['uid'])); // who is the last child now? $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid'])); if (count($r)) { q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id'])); } } } } } } } foreach ($feed->get_items() as $item) { $is_reply = false; $item_id = $item->get_id(); $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to'); if (isset($rawthread[0]['attribs']['']['ref'])) { $is_reply = true; $parent_uri = $rawthread[0]['attribs']['']['ref']; } if ($is_reply) { $community = false; if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) { $sql_extra = ''; $community = true; logger('local_delivery: possible community reply'); } else { $sql_extra = " and contact.self = 1 and item.wall = 1 "; } // was the top-level post for this reply written by somebody on this site? // Specifically, the recipient? $is_a_remote_comment = false; $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, \n\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` \n\t\t\t\tLEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` \n\t\t\t\tWHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'\n\t\t\t\tAND `item`.`uid` = %d \n\t\t\t\t{$sql_extra}\n\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid'])); if ($r && count($r)) { $is_a_remote_comment = true; } // Does this have the characteristics of a community or private group comment? // If it's a reply to a wall post on a community/prvgroup page it's a // valid community comment. Also forum_mode makes it valid for sure. // If neither, it's not. if ($is_a_remote_comment && $community) { if (!$r[0]['forum_mode'] && !$r[0]['wall']) { $is_a_remote_comment = false; logger('local_delivery: not a community reply'); } } if ($is_a_remote_comment) { logger('local_delivery: received remote comment'); $is_like = false; // remote reply to our post. Import and then notify everybody else. $datarray = get_atom_elements($feed, $item); $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { $iid = $r[0]['id']; if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) { logger('received updated comment', LOGGER_DEBUG); $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['importer_uid'])); proc_run('php', "include/notifier.php", "comment-import", $iid); } continue; } // TODO: make this next part work against both delivery threads of a community post // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) { // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); // they won't know what to do so don't report an error. Just quietly die. // return 0; // } // our user with $importer['importer_uid'] is the owner $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1", intval($importer['importer_uid'])); $datarray['type'] = 'remote-comment'; $datarray['wall'] = 1; $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['owner-name'] = $own[0]['name']; $datarray['owner-link'] = $own[0]['url']; $datarray['owner-avatar'] = $own[0]['thumb']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE) { $is_like = true; $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; $datarray['last-child'] = 0; // only one like or dislike per person $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb'])); if ($r && count($r)) { continue; } } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE && $xt->id) { // fetch the parent item $tagp = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (!count($tagp)) { continue; } // extract tag, if not duplicate, and this user allows tags, add to parent item if ($xo->id && $xo->content) { $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]'; if (!stristr($tagp[0]['tag'], $newtag)) { $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid'])); if (count($i) && !intval($i[0]['blocktags'])) { q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1", dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag), intval($tagp[0]['id']), dbesc(datetime_convert())); } } } } } // if($community) { // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]'; // if(! stristr($datarray['tag'],$newtag)) { // if(strlen($datarray['tag'])) // $datarray['tag'] .= ','; // $datarray['tag'] .= $newtag; // } // } $posted_id = item_store($datarray); $parent = 0; if ($posted_id) { $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid'])); if (count($r)) { $parent = $r[0]['parent']; } if (!$is_like) { $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent'])); $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id)); } if ($posted_id && $parent) { proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}"); if (!$is_like && !$importer['self']) { require_once 'include/enotify.php'; notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent)); } } return 0; // NOTREACHED } } else { // regular comment that is part of this total conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) { $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['importer_uid'])); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['importer_uid'])); $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] == ACTIVITY_LIKE || $datarray['verb'] == ACTIVITY_DISLIKE) { $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; // only one like or dislike per person $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb'])); if ($r && count($r)) { continue; } } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE) { $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (!count($r)) { continue; } // extract tag, if not duplicate, add to parent item if ($xo->content) { if (!stristr($r[0]['tag'], trim($xo->content))) { q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id'])); } } } } $posted_id = item_store($datarray); // find out if our user is involved in this conversation and wants to be notified. if (!x($datarray['type']) || $datarray['type'] != 'activity') { $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($parent_uri), intval($importer['importer_uid'])); if (count($myconv)) { $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname']; // first make sure this isn't our own post coming back to us from a wall-to-wall event if (!link_compare($datarray['author-link'], $importer_url)) { foreach ($myconv as $conv) { // now if we find a match, it means we're in this conversation if (!link_compare($conv['author-link'], $importer_url)) { continue; } require_once 'include/enotify.php'; $conv_parent = $conv['parent']; notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $conv_parent)); // only send one notification break; } } } } continue; } } else { // Head post of a conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); if (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) { $ev = bbtoevent($datarray['body']); if (x($ev, 'desc') && x($ev, 'start')) { $ev['cid'] = $importer['id']; $ev['uid'] = $importer['uid']; $ev['uri'] = $item_id; $ev['edited'] = $datarray['edited']; $ev['private'] = $datarray['private']; $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid'])); if (count($r)) { $ev['id'] = $r[0]['id']; } $xyz = event_store($ev); continue; } } $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) { $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['importer_uid'])); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } // This is my contact on another system, but it's really me. // Turn this into a wall post. if ($importer['remote_self']) { $datarray['wall'] = 1; } $datarray['parent-uri'] = $item_id; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; if (!link_compare($datarray['owner-link'], $contact['url'])) { // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, // but otherwise there's a possible data mixup on the sender's system. // the tgroup delivery code called from item_store will correct it if it's a forum, // but we're going to unconditionally correct it here so that the post will always be owned by our contact. logger('local_delivery: Correcting item owner.', LOGGER_DEBUG); $datarray['owner-name'] = $importer['senderName']; $datarray['owner-link'] = $importer['url']; $datarray['owner-avatar'] = $importer['thumb']; } $r = item_store($datarray); continue; } } return 0; // NOTREACHED }
function post_remote($a, $arr) { if ($arr['gravity']) { $arr['gravity'] = intval($arr['gravity']); } elseif ($arr['parent-uri'] == $arr['uri']) { $arr['gravity'] = 0; } elseif ($arr['verb'] == ACTIVITY_POST) { $arr['gravity'] = 6; } if (!x($arr, 'type')) { $arr['type'] = 'remote'; } $arr['wall'] = intval($arr['wall']) ? 1 : 0; $arr['uri'] = notags(trim($arr['uri'])); $arr['author-name'] = notags(trim($arr['author-name'])); $arr['author-link'] = notags(trim($arr['author-link'])); $arr['author-avatar'] = notags(trim($arr['author-avatar'])); $arr['owner-name'] = notags(trim($arr['owner-name'])); $arr['owner-link'] = notags(trim($arr['owner-link'])); $arr['owner-avatar'] = notags(trim($arr['owner-avatar'])); $arr['created'] = datetime_convert('UTC', 'UTC', $arr['created'], 'Y-m-d H:i:s'); $arr['edited'] = datetime_convert('UTC', 'UTC', $arr['edited'], 'Y-m-d H:i:s'); $arr['changed'] = datetime_convert(); $arr['title'] = notags(trim($arr['title'])); $arr['location'] = notags(trim($arr['location'])); $arr['body'] = escape_tags(trim($arr['body'])); $arr['last-child'] = intval($arr['last-child']); $arr['visible'] = 1; $arr['deleted'] = 0; $arr['parent-uri'] = notags(trim($arr['parent-uri'])); $arr['verb'] = notags(trim($arr['verb'])); $arr['object-type'] = notags(trim($arr['object-type'])); $arr['object'] = trim($arr['object']); $parent_id = 0; $parent_missing = false; dbesc_array($arr); $r = q("INSERT INTO `item` (`" . implode("`, `", array_keys($arr)) . "`) VALUES ('" . implode("', '", array_values($arr)) . "')"); $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($arr['parent-uri'])); if (count($r)) { $parent_id = $r[0]['id']; } else { $parent_missing = true; } $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1", $arr['uri']); if (count($r)) { $current_post = $r[0]['id']; } else { return 0; } if ($parent_missing) { // perhaps the parent was deleted, but in any case, this thread is dead // and unfortunately our brand new item now has to be destroyed q("DELETE FROM `item` WHERE `id` = %d LIMIT 1", intval($current_post)); return 0; } $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d LIMIT 1", intval($parent_id), intval($current_post)); return $current_post; }
function import_post(&$a) { $account_id = get_account_id(); if (!$account_id) { return; } $max_identities = account_service_class_fetch($account_id, 'total_identities'); $max_friends = account_service_class_fetch($account_id, 'total_channels'); $max_feeds = account_service_class_fetch($account_id, 'total_feeds'); if ($max_identities !== false) { $r = q("select channel_id from channel where channel_account_id = %d", intval($account_id)); if ($r && count($r) > $max_identities) { notice(sprintf(t('Your service plan only allows %d channels.'), $max_identities) . EOL); return; } } $data = null; $seize = x($_REQUEST, 'make_primary') ? intval($_REQUEST['make_primary']) : 0; $import_posts = x($_REQUEST, 'import_posts') ? intval($_REQUEST['import_posts']) : 0; $src = $_FILES['filename']['tmp_name']; $filename = basename($_FILES['filename']['name']); $filesize = intval($_FILES['filename']['size']); $filetype = $_FILES['filename']['type']; if ($src) { // This is OS specific and could also fail if your tmpdir isn't very large // mostly used for Diaspora which exports gzipped files. if (strpos($filename, '.gz')) { @rename($src, $src . '.gz'); @system('gunzip ' . escapeshellarg($src . '.gz')); } if ($filesize) { $data = @file_get_contents($src); } unlink($src); } if (!$src) { $old_address = x($_REQUEST, 'old_address') ? $_REQUEST['old_address'] : ''; if (!$old_address) { logger('mod_import: nothing to import.'); notice(t('Nothing to import.') . EOL); return; } $email = x($_REQUEST, 'email') ? $_REQUEST['email'] : ''; $password = x($_REQUEST, 'password') ? $_REQUEST['password'] : ''; $channelname = substr($old_address, 0, strpos($old_address, '@')); $servername = substr($old_address, strpos($old_address, '@') + 1); $scheme = 'https://'; $api_path = '/api/red/channel/export/basic?f=&channel=' . $channelname; if ($import_posts) { $api_path .= '&posts=1'; } $binary = false; $redirects = 0; $opts = array('http_auth' => $email . ':' . $password); $url = $scheme . $servername . $api_path; $ret = z_fetch_url($url, $binary, $redirects, $opts); if (!$ret['success']) { $ret = z_fetch_url('http://' . $servername . $api_path, $binary, $redirects, $opts); } if ($ret['success']) { $data = $ret['body']; } else { notice(t('Unable to download data from old server') . EOL); } } if (!$data) { logger('mod_import: empty file.'); notice(t('Imported file is empty.') . EOL); return; } $data = json_decode($data, true); // logger('import: data: ' . print_r($data,true)); // print_r($data); if (array_key_exists('user', $data) && array_key_exists('version', $data)) { require_once 'include/Import/import_diaspora.php'; import_diaspora($data); return; } if (array_key_exists('compatibility', $data) && array_key_exists('database', $data['compatibility'])) { $v1 = substr($data['compatibility']['database'], -4); $v2 = substr(DB_UPDATE_VERSION, -4); if ($data['compatibility']['project'] !== PLATFORM_NAME) { notice(t('The data provided is not compatible with this project.')); return; } } if ($v2 > $v1) { $t = sprintf(t('Warning: Database versions differ by %1$d updates.'), $v2 - $v1); notice($t); } // import channel $channel = $data['channel']; $r = q("select * from channel where (channel_guid = '%s' or channel_hash = '%s' or channel_address = '%s' ) limit 1", dbesc($channel['channel_guid']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'])); // We should probably also verify the hash if ($r) { if ($r[0]['channel_guid'] === $channel['channel_guid'] || $r[0]['channel_hash'] === $channel['channel_hash']) { logger('mod_import: duplicate channel. ', print_r($channel, true)); notice(t('Cannot create a duplicate channel identifier on this system. Import failed.') . EOL); return; } else { // try at most ten times to generate a unique address. $x = 0; $found_unique = false; do { $tmp = $channel['channel_address'] . mt_rand(1000, 9999); $r = q("select * from channel where channel_address = '%s' limit 1", dbesc($tmp)); if (!$r) { $channel['channel_address'] = $tmp; $found_unique = true; break; } $x++; } while ($x < 10); if (!$found_unique) { logger('mod_import: duplicate channel. randomisation failed.', print_r($channel, true)); notice(t('Unable to create a unique channel address. Import failed.') . EOL); return; } } } unset($channel['channel_id']); $channel['channel_account_id'] = get_account_id(); $channel['channel_primary'] = $seize ? 1 : 0; dbesc_array($channel); $r = dbq("INSERT INTO channel (`" . implode("`, `", array_keys($channel)) . "`) VALUES ('" . implode("', '", array_values($channel)) . "')"); if (!$r) { logger('mod_import: channel clone failed. ', print_r($channel, true)); notice(t('Channel clone failed. Import failed.') . EOL); return; } $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", intval(get_account_id()), $channel['channel_guid']); if (!$r) { logger('mod_import: channel not found. ', print_r($channel, true)); notice(t('Cloned channel not found. Import failed.') . EOL); return; } // reset $channel = $r[0]; set_default_login_identity(get_account_id(), $channel['channel_id'], false); if ($data['photo']) { require_once 'include/photo/photo_driver.php'; import_channel_photo(base64url_decode($data['photo']['data']), $data['photo']['type'], get_account_id(), $channel['channel_id']); } $profiles = $data['profile']; if ($profiles) { foreach ($profiles as $profile) { unset($profile['id']); $profile['aid'] = get_account_id(); $profile['uid'] = $channel['channel_id']; // we are going to reset all profile photos to the original // somebody will have to fix this later and put all the applicable photos into the export $profile['photo'] = z_root() . '/photo/profile/l/' . $channel['channel_id']; $profile['thumb'] = z_root() . '/photo/profile/m/' . $channel['channel_id']; dbesc_array($profile); $r = dbq("INSERT INTO profile (`" . implode("`, `", array_keys($profile)) . "`) VALUES ('" . implode("', '", array_values($profile)) . "')"); } } $hublocs = $data['hubloc']; if ($hublocs) { foreach ($hublocs as $hubloc) { $arr = array('guid' => $hubloc['hubloc_guid'], 'guid_sig' => $hubloc['guid_sig'], 'url' => $hubloc['hubloc_url'], 'url_sig' => $hubloc['hubloc_url_sig']); if ($hubloc['hubloc_hash'] === $channel['channel_hash'] && $hubloc['hubloc_flags'] & HUBLOC_FLAGS_PRIMARY && $seize) { $hubloc['hubloc_flags'] = $hubloc['hubloc_flags'] ^ HUBLOC_FLAGS_PRIMARY; } if (!zot_gethub($arr)) { unset($hubloc['hubloc_id']); dbesc_array($hubloc); $r = dbq("INSERT INTO hubloc (`" . implode("`, `", array_keys($hubloc)) . "`) VALUES ('" . implode("', '", array_values($hubloc)) . "')"); } } } // create new hubloc for the new channel at this site $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_flags, \n\t\thubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey )\n\t\tvalues ( '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc($channel['channel_address'] . '@' . get_app()->get_hostname()), dbesc('zot'), intval($seize ? HUBLOC_FLAGS_PRIMARY : 0), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $channel['channel_prvkey']))), dbesc(get_app()->get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system', 'pubkey'))); // reset the original primary hubloc if it is being seized if ($seize) { $r = q("update hubloc set hubloc_flags = (hubloc_flags & ~%d) where (hubloc_flags & %d)>0 and hubloc_hash = '%s' and hubloc_url != '%s' ", intval(HUBLOC_FLAGS_PRIMARY), intval(HUBLOC_FLAGS_PRIMARY), dbesc($channel['channel_hash']), dbesc(z_root())); } // import xchans and contact photos if ($seize) { // replace any existing xchan we may have on this site if we're seizing control $r = q("delete from xchan where xchan_hash = '%s'", dbesc($channel['channel_hash'])); $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", dbesc($channel['channel_hash']), dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_pubkey']), dbesc($a->get_baseurl() . "/photo/profile/l/" . $channel['channel_id']), dbesc($a->get_baseurl() . "/photo/profile/m/" . $channel['channel_id']), dbesc($a->get_baseurl() . "/photo/profile/s/" . $channel['channel_id']), dbesc($channel['channel_address'] . '@' . get_app()->get_hostname()), dbesc(z_root() . '/channel/' . $channel['channel_address']), dbesc(z_root() . '/follow?f=&url=%s'), dbesc(z_root() . '/poco/' . $channel['channel_address']), dbesc($channel['channel_name']), dbesc('zot'), dbesc(datetime_convert()), dbesc(datetime_convert())); } $xchans = $data['xchan']; if ($xchans) { foreach ($xchans as $xchan) { $r = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($xchan['xchan_hash'])); if ($r) { continue; } dbesc_array($xchan); $r = dbq("INSERT INTO xchan (`" . implode("`, `", array_keys($xchan)) . "`) VALUES ('" . implode("', '", array_values($xchan)) . "')"); require_once 'include/photo/photo_driver.php'; $photos = import_profile_photo($xchan['xchan_photo_l'], $xchan['xchan_hash']); if ($photos[4]) { $photodate = NULL_DATE; } else { $photodate = $xchan['xchan_photo_date']; } $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s', xchan_photo_date = '%s'\n\t\t\t\twhere xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($photodate), dbesc($xchan['xchan_hash'])); } } // FIXME - ensure we have an xchan if somebody is trying to pull a fast one $friends = 0; $feeds = 0; // import contacts $abooks = $data['abook']; if ($abooks) { foreach ($abooks as $abook) { if ($max_friends !== false && $friends > $max_friends) { continue; } if ($max_feeds !== false && $abook['abook_flags'] & ABOOK_FLAG_FEED && $feeds > $max_feeds) { continue; } unset($abook['abook_id']); $abook['abook_account'] = get_account_id(); $abook['abook_channel'] = $channel['channel_id']; dbesc_array($abook); $r = dbq("INSERT INTO abook (`" . implode("`, `", array_keys($abook)) . "`) VALUES ('" . implode("', '", array_values($abook)) . "')"); $friends++; if ($abook['abook_flags'] & ABOOK_FLAG_FEED) { $feeds++; } } } $configs = $data['config']; if ($configs) { foreach ($configs as $config) { unset($config['id']); $config['uid'] = $channel['channel_id']; dbesc_array($config); $r = dbq("INSERT INTO pconfig (`" . implode("`, `", array_keys($config)) . "`) VALUES ('" . implode("', '", array_values($config)) . "')"); } } $groups = $data['group']; if ($groups) { $saved = array(); foreach ($groups as $group) { $saved[$group['hash']] = array('old' => $group['id']); unset($group['id']); $group['uid'] = $channel['channel_id']; dbesc_array($group); $r = dbq("INSERT INTO groups (`" . implode("`, `", array_keys($group)) . "`) VALUES ('" . implode("', '", array_values($group)) . "')"); } $r = q("select * from `groups` where uid = %d", intval($channel['channel_id'])); if ($r) { foreach ($r as $rr) { $saved[$rr['hash']]['new'] = $rr['id']; } } } $group_members = $data['group_member']; if ($group_members) { foreach ($group_members as $group_member) { unset($group_member['id']); $group_member['uid'] = $channel['channel_id']; foreach ($saved as $x) { if ($x['old'] == $group_member['gid']) { $group_member['gid'] = $x['new']; } } dbesc_array($group_member); $r = dbq("INSERT INTO group_member (`" . implode("`, `", array_keys($group_member)) . "`) VALUES ('" . implode("', '", array_values($group_member)) . "')"); } } $saved_notification_flags = notifications_off($channel['channel_id']); if ($import_posts && array_key_exists('item', $data) && $data['item']) { foreach ($data['item'] as $i) { $item = get_item_elements($i); $r = q("select id, edited from item where mid = '%s' and uid = %d limit 1", dbesc($item['mid']), intval($channel['channel_id'])); if ($r) { if ($item['edited'] > $r[0]['edited']) { $item['id'] = $r[0]['id']; $item['uid'] = $channel['channel_id']; item_store_update($item); continue; } } else { $item['aid'] = $channel['channel_account_id']; $item['uid'] = $channel['channel_id']; $item_result = item_store($item); } } } notifications_on($channel['channel_id'], $saved_notification_flags); if (array_key_exists('item_id', $data) && $data['item_id']) { foreach ($data['item_id'] as $i) { $r = q("select id from item where mid = '%s' and uid = %d limit 1", dbesc($i['mid']), intval($channel['channel_id'])); if (!$r) { continue; } $z = q("select * from item_id where service = '%s' and sid = '%s' and iid = %d and uid = %d limit 1", dbesc($i['service']), dbesc($i['sid']), intval($r[0]['id']), intval($channel['channel_id'])); if (!$z) { q("insert into item_id (iid,uid,sid,service) values(%d,%d,'%s','%s')", intval($r[0]['id']), intval($channel['channel_id']), dbesc($i['sid']), dbesc($i['service'])); } } } // FIXME - ensure we have a self entry if somebody is trying to pull a fast one // send out refresh requests // notify old server that it may no longer be primary. proc_run('php', 'include/notifier.php', 'location', $channel['channel_id']); // This will indirectly perform a refresh_all *and* update the directory proc_run('php', 'include/directory.php', $channel['channel_id']); notice(t('Import completed.') . EOL); change_channel($channel['channel_id']); goaway(z_root() . '/network'); }
function local_delivery($importer, $data) { $a = get_app(); if ($importer['readonly']) { // We aren't receiving stuff from this person. But we will quietly ignore them // rather than a blatant "go away" message. logger('local_delivery: ignoring'); return 0; //NOTREACHED } // Consume notification feed. This may differ from consuming a public feed in several ways // - might contain email or friend suggestions // - might contain remote followup to our message // - in which case we need to accept it and then notify other conversants // - we may need to send various email notifications $feed = new SimplePie(); $feed->set_raw_data($data); $feed->enable_order_by_date(false); $feed->init(); $reloc = $feed->get_feed_tags(NAMESPACE_DFRN, 'relocate'); if (isset($reloc[0]['child'][NAMESPACE_DFRN])) { $base = $reloc[0]['child'][NAMESPACE_DFRN]; $newloc = array(); $newloc['uid'] = $importer['importer_uid']; $newloc['cid'] = $importer['id']; $newloc['name'] = notags(unxmlify($base['name'][0]['data'])); $newloc['photo'] = notags(unxmlify($base['photo'][0]['data'])); $newloc['url'] = notags(unxmlify($base['url'][0]['data'])); $newloc['request'] = notags(unxmlify($base['request'][0]['data'])); $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data'])); $newloc['notify'] = notags(unxmlify($base['notify'][0]['data'])); $newloc['poll'] = notags(unxmlify($base['poll'][0]['data'])); $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data'])); $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data'])); $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data'])); // TODO // merge with current record, current contents have priority // update record, set url-updated // update profile photos // schedule a scan? } // handle friend suggestion notification $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest'); if (isset($sugg[0]['child'][NAMESPACE_DFRN])) { $base = $sugg[0]['child'][NAMESPACE_DFRN]; $fsugg = array(); $fsugg['uid'] = $importer['importer_uid']; $fsugg['cid'] = $importer['id']; $fsugg['name'] = notags(unxmlify($base['name'][0]['data'])); $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data'])); $fsugg['url'] = notags(unxmlify($base['url'][0]['data'])); $fsugg['request'] = notags(unxmlify($base['request'][0]['data'])); $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data'])); // Does our member already have a friend matching this description? $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid'])); if (count($r)) { return 0; } // Do we already have an fcontact record for this person? $fid = 0; $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; } if (!$fid) { $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request'])); } $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; } else { return 0; } $hash = random_string(); $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0)); // TODO - send email notify (which may require a new notification preference) return 0; } $ismail = false; $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail'); if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) { logger('local_delivery: private message received'); $ismail = true; $base = $rawmail[0]['child'][NAMESPACE_DFRN]; $msg = array(); $msg['uid'] = $importer['importer_uid']; $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data'])); $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data'])); $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])); $msg['contact-id'] = $importer['id']; $msg['title'] = notags(unxmlify($base['subject'][0]['data'])); $msg['body'] = escape_tags(unxmlify($base['content'][0]['data'])); $msg['seen'] = 0; $msg['replied'] = 0; $msg['uri'] = notags(unxmlify($base['id'][0]['data'])); $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data'])); $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data']))); dbesc_array($msg); $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')"); // send email notification if requested. require_once 'bbcode.php'; if ($importer['notify-flags'] & NOTIFY_MAIL) { push_lang($importer['language']); // name of the automated email sender $msg['notificationfromname'] = t('Administrator'); // noreply address to send from $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname(); // text version // process the message body to display properly in text mode // 1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character) // 2) remove escape slashes // 3) decode any bbcode from the message editor // 4) decode any encoded html tags // 5) remove html tags $msg['textversion'] = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n", $msg['body']))), ENT_QUOTES, 'UTF-8')); // html version // process the message body to display properly in text mode // 1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character) // 2) remove escape slashes // 3) decode any bbcode from the message editor // 4) decode any encoded html tags $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $msg['body'])))); // load the template for private message notifications $tpl = get_intltext_template('mail_received_html_body_eml.tpl'); $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$siteName' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $importer['thumb'], '$email' => $importer['email'], '$url' => $importer['url'], '$from' => $msg['from-name'], '$title' => stripslashes($msg['title']), '$htmlversion' => $msg['htmlversion'], '$mimeboundary' => $msg['mimeboundary'], '$hostname' => $a->get_hostname())); // load the template for private message notifications $tpl = get_intltext_template('mail_received_text_body_eml.tpl'); $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$siteName' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $importer['thumb'], '$email' => $importer['email'], '$url' => $importer['url'], '$from' => $msg['from-name'], '$title' => stripslashes($msg['title']), '$textversion' => $msg['textversion'], '$mimeboundary' => $msg['mimeboundary'], '$hostname' => $a->get_hostname())); // use the EmailNotification library to send the message require_once "include/EmailNotification.php"; EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], $msg['notificationfromemail'], $msg['notificationfromemail'], $importer['email'], t('New mail received at ') . $a->config['sitename'], $email_html_body_tpl, $email_text_body_tpl); pop_lang(); } return 0; // NOTREACHED } logger('local_delivery: feed item count = ' . $feed->get_item_quantity()); // process any deleted entries $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry'); if (is_array($del_entries) && count($del_entries)) { foreach ($del_entries as $dentry) { $deleted = false; if (isset($dentry['attribs']['']['ref'])) { $uri = $dentry['attribs']['']['ref']; $deleted = true; if (isset($dentry['attribs']['']['when'])) { $when = $dentry['attribs']['']['when']; $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s'); } else { $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s'); } } if ($deleted) { $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`\n\t\t\t\t\tWHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1", dbesc($uri), intval($importer['importer_uid']), intval($importer['id'])); if (count($r)) { $item = $r[0]; if ($item['deleted']) { continue; } logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG); if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTVITY_OBJ_TAGTERM) { $xo = parse_xml_string($item['object'], false); $xt = parse_xml_string($item['target'], false); if ($xt->type === ACTIVITY_OBJ_NOTE) { $i = q("select * from `item` where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (count($i)) { // For tags, the owner cannot remove the tag on the author's copy of the post. $owner_remove = $item['contact-id'] == $i[0]['contact-id'] ? true : false; $author_remove = $item['origin'] && $item['self'] ? true : false; $author_copy = $item['origin'] ? true : false; if ($owner_remove && $author_copy) { continue; } if ($author_remove || $owner_remove) { $tags = explode(',', $i[0]['tag']); $newtags = array(); if (count($tags)) { foreach ($tags as $tag) { if (trim($tag) !== trim($xo->body)) { $newtags[] = trim($tag); } } } q("update item set tag = '%s' where id = %d limit 1", dbesc(implode(',', $newtags)), intval($i[0]['id'])); } } } } if ($item['uri'] == $item['parent-uri']) { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'\n\t\t\t\t\t\t\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['importer_uid'])); } else { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' \n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['importer_uid'])); if ($item['last-child']) { // ensure that last-child is set in case the comment that had it just got wiped. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), dbesc($item['parent-uri']), intval($item['uid'])); // who is the last child now? $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid'])); if (count($r)) { q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id'])); } } } } } } } foreach ($feed->get_items() as $item) { $is_reply = false; $item_id = $item->get_id(); $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to'); if (isset($rawthread[0]['attribs']['']['ref'])) { $is_reply = true; $parent_uri = $rawthread[0]['attribs']['']['ref']; } if ($is_reply) { $community = false; if ($importer['page-flags'] == PAGE_COMMUNITY) { $sql_extra = ''; $community = true; logger('local_delivery: community reply'); } else { $sql_extra = " and contact.self = 1 and item.wall = 1 "; } // was the top-level post for this reply written by somebody on this site? // Specifically, the recipient? $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, \n\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` \n\t\t\t\tLEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` \n\t\t\t\tWHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'\n\t\t\t\tAND `item`.`uid` = %d \n\t\t\t\t{$sql_extra}\n\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid'])); if ($r && count($r)) { logger('local_delivery: received remote comment'); $is_like = false; // remote reply to our post. Import and then notify everybody else. $datarray = get_atom_elements($feed, $item); // TODO: make this next part work against both delivery threads of a community post // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) { // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); // they won't know what to do so don't report an error. Just quietly die. // return 0; // } $datarray['type'] = 'remote-comment'; $datarray['wall'] = 1; $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['owner-name'] = $r[0]['name']; $datarray['owner-link'] = $r[0]['url']; $datarray['owner-avatar'] = $r[0]['thumb']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE) { $is_like = true; $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; $datarray['last-child'] = 0; } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE && $xt->id == $r[0]['uri']) { // extract tag, if not duplicate, and this user allows tags, add to parent item if ($xo->id && $xo->content) { $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]'; if (!stristr($r[0]['tag'], $newtag)) { $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid'])); if (count($i) && !$i[0]['blocktags']) { q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag), intval($r[0]['id'])); } } } } } // if($community) { // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]'; // if(! stristr($datarray['tag'],$newtag)) { // if(strlen($datarray['tag'])) // $datarray['tag'] .= ','; // $datarray['tag'] .= $newtag; // } // } $posted_id = item_store($datarray); $parent = 0; if ($posted_id) { $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid'])); if (count($r)) { $parent = $r[0]['parent']; } if (!$is_like) { $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent'])); $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id)); } if ($posted_id && $parent) { proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}"); if (!$is_like && $importer['notify-flags'] & NOTIFY_COMMENT && !$importer['self']) { push_lang($importer['language']); require_once 'bbcode.php'; $from = stripslashes($datarray['author-name']); // name of the automated email sender $msg['notificationfromname'] = stripslashes($datarray['author-name']); // noreply address to send from $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname(); // text version // process the message body to display properly in text mode $msg['textversion'] = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8'); // html version // process the message body to display properly in text mode $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $datarray['body'])))); $imgtouse = link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar']; // load the template for private message notifications $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl'); $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$email' => $importer['email'], '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['htmlversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id)); // load the template for private message notifications $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl'); $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$email' => $importer['email'], '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['textversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id)); // use the EmailNotification library to send the message require_once "include/EmailNotification.php"; EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], t("Administrator") . '@' . $a->get_hostname(), t("noreply") . '@' . $a->get_hostname(), $importer['email'], sprintf(t('%s commented on an item at %s'), $from, $a->config['sitename']), $email_html_body_tpl, $email_text_body_tpl); pop_lang(); } } return 0; // NOTREACHED } } else { // regular comment that is part of this total conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) { $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['body']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['importer_uid'])); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['importer_uid'])); $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] == ACTIVITY_LIKE || $datarray['verb'] == ACTIVITY_DISLIKE) { $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE) { $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (!count($r)) { continue; } // extract tag, if not duplicate, add to parent item if ($xo->content) { if (!stristr($r[0]['tag'], trim($xo->content))) { q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id'])); } } } } $posted_id = item_store($datarray); // find out if our user is involved in this conversation and wants to be notified. if ($datarray['type'] != 'activity' && $importer['notify-flags'] & NOTIFY_COMMENT) { $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ", dbesc($parent_uri), intval($importer['importer_uid'])); if (count($myconv)) { $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname']; foreach ($myconv as $conv) { if (!link_compare($conv['author-link'], $importer_url)) { continue; } push_lang($importer['language']); require_once 'bbcode.php'; $from = stripslashes($datarray['author-name']); // name of the automated email sender $msg['notificationfromname'] = stripslashes($datarray['author-name']); // noreply address to send from $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname(); // text version // process the message body to display properly in text mode $msg['textversion'] = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8'); // html version // process the message body to display properly in text mode $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $datarray['body'])))); $imgtouse = link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar']; // load the template for private message notifications $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl'); $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['htmlversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id)); // load the template for private message notifications $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl'); $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['textversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id)); // use the EmailNotification library to send the message require_once "include/EmailNotification.php"; EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], t("Administrator@") . $a->get_hostname(), t("noreply") . '@' . $a->get_hostname(), $importer['email'], sprintf(t('%s commented on an item at %s'), $from, $a->config['sitename']), $email_html_body_tpl, $email_text_body_tpl); pop_lang(); break; } } } continue; } } else { // Head post of a conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); if (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) { $ev = bbtoevent($datarray['body']); if (x($ev, 'desc') && x($ev, 'start')) { $ev['cid'] = $importer['id']; $ev['uid'] = $importer['uid']; $ev['uri'] = $item_id; $ev['edited'] = $datarray['edited']; $ev['private'] = $datarray['private']; $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid'])); if (count($r)) { $ev['id'] = $r[0]['id']; } $xyz = event_store($ev); continue; } } $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) { $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['body']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['importer_uid'])); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } // This is my contact on another system, but it's really me. // Turn this into a wall post. if ($contact['remote_self']) { $datarray['wall'] = 1; } $datarray['parent-uri'] = $item_id; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; $r = item_store($datarray); continue; } } return 0; // NOTREACHED }
function post_remote($a, $arr) { if (!x($arr, 'type')) { $arr['type'] = 'remote'; } $arr['uri'] = notags(trim($arr['uri'])); $arr['author-name'] = notags(trim($arr['author-name'])); $arr['author-link'] = notags(trim($arr['author-link'])); $arr['author-avatar'] = notags(trim($arr['author-avatar'])); $arr['owner-name'] = notags(trim($arr['owner-name'])); $arr['owner-link'] = notags(trim($arr['owner-link'])); $arr['owner-avatar'] = notags(trim($arr['owner-avatar'])); $arr['created'] = datetime_convert('UTC', 'UTC', $arr['created'], 'Y-m-d H:i:s'); $arr['edited'] = datetime_convert('UTC', 'UTC', $arr['edited'], 'Y-m-d H:i:s'); $arr['title'] = notags(trim($arr['title'])); $arr['body'] = escape_tags(trim($arr['body'])); $arr['last-child'] = intval($arr['last-child']); $arr['visible'] = 1; $arr['deleted'] = 0; $arr['parent-uri'] = notags(trim($arr['parent-uri'])); $parent_id = 0; dbesc_array($arr); $r = q("INSERT INTO `item` (`" . implode("`, `", array_keys($arr)) . "`) VALUES ('" . implode("', '", array_values($arr)) . "')"); $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($arr['parent-uri'])); if (count($r)) { $parent_id = $r[0]['id']; } else { // if parent is missing, what do we do? } $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1", $arr['uri']); if (count($r)) { $current_post = $r[0]['id']; } $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d LIMIT 1", intval($parent_id), intval($current_post)); return $current_post; }
function import_likes($channel, $likes) { if ($channel && $likes) { foreach ($likes as $like) { if ($like['deleted']) { q("delete from likes where liker = '%s' and likee = '%s' and verb = '%s' and target_type = '%s' and target_id = '%s'", dbesc($like['liker']), dbesc($like['likee']), dbesc($like['verb']), dbesc($like['target_type']), dbesc($like['target_id'])); continue; } unset($like['id']); unset($like['iid']); $like['channel_id'] = $channel['channel_id']; $r = q("select * from likes where liker = '%s' and likee = '%s' and verb = '%s' and target_type = '%s' and target_id = '%s' and i_mid = '%s'", dbesc($like['liker']), dbesc($like['likee']), dbesc($like['verb']), dbesc($like['target_type']), dbesc($like['target_id']), dbesc($like['i_mid'])); if ($r) { continue; } dbesc_array($config); $r = dbq("INSERT INTO likes (`" . implode("`, `", array_keys($like)) . "`) VALUES ('" . implode("', '", array_values($like)) . "')"); } } }
function run_submit($url) { global $a; if (!strlen($url)) { return false; } logger('Updating: ' . $url); //First run a notice script for the site it is hosted on. $site_health = notice_site($url, true); $submit_start = microtime(true); $nurl = str_replace(array('https:', '//www.'), array('http:', '//'), $url); $profile_exists = false; $r = q("SELECT * FROM `profile` WHERE ( `homepage` = '%s' OR `nurl` = '%s' )", dbesc($url), dbesc($nurl)); if (count($r)) { $profile_exists = true; $profile_id = $r[0]['id']; } //Remove duplicates. if (count($r) > 1) { for ($i = 1; $i < count($r); $i++) { logger('Removed duplicate profile ' . intval($r[$i]['id'])); q("DELETE FROM `photo` WHERE `profile-id` = %d LIMIT 1", intval($r[$i]['id'])); q("DELETE FROM `profile` WHERE `id` = %d LIMIT 1", intval($r[$i]['id'])); } } require_once 'Scrape.php'; //Skip the scrape? :D $noscrape = $site_health && $site_health['no_scrape_url']; if ($noscrape) { //Find out who to look up. $which = str_replace($site_health['base_url'], '', $url); $noscrape = preg_match('~/profile/([^/]+)~', $which, $matches) === 1; //If that did not fail... if ($noscrape) { $parms = noscrape_dfrn($site_health['no_scrape_url'] . '/' . $matches[1]); $noscrape = !!$parms; //If the result was false, do a scrape after all. } } if (!$noscrape) { $parms = scrape_dfrn($url); } //Empty result is due to an offline site. if (!count($parms)) { //For large sites this could lower the health too quickly, so don't track health. //But for sites that are already in bad status. Do a cleanup now. if ($profile_exists && $site_health['health_score'] < $a->config['maintenance']['remove_profile_health_threshold']) { logger('Nuked bad health record.'); nuke_record($url); } return false; } elseif ($parms['explicit-hide'] && $profile_exists) { logger('User opted out of the directory.'); nuke_record($url); return true; //This is a good update. } elseif (validate_dfrn($parms)) { return false; } if (x($parms, 'hide') || !x($parms, 'fn') && x($parms, 'photo')) { if ($profile_exists) { nuke_record($url); } return true; //This is a good update. } $photo = $parms['photo']; dbesc_array($parms); if (x($parms, 'comm')) { $parms['comm'] = intval($parms['comm']); } if ($profile_exists) { $r = q("UPDATE `profile` SET \n\t\t\t`name` = '%s', \n\t\t\t`pdesc` = '%s',\n\t\t\t`locality` = '%s', \n\t\t\t`region` = '%s', \n\t\t\t`postal-code` = '%s', \n\t\t\t`country-name` = '%s', \n\t\t\t`gender` = '%s', \n\t\t\t`marital` = '%s', \n\t\t\t`homepage` = '%s',\n\t\t\t`nurl` = '%s',\n\t\t\t`comm` = %d,\n\t\t\t`tags` = '%s',\n\t\t\t`updated` = '%s' \n\t\t\tWHERE `id` = %d LIMIT 1", $parms['fn'], $parms['pdesc'], $parms['locality'], $parms['region'], $parms['postal-code'], $parms['country-name'], $parms['gender'], $parms['marital'], dbesc($url), dbesc($nurl), intval($parms['comm']), $parms['tags'], dbesc(datetime_convert()), intval($profile_id)); logger('Update returns: ' . $r); } else { $r = q("INSERT INTO `profile` ( `name`, `pdesc`, `locality`, `region`, `postal-code`, `country-name`, `gender`, `marital`, `homepage`, `nurl`, `comm`, `tags`, `created`, `updated` )\n\t\t\tVALUES ( '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s' )", $parms['fn'], $parms['pdesc'], $parms['locality'], $parms['region'], $parms['postal-code'], $parms['country-name'], $parms['gender'], $parms['marital'], dbesc($url), dbesc($nurl), intval($parms['comm']), $parms['tags'], dbesc(datetime_convert()), dbesc(datetime_convert())); logger('Insert returns: ' . $r); $r = q("SELECT `id` FROM `profile` WHERE ( `homepage` = '%s' or `nurl` = '%s' ) order by id asc", dbesc($url), dbesc($nurl)); if (count($r)) { $profile_id = $r[count($r) - 1]['id']; } if (count($r) > 1) { q("DELETE FROM `photo` WHERE `profile-id` = %d LIMIT 1", intval($r[0]['id'])); q("DELETE FROM `profile` WHERE `id` = %d LIMIT 1", intval($r[0]['id'])); } } if ($parms['tags']) { $arr = explode(' ', $parms['tags']); if (count($arr)) { foreach ($arr as $t) { $t = strip_tags(trim($t)); $t = substr($t, 0, 254); if (strlen($t)) { $r = q("SELECT `id` FROM `tag` WHERE `term` = '%s' and `nurl` = '%s' LIMIT 1", dbesc($t), dbesc($nurl)); if (!count($r)) { $r = q("INSERT INTO `tag` (`term`, `nurl`) VALUES ('%s', '%s') ", dbesc($t), dbesc($nurl)); } } } } } $submit_photo_start = microtime(true); require_once "Photo.php"; $photo_failure = false; $status = false; if ($profile_id) { $img_str = fetch_url($photo, true); $img = new Photo($img_str); if ($img) { $img->scaleImageSquare(80); $r = $img->store($profile_id); } $r = q("UPDATE `profile` SET `photo` = '%s' WHERE `id` = %d LIMIT 1", dbesc($a->get_baseurl() . '/photo/' . $profile_id . '.jpg'), intval($profile_id)); $status = true; } else { nuke_record($url); return false; } $submit_end = microtime(true); $photo_time = round(($submit_end - $submit_photo_start) * 1000); $time = round(($submit_end - $submit_start) * 1000); //Record the scrape speed in a scrapes table. if ($site_health && $status) { q("INSERT INTO `site-scrape` (`site_health_id`, `dt_performed`, `request_time`, `scrape_time`, `photo_time`, `total_time`)" . "VALUES (%u, NOW(), %u, %u, %u, %u)", $site_health['id'], $parms['_timings']['fetch'], $parms['_timings']['scrape'], $photo_time, $time); } return $status; }
function dfrn_request_post(&$a) { if ($a->argc != 2 || !count($a->profile)) { return; } if ($_POST['cancel']) { goaway(z_root()); } /** * * Scenario 2: We've introduced ourself to another cell, then have been returned to our own cell * to confirm the request, and then we've clicked submit (perhaps after logging in). * That brings us here: * */ if (x($_POST, 'localconfirm') && $_POST['localconfirm'] == 1) { /** * Ensure this is a valid request */ if (local_user() && $a->user['nickname'] == $a->argv[1] && x($_POST, 'dfrn_url')) { $dfrn_url = notags(trim($_POST['dfrn_url'])); $aes_allow = x($_POST, 'aes_allow') && $_POST['aes_allow'] == 1 ? 1 : 0; $confirm_key = x($_POST, 'confirm_key') ? $_POST['confirm_key'] : ""; $contact_record = null; if (x($dfrn_url)) { /** * Lookup the contact based on their URL (which is the only unique thing we have at the moment) */ $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", intval(local_user()), dbesc($dfrn_url)); if (count($r)) { if (strlen($r[0]['dfrn-id'])) { /** * We don't need to be here. It has already happened. */ notice(t("This introduction has already been accepted.") . EOL); return; } else { $contact_record = $r[0]; } } if (is_array($contact_record)) { $r = q("UPDATE `contact` SET `ret-aes` = %d WHERE `id` = %d LIMIT 1", intval($aes_allow), intval($contact_record['id'])); } else { /** * Scrape the other site's profile page to pick up the dfrn links, key, fn, and photo */ require_once 'Scrape.php'; $parms = scrape_dfrn($dfrn_url); if (!count($parms)) { notice(t('Profile location is not valid or does not contain profile information.') . EOL); return; } else { if (!x($parms, 'fn')) { notice(t('Warning: profile location has no identifiable owner name.') . EOL); } if (!x($parms, 'photo')) { notice(t('Warning: profile location has no profile photo.') . EOL); } $invalid = validate_dfrn($parms); if ($invalid) { notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL); return; } } $dfrn_request = $parms['dfrn-request']; /********* Escape the entire array ********/ dbesc_array($parms); /******************************************/ /** * Create a contact record on our site for the other person */ $r = q("INSERT INTO `contact` ( `uid`, `created`,`url`, `nurl`, `name`, `nick`, `photo`, `site-pubkey`,\n\t\t\t\t\t\t`request`, `confirm`, `notify`, `poll`, `poco`, `network`, `aes_allow`) \n\t\t\t\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)", intval(local_user()), datetime_convert(), dbesc($dfrn_url), dbesc(normalise_link($dfrn_url)), $parms['fn'], $parms['nick'], $parms['photo'], $parms['key'], $parms['dfrn-request'], $parms['dfrn-confirm'], $parms['dfrn-notify'], $parms['dfrn-poll'], $parms['dfrn-poco'], dbesc(NETWORK_DFRN), intval($aes_allow)); } if ($r) { info(t("Introduction complete.") . EOL); } /** * Allow the blocked remote notification to complete */ if (is_array($contact_record)) { $dfrn_request = $contact_record['request']; } if (strlen($dfrn_request) && strlen($confirm_key)) { $s = fetch_url($dfrn_request . '?confirm_key=' . $confirm_key); } // (ignore reply, nothing we can do it failed) goaway($dfrn_url); return; // NOTREACHED } } // invalid/bogus request notice(t('Unrecoverable protocol error.') . EOL); goaway(z_root()); return; // NOTREACHED } /** * Otherwise: * * Scenario 1: * We are the requestee. A person from a remote cell has made an introduction * on our profile web page and clicked submit. We will use their DFRN-URL to * figure out how to contact their cell. * * Scrape the originating DFRN-URL for everything we need. Create a contact record * and an introduction to show our user next time he/she logs in. * Finally redirect back to the requestor so that their site can record the request. * If our user (the requestee) later confirms this request, a record of it will need * to exist on the requestor's cell in order for the confirmation process to complete.. * * It's possible that neither the requestor or the requestee are logged in at the moment, * and the requestor does not yet have any credentials to the requestee profile. * * Who is the requestee? We've already loaded their profile which means their nickname should be * in $a->argv[1] and we should have their complete info in $a->profile. * */ if (!(is_array($a->profile) && count($a->profile))) { notice(t('Profile unavailable.') . EOL); return; } $nickname = $a->profile['nickname']; $notify_flags = $a->profile['notify-flags']; $uid = $a->profile['uid']; $maxreq = intval($a->profile['maxreq']); $contact_record = null; $failed = false; $parms = null; if (x($_POST, 'dfrn_url')) { /** * Block friend request spam */ if ($maxreq) { $r = q("SELECT * FROM `intro` WHERE `datetime` > '%s' AND `uid` = %d", dbesc(datetime_convert('UTC', 'UTC', 'now - 24 hours')), intval($uid)); if (count($r) > $maxreq) { notice(sprintf(t('%s has received too many connection requests today.'), $a->profile['name']) . EOL); notice(t('Spam protection measures have been invoked.') . EOL); notice(t('Friends are advised to please try again in 24 hours.') . EOL); return; } } /** * * Cleanup old introductions that remain blocked. * Also remove the contact record, but only if there is no existing relationship * Do not remove email contacts as these may be awaiting email verification */ $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel` \n\t\t\tFROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`\n\t\t\tWHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 \n\t\t\tAND `contact`.`network` != '%s'\n\t\t\tAND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 30 MINUTE ", dbesc(NETWORK_MAIL)); if (count($r)) { foreach ($r as $rr) { if (!$rr['rel']) { q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1", intval($rr['cid'])); } q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($rr['iid'])); } } /** * * Cleanup any old email intros - which will have a greater lifetime */ $r = q("SELECT `intro`.*, `intro`.`id` AS `iid`, `contact`.`id` AS `cid`, `contact`.`rel` \n\t\t\tFROM `intro` LEFT JOIN `contact` on `intro`.`contact-id` = `contact`.`id`\n\t\t\tWHERE `intro`.`blocked` = 1 AND `contact`.`self` = 0 \n\t\t\tAND `contact`.`network` = '%s'\n\t\t\tAND `intro`.`datetime` < UTC_TIMESTAMP() - INTERVAL 3 DAY ", dbesc(NETWORK_MAIL)); if (count($r)) { foreach ($r as $rr) { if (!$rr['rel']) { q("DELETE FROM `contact` WHERE `id` = %d LIMIT 1", intval($rr['cid'])); } q("DELETE FROM `intro` WHERE `id` = %d LIMIT 1", intval($rr['iid'])); } } $url = trim($_POST['dfrn_url']); if (!strlen($url)) { notice(t("Invalid locator") . EOL); return; } // Canonicalise email-style profile locator $hcard = ''; $url = webfinger_dfrn($url, $hcard); if (substr($url, 0, 5) === 'stat:') { $network = NETWORK_OSTATUS; $url = substr($url, 5); } else { $network = NETWORK_DFRN; } logger('dfrn_request: url: ' . $url); if (!strlen($url)) { notice(t("Unable to resolve your name at the provided location.") . EOL); return; } if ($network === NETWORK_DFRN) { $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", intval($uid), dbesc($url)); if (count($ret)) { if (strlen($ret[0]['issued-id'])) { notice(t('You have already introduced yourself here.') . EOL); return; } elseif ($ret[0]['rel'] == CONTACT_IS_FRIEND) { notice(sprintf(t('Apparently you are already friends with %s.'), $a->profile['name']) . EOL); return; } else { $contact_record = $ret[0]; $parms = array('dfrn-request' => $ret[0]['request']); } } $issued_id = random_string(); if (is_array($contact_record)) { // There is a contact record but no issued-id, so this // is a reciprocal introduction from a known contact $r = q("UPDATE `contact` SET `issued-id` = '%s' WHERE `id` = %d LIMIT 1", dbesc($issued_id), intval($contact_record['id'])); } else { if (!validate_url($url)) { notice(t('Invalid profile URL.') . EOL); goaway($a->get_baseurl() . '/' . $a->cmd); return; // NOTREACHED } if (!allowed_url($url)) { notice(t('Disallowed profile URL.') . EOL); goaway($a->get_baseurl() . '/' . $a->cmd); return; // NOTREACHED } require_once 'Scrape.php'; $parms = scrape_dfrn($hcard ? $hcard : $url); if (!count($parms)) { notice(t('Profile location is not valid or does not contain profile information.') . EOL); goaway($a->get_baseurl() . '/' . $a->cmd); } else { if (!x($parms, 'fn')) { notice(t('Warning: profile location has no identifiable owner name.') . EOL); } if (!x($parms, 'photo')) { notice(t('Warning: profile location has no profile photo.') . EOL); } $invalid = validate_dfrn($parms); if ($invalid) { notice(sprintf(tt("%d required parameter was not found at the given location", "%d required parameters were not found at the given location", $invalid), $invalid) . EOL); return; } } $parms['url'] = $url; $parms['issued-id'] = $issued_id; dbesc_array($parms); $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`,`name`, `nick`, `issued-id`, `photo`, `site-pubkey`,\n\t\t\t\t\t`request`, `confirm`, `notify`, `poll`, `poco`, `network` )\n\t\t\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )", intval($uid), dbesc(datetime_convert()), $parms['url'], dbesc(normalise_link($parms['url'])), $parms['fn'], $parms['nick'], $parms['issued-id'], $parms['photo'], $parms['key'], $parms['dfrn-request'], $parms['dfrn-confirm'], $parms['dfrn-notify'], $parms['dfrn-poll'], $parms['dfrn-poco'], dbesc(NETWORK_DFRN)); // find the contact record we just created if ($r) { $r = q("SELECT `id` FROM `contact` \n\t\t\t\t\t\tWHERE `uid` = %d AND `url` = '%s' AND `issued-id` = '%s' LIMIT 1", intval($uid), $parms['url'], $parms['issued-id']); if (count($r)) { $contact_record = $r[0]; } } } if ($r === false) { notice(t('Failed to update contact record.') . EOL); return; } $hash = random_string() . (string) time(); // Generate a confirm_key if (is_array($contact_record)) { $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)\n\t\t\t\t\tVALUES ( %d, %d, 1, %d, '%s', '%s', '%s' )", intval($uid), intval($contact_record['id']), x($_POST, 'knowyou') && $_POST['knowyou'] == 1 ? 1 : 0, dbesc(notags(trim($_POST['dfrn-request-message']))), dbesc($hash), dbesc(datetime_convert())); } // This notice will only be seen by the requestor if the requestor and requestee are on the same server. if (!$failed) { info(t('Your introduction has been sent.') . EOL); } // "Homecoming" - send the requestor back to their site to record the introduction. $dfrn_url = bin2hex($a->get_baseurl() . '/profile/' . $nickname); $aes_allow = function_exists('openssl_encrypt') ? 1 : 0; goaway($parms['dfrn-request'] . "?dfrn_url={$dfrn_url}" . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&confirm_key=' . $hash . ($aes_allow ? "&aes_allow=1" : "")); // NOTREACHED // END $network === NETWORK_DFRN } elseif ($network === NETWORK_OSTATUS) { /** * * OStatus network * Check contact existence * Try and scrape together enough information to create a contact record, * with us as CONTACT_IS_FOLLOWER * Substitute our user's feed URL into $url template * Send the subscriber home to subscribe * */ $url = str_replace('{uri}', $a->get_baseurl() . '/dfrn_poll/' . $nickname, $url); goaway($url); // NOTREACHED // END $network === NETWORK_OSTATUS } } return; }
function profiles_init(&$a) { nav_set_selected('profiles'); if (!local_user()) { return; } if ($a->argc > 2 && $a->argv[1] === "drop" && intval($a->argv[2])) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d AND `is-default` = 0 LIMIT 1", intval($a->argv[2]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } check_form_security_token_redirectOnErr('/profiles', 'profile_drop', 't'); // move every contact using this profile as their default to the user default $r = q("UPDATE `contact` SET `profile-id` = (SELECT `profile`.`id` AS `profile-id` FROM `profile` WHERE `profile`.`is-default` = 1 AND `profile`.`uid` = %d LIMIT 1) WHERE `profile-id` = %d AND `uid` = %d ", intval(local_user()), intval($a->argv[2]), intval(local_user())); $r = q("DELETE FROM `profile` WHERE `id` = %d AND `uid` = %d", intval($a->argv[2]), intval(local_user())); if ($r) { info(t('Profile deleted.') . EOL); } goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } if ($a->argc > 1 && $a->argv[1] === 'new') { check_form_security_token_redirectOnErr('/profiles', 'profile_new', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT `name`, `photo`, `thumb` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", intval(local_user())); $r2 = q("INSERT INTO `profile` (`uid` , `profile-name` , `name`, `photo`, `thumb`)\n\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s' )", intval(local_user()), dbesc($name), dbesc($r1[0]['name']), dbesc($r1[0]['photo']), dbesc($r1[0]['thumb'])); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile-name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl(true) . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl(true) . '/profiles'); } if ($a->argc > 2 && $a->argv[1] === 'clone') { check_form_security_token_redirectOnErr('/profiles', 'profile_clone', 't'); $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_user()), intval($a->argv[2])); if (!count($r1)) { notice(t('Profile unavailable to clone.') . EOL); killme(); return; } unset($r1[0]['id']); $r1[0]['is-default'] = 0; $r1[0]['publish'] = 0; $r1[0]['net-publish'] = 0; $r1[0]['profile-name'] = dbesc($name); dbesc_array($r1[0]); $r2 = dbq("INSERT INTO `profile` (`" . implode("`, `", array_keys($r1[0])) . "`) VALUES ('" . implode("', '", array_values($r1[0])) . "')"); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile-name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl(true) . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl(true) . '/profiles'); return; // NOTREACHED } if ($a->argc > 1 && intval($a->argv[1])) { $r = q("SELECT id FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($a->argv[1]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); killme(); return; } profile_load($a, $a->user['nickname'], $r[0]['id']); } }
function local_delivery($importer, $data) { $a = get_app(); logger(__FUNCTION__, LOGGER_TRACE); if ($importer['readonly']) { // We aren't receiving stuff from this person. But we will quietly ignore them // rather than a blatant "go away" message. logger('local_delivery: ignoring'); return 0; //NOTREACHED } // Consume notification feed. This may differ from consuming a public feed in several ways // - might contain email or friend suggestions // - might contain remote followup to our message // - in which case we need to accept it and then notify other conversants // - we may need to send various email notifications $feed = new SimplePie(); $feed->set_raw_data($data); $feed->enable_order_by_date(false); $feed->init(); if ($feed->error()) { logger('local_delivery: Error parsing XML: ' . $feed->error()); } // Check at the feed level for updated contact name and/or photo $name_updated = ''; $new_name = ''; $photo_timestamp = ''; $photo_url = ''; $contact_updated = ''; $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'owner'); // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags // if(! $rawtags) // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author'); if ($rawtags) { $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]; if ($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) { $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']; $new_name = $elems['name'][0]['data']; // Manually checking for changed contact names if ($new_name != $importer['name'] and $new_name != "" and $name_updated <= $importer['name-date']) { $name_updated = date("c"); $photo_timestamp = date("c"); } } if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo' && $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']) { if ($photo_timestamp == "") { $photo_timestamp = datetime_convert('UTC', 'UTC', $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']); } $photo_url = $elems['link'][0]['attribs']['']['href']; } } if ($photo_timestamp && strlen($photo_url) && $photo_timestamp > $importer['avatar-date']) { $contact_updated = $photo_timestamp; logger('local_delivery: Updating photo for ' . $importer['name']); require_once "include/Photo.php"; $photos = import_profile_photo($photo_url, $importer['importer_uid'], $importer['id']); q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'\n\t\t\tWHERE `uid` = %d AND `id` = %d AND NOT `self`", dbesc(datetime_convert()), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), intval($importer['importer_uid']), intval($importer['id'])); } if ($name_updated && strlen($new_name) && $name_updated > $importer['name-date']) { if ($name_updated > $contact_updated) { $contact_updated = $name_updated; } $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($importer['importer_uid']), intval($importer['id'])); $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`", dbesc(notags(trim($new_name))), dbesc(datetime_convert()), intval($importer['importer_uid']), intval($importer['id']), dbesc(notags(trim($new_name)))); // do our best to update the name on content items if (count($r) and notags(trim($new_name)) != $r[0]['name']) { q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'", dbesc(notags(trim($new_name))), dbesc($r[0]['name']), dbesc($r[0]['url']), intval($importer['importer_uid']), dbesc(notags(trim($new_name)))); } } if ($contact_updated and $new_name and $photo_url) { poco_check($importer['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $importer['id'], $importer['importer_uid']); } // Currently unsupported - needs a lot of work $reloc = $feed->get_feed_tags(NAMESPACE_DFRN, 'relocate'); if (isset($reloc[0]['child'][NAMESPACE_DFRN])) { $base = $reloc[0]['child'][NAMESPACE_DFRN]; $newloc = array(); $newloc['uid'] = $importer['importer_uid']; $newloc['cid'] = $importer['id']; $newloc['name'] = notags(unxmlify($base['name'][0]['data'])); $newloc['photo'] = notags(unxmlify($base['photo'][0]['data'])); $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data'])); $newloc['micro'] = notags(unxmlify($base['micro'][0]['data'])); $newloc['url'] = notags(unxmlify($base['url'][0]['data'])); $newloc['request'] = notags(unxmlify($base['request'][0]['data'])); $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data'])); $newloc['notify'] = notags(unxmlify($base['notify'][0]['data'])); $newloc['poll'] = notags(unxmlify($base['poll'][0]['data'])); $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data'])); /** relocated user must have original key pair */ /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data'])); $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/ logger("items:relocate contact " . print_r($newloc, true) . print_r($importer, true), LOGGER_DEBUG); // update contact $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;", intval($importer['id']), intval($importer['importer_uid'])); if ($r === false) { return 1; } $old = $r[0]; $x = q("UPDATE contact SET\n\t\t\t\t\tname = '%s',\n\t\t\t\t\tphoto = '%s',\n\t\t\t\t\tthumb = '%s',\n\t\t\t\t\tmicro = '%s',\n\t\t\t\t\turl = '%s',\n\t\t\t\t\tnurl = '%s',\n\t\t\t\t\trequest = '%s',\n\t\t\t\t\tconfirm = '%s',\n\t\t\t\t\tnotify = '%s',\n\t\t\t\t\tpoll = '%s',\n\t\t\t\t\t`site-pubkey` = '%s'\n\t\t\tWHERE id=%d AND uid=%d;", dbesc($newloc['name']), dbesc($newloc['photo']), dbesc($newloc['thumb']), dbesc($newloc['micro']), dbesc($newloc['url']), dbesc(normalise_link($newloc['url'])), dbesc($newloc['request']), dbesc($newloc['confirm']), dbesc($newloc['notify']), dbesc($newloc['poll']), dbesc($newloc['sitepubkey']), intval($importer['id']), intval($importer['importer_uid'])); if ($x === false) { return 1; } // update items $fields = array('owner-link' => array($old['url'], $newloc['url']), 'author-link' => array($old['url'], $newloc['url']), 'owner-avatar' => array($old['photo'], $newloc['photo']), 'author-avatar' => array($old['photo'], $newloc['photo'])); foreach ($fields as $n => $f) { $x = q("UPDATE `item` SET `%s`='%s' WHERE `%s`='%s' AND uid=%d", $n, dbesc($f[1]), $n, dbesc($f[0]), intval($importer['importer_uid'])); if ($x === false) { return 1; } } // TODO // merge with current record, current contents have priority // update record, set url-updated // update profile photos // schedule a scan? return 0; } // handle friend suggestion notification $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest'); if (isset($sugg[0]['child'][NAMESPACE_DFRN])) { $base = $sugg[0]['child'][NAMESPACE_DFRN]; $fsugg = array(); $fsugg['uid'] = $importer['importer_uid']; $fsugg['cid'] = $importer['id']; $fsugg['name'] = notags(unxmlify($base['name'][0]['data'])); $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data'])); $fsugg['url'] = notags(unxmlify($base['url'][0]['data'])); $fsugg['request'] = notags(unxmlify($base['request'][0]['data'])); $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data'])); // Does our member already have a friend matching this description? $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid'])); if (count($r)) { return 0; } // Do we already have an fcontact record for this person? $fid = 0; $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; // OK, we do. Do we already have an introduction for this person ? $r = q("select id from intro where uid = %d and fid = %d limit 1", intval($fsugg['uid']), intval($fid)); if (count($r)) { return 0; } } if (!$fid) { $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request'])); } $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request'])); if (count($r)) { $fid = $r[0]['id']; } else { return 0; } $hash = random_string(); $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0)); notification(array('type' => NOTIFY_SUGGEST, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $fsugg, 'link' => $a->get_baseurl() . '/notifications/intros', 'source_name' => $importer['name'], 'source_link' => $importer['url'], 'source_photo' => $importer['photo'], 'verb' => ACTIVITY_REQ_FRIEND, 'otype' => 'intro')); return 0; } $ismail = false; $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail'); if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) { logger('local_delivery: private message received'); $ismail = true; $base = $rawmail[0]['child'][NAMESPACE_DFRN]; $msg = array(); $msg['uid'] = $importer['importer_uid']; $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data'])); $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data'])); $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])); $msg['contact-id'] = $importer['id']; $msg['title'] = notags(unxmlify($base['subject'][0]['data'])); $msg['body'] = escape_tags(unxmlify($base['content'][0]['data'])); $msg['seen'] = 0; $msg['replied'] = 0; $msg['uri'] = notags(unxmlify($base['id'][0]['data'])); $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data'])); $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data']))); dbesc_array($msg); $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')"); // send notifications. require_once 'include/enotify.php'; $notif_params = array('type' => NOTIFY_MAIL, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $msg, 'source_name' => $msg['from-name'], 'source_link' => $importer['url'], 'source_photo' => $importer['thumb'], 'verb' => ACTIVITY_POST, 'otype' => 'mail'); notification($notif_params); return 0; // NOTREACHED } $community_page = 0; $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community'); if ($rawtags) { $community_page = intval($rawtags[0]['data']); } if (intval($importer['forum']) != $community_page) { q("update contact set forum = %d where id = %d", intval($community_page), intval($importer['id'])); $importer['forum'] = (string) $community_page; } logger('local_delivery: feed item count = ' . $feed->get_item_quantity()); // process any deleted entries $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry'); if (is_array($del_entries) && count($del_entries)) { foreach ($del_entries as $dentry) { $deleted = false; if (isset($dentry['attribs']['']['ref'])) { $uri = $dentry['attribs']['']['ref']; $deleted = true; if (isset($dentry['attribs']['']['when'])) { $when = $dentry['attribs']['']['when']; $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s'); } else { $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s'); } } if ($deleted) { // check for relayed deletes to our conversation $is_reply = false; $r = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($uri), intval($importer['importer_uid'])); if (count($r)) { $parent_uri = $r[0]['parent-uri']; if ($r[0]['id'] != $r[0]['parent']) { $is_reply = true; } } if ($is_reply) { $community = false; if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) { $sql_extra = ''; $community = true; logger('local_delivery: possible community delete'); } else { $sql_extra = " and contact.self = 1 and item.wall = 1 "; } // was the top-level post for this reply written by somebody on this site? // Specifically, the recipient? $is_a_remote_delete = false; // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used? $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,\n\t\t\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`\n\t\t\t\t\t\tINNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\t\t\tWHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')\n\t\t\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid'])); if ($r && count($r)) { $is_a_remote_delete = true; } // Does this have the characteristics of a community or private group comment? // If it's a reply to a wall post on a community/prvgroup page it's a // valid community comment. Also forum_mode makes it valid for sure. // If neither, it's not. if ($is_a_remote_delete && $community) { if (!$r[0]['forum_mode'] && !$r[0]['wall']) { $is_a_remote_delete = false; logger('local_delivery: not a community delete'); } } if ($is_a_remote_delete) { logger('local_delivery: received remote delete'); } } $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN contact on `item`.`contact-id` = `contact`.`id`\n\t\t\t\t\tWHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1", dbesc($uri), intval($importer['importer_uid']), intval($importer['id'])); if (count($r)) { $item = $r[0]; if ($item['deleted']) { continue; } logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG); if ($item['object-type'] === ACTIVITY_OBJ_EVENT) { logger("Deleting event " . $item['event-id'], LOGGER_DEBUG); event_delete($item['event-id']); } if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($item['object'], false); $xt = parse_xml_string($item['target'], false); if ($xt->type === ACTIVITY_OBJ_NOTE) { $i = q("select * from `item` where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (count($i)) { // For tags, the owner cannot remove the tag on the author's copy of the post. $owner_remove = $item['contact-id'] == $i[0]['contact-id'] ? true : false; $author_remove = $item['origin'] && $item['self'] ? true : false; $author_copy = $item['origin'] ? true : false; if ($owner_remove && $author_copy) { continue; } if ($author_remove || $owner_remove) { $tags = explode(',', $i[0]['tag']); $newtags = array(); if (count($tags)) { foreach ($tags as $tag) { if (trim($tag) !== trim($xo->body)) { $newtags[] = trim($tag); } } } q("update item set tag = '%s' where id = %d", dbesc(implode(',', $newtags)), intval($i[0]['id'])); create_tags_from_item($i[0]['id']); } } } } if ($item['uri'] == $item['parent-uri']) { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = ''\n\t\t\t\t\t\t\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['importer_uid'])); create_tags_from_itemuri($item['uri'], $importer['importer_uid']); create_files_from_itemuri($item['uri'], $importer['importer_uid']); update_thread_uri($item['uri'], $importer['importer_uid']); } else { $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = ''\n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['importer_uid'])); create_tags_from_itemuri($uri, $importer['importer_uid']); create_files_from_itemuri($uri, $importer['importer_uid']); update_thread_uri($uri, $importer['importer_uid']); if ($item['last-child']) { // ensure that last-child is set in case the comment that had it just got wiped. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), dbesc($item['parent-uri']), intval($item['uid'])); // who is the last child now? $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid'])); if (count($r)) { q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d", intval($r[0]['id'])); } } // if this is a relayed delete, propagate it to other recipients if ($is_a_remote_delete) { proc_run('php', "include/notifier.php", "drop", $item['id']); } } } } } } foreach ($feed->get_items() as $item) { $is_reply = false; $item_id = $item->get_id(); $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to'); if (isset($rawthread[0]['attribs']['']['ref'])) { $is_reply = true; $parent_uri = $rawthread[0]['attribs']['']['ref']; } if ($is_reply) { $community = false; if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) { $sql_extra = ''; $community = true; logger('local_delivery: possible community reply'); } else { $sql_extra = " and contact.self = 1 and item.wall = 1 "; } // was the top-level post for this reply written by somebody on this site? // Specifically, the recipient? $is_a_remote_comment = false; $top_uri = $parent_uri; $r = q("select `item`.`parent-uri` from `item`\n\t\t\t\tWHERE `item`.`uri` = '%s'\n\t\t\t\tLIMIT 1", dbesc($parent_uri)); if ($r && count($r)) { $top_uri = $r[0]['parent-uri']; // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used? $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,\n\t\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`\n\t\t\t\t\tINNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\t\tWHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')\n\t\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t\t{$sql_extra}\n\t\t\t\t\tLIMIT 1", dbesc($top_uri), dbesc($top_uri), dbesc($top_uri), intval($importer['importer_uid'])); if ($r && count($r)) { $is_a_remote_comment = true; } } // Does this have the characteristics of a community or private group comment? // If it's a reply to a wall post on a community/prvgroup page it's a // valid community comment. Also forum_mode makes it valid for sure. // If neither, it's not. if ($is_a_remote_comment && $community) { if (!$r[0]['forum_mode'] && !$r[0]['wall']) { $is_a_remote_comment = false; logger('local_delivery: not a community reply'); } } if ($is_a_remote_comment) { logger('local_delivery: received remote comment'); $is_like = false; // remote reply to our post. Import and then notify everybody else. $datarray = get_atom_elements($feed, $item); $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { $iid = $r[0]['id']; if (edited_timestamp_is_newer($r[0], $datarray)) { // do not accept (ignore) an earlier edit than one we currently have. if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) { continue; } logger('received updated comment', LOGGER_DEBUG); $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); create_tags_from_itemuri($item_id, $importer['importer_uid']); proc_run('php', "include/notifier.php", "comment-import", $iid); } continue; } $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1", intval($importer['importer_uid'])); $datarray['type'] = 'remote-comment'; $datarray['wall'] = 1; $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['owner-name'] = $own[0]['name']; $datarray['owner-link'] = $own[0]['url']; $datarray['owner-avatar'] = $own[0]['thumb']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE || $datarray['verb'] === ACTIVITY_ATTEND || $datarray['verb'] === ACTIVITY_ATTENDNO || $datarray['verb'] === ACTIVITY_ATTENDMAYBE) { $is_like = true; $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; $datarray['last-child'] = 0; // only one like or dislike per person // splitted into two queries for performance issues $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`parent-uri` = '%s') and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($datarray['parent-uri'])); if ($r && count($r)) { continue; } $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s') and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($datarray['parent-uri'])); if ($r && count($r)) { continue; } } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE && $xt->id) { // fetch the parent item $tagp = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (!count($tagp)) { continue; } // extract tag, if not duplicate, and this user allows tags, add to parent item if ($xo->id && $xo->content) { $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]'; if (!stristr($tagp[0]['tag'], $newtag)) { $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid'])); if (count($i) && !intval($i[0]['blocktags'])) { q("UPDATE item SET tag = '%s', `edited` = '%s', `changed` = '%s' WHERE id = %d", dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag), intval($tagp[0]['id']), dbesc(datetime_convert()), dbesc(datetime_convert())); create_tags_from_item($tagp[0]['id']); } } } } } $posted_id = item_store($datarray); $parent = 0; if ($posted_id) { $datarray["id"] = $posted_id; $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid'])); if (count($r)) { $parent = $r[0]['parent']; $parent_uri = $r[0]['parent-uri']; } if (!$is_like) { $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent'])); $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id)); } if ($posted_id && $parent) { proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}"); if (!$is_like && !$importer['self']) { require_once 'include/enotify.php'; notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_uri' => $parent_uri)); } } return 0; // NOTREACHED } } else { // regular comment that is part of this total conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); if ($importer['rel'] == CONTACT_IS_FOLLOWER) { continue; } $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (edited_timestamp_is_newer($r[0], $datarray)) { // do not accept (ignore) an earlier edit than one we currently have. if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) { continue; } $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); create_tags_from_itemuri($item_id, $importer['importer_uid']); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['importer_uid'])); $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } $datarray['parent-uri'] = $parent_uri; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE || $datarray['verb'] === ACTIVITY_ATTEND || $datarray['verb'] === ACTIVITY_ATTENDNO || $datarray['verb'] === ACTIVITY_ATTENDMAYBE) { $datarray['type'] = 'activity'; $datarray['gravity'] = GRAVITY_LIKE; // only one like or dislike per person // splitted into two queries for performance issues $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s') limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($parent_uri)); if ($r && count($r)) { continue; } $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`thr-parent` = '%s') limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($parent_uri)); if ($r && count($r)) { continue; } } if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) { $xo = parse_xml_string($datarray['object'], false); $xt = parse_xml_string($datarray['target'], false); if ($xt->type == ACTIVITY_OBJ_NOTE) { $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1", dbesc($xt->id), intval($importer['importer_uid'])); if (!count($r)) { continue; } // extract tag, if not duplicate, add to parent item if ($xo->content) { if (!stristr($r[0]['tag'], trim($xo->content))) { q("UPDATE item SET tag = '%s' WHERE id = %d", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id'])); create_tags_from_item($r[0]['id']); } } } } $posted_id = item_store($datarray); // find out if our user is involved in this conversation and wants to be notified. if (!x($datarray['type']) || $datarray['type'] != 'activity') { $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($top_uri), intval($importer['importer_uid'])); if (count($myconv)) { $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname']; // first make sure this isn't our own post coming back to us from a wall-to-wall event if (!link_compare($datarray['author-link'], $importer_url)) { foreach ($myconv as $conv) { // now if we find a match, it means we're in this conversation if (!link_compare($conv['author-link'], $importer_url)) { continue; } require_once 'include/enotify.php'; $conv_parent = $conv['parent']; notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $conv_parent, 'parent_uri' => $parent_uri)); // only send one notification break; } } } } continue; } } else { // Head post of a conversation. Have we seen it? If not, import it. $item_id = $item->get_id(); $datarray = get_atom_elements($feed, $item); if (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) { $ev = bbtoevent($datarray['body']); if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) { $ev['cid'] = $importer['id']; $ev['uid'] = $importer['uid']; $ev['uri'] = $item_id; $ev['edited'] = $datarray['edited']; $ev['private'] = $datarray['private']; $ev['guid'] = $datarray['guid']; $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid'])); if (count($r)) { $ev['id'] = $r[0]['id']; } $xyz = event_store($ev); continue; } } $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid'])); // Update content if 'updated' changes if (count($r)) { if (edited_timestamp_is_newer($r[0], $datarray)) { // do not accept (ignore) an earlier edit than one we currently have. if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) { continue; } $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); create_tags_from_itemuri($item_id, $importer['importer_uid']); update_thread_uri($item_id, $importer['importer_uid']); } // update last-child if it changes $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow'); if ($allow && $allow[0]['data'] != $r[0]['last-child']) { $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['importer_uid'])); } continue; } $datarray['parent-uri'] = $item_id; $datarray['uid'] = $importer['importer_uid']; $datarray['contact-id'] = $importer['id']; if (!link_compare($datarray['owner-link'], $importer['url'])) { // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, // but otherwise there's a possible data mixup on the sender's system. // the tgroup delivery code called from item_store will correct it if it's a forum, // but we're going to unconditionally correct it here so that the post will always be owned by our contact. logger('local_delivery: Correcting item owner.', LOGGER_DEBUG); $datarray['owner-name'] = $importer['senderName']; $datarray['owner-link'] = $importer['url']; $datarray['owner-avatar'] = $importer['thumb']; } if ($importer['rel'] == CONTACT_IS_FOLLOWER && !tgroup_check($importer['importer_uid'], $datarray)) { continue; } // This is my contact on another system, but it's really me. // Turn this into a wall post. $notify = item_is_remote_self($importer, $datarray); $posted_id = item_store($datarray, false, $notify); if (stristr($datarray['verb'], ACTIVITY_POKE)) { $verb = urldecode(substr($datarray['verb'], strpos($datarray['verb'], '#') + 1)); if (!$verb) { continue; } $xo = parse_xml_string($datarray['object'], false); if ($xo->type == ACTIVITY_OBJ_PERSON && $xo->id) { // somebody was poked/prodded. Was it me? $links = parse_xml_string("<links>" . unxmlify($xo->link) . "</links>", false); foreach ($links->link as $l) { $atts = $l->attributes(); switch ($atts['rel']) { case "alternate": $Blink = $atts['href']; break; default: break; } } if ($Blink && link_compare($Blink, $a->get_baseurl() . '/profile/' . $importer['nickname'])) { // send a notification require_once 'include/enotify.php'; notification(array('type' => NOTIFY_POKE, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => $datarray['verb'], 'otype' => 'person', 'activity' => $verb, 'parent' => $datarray['parent'])); } } } continue; } } return 0; // NOTREACHED }
function profiles_content(&$a) { $o = ''; nav_set_selected('profiles'); if (!local_user()) { notice(t('Permission denied.') . EOL); return; } if ($a->argc > 2 && $a->argv[1] === "drop" && intval($a->argv[2])) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d AND `is-default` = 0 LIMIT 1", intval($a->argv[2]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } // move every contact using this profile as their default to the user default $r = q("UPDATE `contact` SET `profile-id` = (SELECT `profile`.`id` AS `profile-id` FROM `profile` WHERE `profile`.`is-default` = 1 AND `profile`.`uid` = %d LIMIT 1) WHERE `profile-id` = %d AND `uid` = %d ", intval(local_user()), intval($a->argv[2]), intval(local_user())); $r = q("DELETE FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($a->argv[2]), intval(local_user())); if ($r) { info(t('Profile deleted.') . EOL); } goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } if ($a->argc > 1 && $a->argv[1] === 'new') { $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT `name`, `photo`, `thumb` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", intval(local_user())); $r2 = q("INSERT INTO `profile` (`uid` , `profile-name` , `name`, `photo`, `thumb`)\n\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s' )", intval(local_user()), dbesc($name), dbesc($r1[0]['name']), dbesc($r1[0]['photo']), dbesc($r1[0]['thumb'])); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile-name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl() . '/profiles'); } if ($a->argc > 2 && $a->argv[1] === 'clone') { $r0 = q("SELECT `id` FROM `profile` WHERE `uid` = %d", intval(local_user())); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval(local_user()), intval($a->argv[2])); if (!count($r1)) { notice(t('Profile unavailable to clone.') . EOL); return; } unset($r1[0]['id']); $r1[0]['is-default'] = 0; $r1[0]['publish'] = 0; $r1[0]['net-publish'] = 0; $r1[0]['profile-name'] = dbesc($name); dbesc_array($r1[0]); $r2 = dbq("INSERT INTO `profile` (`" . implode("`, `", array_keys($r1[0])) . "`) VALUES ('" . implode("', '", array_values($r1[0])) . "')"); $r3 = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `profile-name` = '%s' LIMIT 1", intval(local_user()), dbesc($name)); info(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } if ($a->argc > 1 && intval($a->argv[1])) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($a->argv[1]), intval(local_user())); if (!count($r)) { notice(t('Profile not found.') . EOL); return; } profile_load($a, $a->user['nickname'], $r[0]['id']); require_once 'include/profile_selectors.php'; $tpl = get_markup_template('profed_head.tpl'); $opt_tpl = get_markup_template("profile-hide-friends.tpl"); $hide_friends = replace_macros($opt_tpl, array('$desc' => t('Hide your contact/friend list from viewers of this profile?'), '$yes_str' => t('Yes'), '$no_str' => t('No'), '$yes_selected' => $r[0]['hide-friends'] ? " checked=\"checked\" " : "", '$no_selected' => $r[0]['hide-friends'] == 0 ? " checked=\"checked\" " : "")); $a->page['htmlhead'] .= replace_macros($tpl, array('$baseurl' => $a->get_baseurl())); $a->page['htmlhead'] .= "<script type=\"text/javascript\" src=\"js/country.js\" ></script>"; $f = get_config('system', 'birthday_input_format'); if (!$f) { $f = 'ymd'; } $is_default = $r[0]['is-default'] ? 1 : 0; $tpl = get_markup_template("profile_edit.tpl"); $o .= replace_macros($tpl, array('$banner' => t('Edit Profile Details'), '$submit' => t('Submit'), '$viewprof' => t('View this profile'), '$cr_prof' => t('Create a new profile using these settings'), '$cl_prof' => t('Clone this profile'), '$del_prof' => t('Delete this profile'), '$lbl_profname' => t('Profile Name:'), '$lbl_fullname' => t('Your Full Name:'), '$lbl_title' => t('Title/Description:'), '$lbl_gender' => t('Your Gender:'), '$lbl_bd' => sprintf(t("Birthday (%s):"), datesel_format($f)), '$lbl_address' => t('Street Address:'), '$lbl_city' => t('Locality/City:'), '$lbl_zip' => t('Postal/Zip Code:'), '$lbl_country' => t('Country:'), '$lbl_region' => t('Region/State:'), '$lbl_marital' => t('<span class="heart">♥</span> Marital Status:'), '$lbl_with' => t("Who: (if applicable)"), '$lbl_ex1' => t('Examples: cathy123, Cathy Williams, cathy@example.com'), '$lbl_sexual' => t('Sexual Preference:'), '$lbl_homepage' => t('Homepage URL:'), '$lbl_politic' => t('Political Views:'), '$lbl_religion' => t('Religious Views:'), '$lbl_pubkey' => t('Public Keywords:'), '$lbl_prvkey' => t('Private Keywords:'), '$lbl_ex2' => t('Example: fishing photography software'), '$lbl_pubdsc' => t("(Used for suggesting potential friends, can be seen by others)"), '$lbl_prvdsc' => t("(Used for searching profiles, never shown to others)"), '$lbl_about' => t('Tell us about yourself...'), '$lbl_hobbies' => t('Hobbies/Interests'), '$lbl_social' => t('Contact information and Social Networks'), '$lbl_music' => t('Musical interests'), '$lbl_book' => t('Books, literature'), '$lbl_tv' => t('Television'), '$lbl_film' => t('Film/dance/culture/entertainment'), '$lbl_love' => t('Love/romance'), '$lbl_work' => t('Work/employment'), '$lbl_school' => t('School/education'), '$disabled' => $is_default ? 'onclick="return false;" style="color: #BBBBFF;"' : '', '$baseurl' => $a->get_baseurl(), '$profile_id' => $r[0]['id'], '$profile_name' => $r[0]['profile-name'], '$default' => $is_default ? '<p id="profile-edit-default-desc">' . t('This is your <strong>public</strong> profile.<br />It <strong>may</strong> be visible to anybody using the internet.') . '</p>' : "", '$name' => $r[0]['name'], '$pdesc' => $r[0]['pdesc'], '$dob' => dob($r[0]['dob']), '$hide_friends' => $hide_friends, '$address' => $r[0]['address'], '$locality' => $r[0]['locality'], '$region' => $r[0]['region'], '$postal_code' => $r[0]['postal-code'], '$country_name' => $r[0]['country-name'], '$age' => intval($r[0]['dob']) ? '(' . t('Age: ') . age($r[0]['dob'], $a->user['timezone'], $a->user['timezone']) . ')' : '', '$gender' => gender_selector($r[0]['gender']), '$marital' => marital_selector($r[0]['marital']), '$with' => strip_tags($r[0]['with']), '$sexual' => sexpref_selector($r[0]['sexual']), '$about' => $r[0]['about'], '$homepage' => $r[0]['homepage'], '$politic' => $r[0]['politic'], '$religion' => $r[0]['religion'], '$pub_keywords' => $r[0]['pub_keywords'], '$prv_keywords' => $r[0]['prv_keywords'], '$music' => $r[0]['music'], '$book' => $r[0]['book'], '$tv' => $r[0]['tv'], '$film' => $r[0]['film'], '$interest' => $r[0]['interest'], '$romance' => $r[0]['romance'], '$work' => $r[0]['work'], '$education' => $r[0]['education'], '$contact' => $r[0]['contact'])); $arr = array('profile' => $r[0], 'entry' => $o); call_hooks('profile_edit', $arr); return $o; } else { $r = q("SELECT * FROM `profile` WHERE `uid` = %d", local_user()); if (count($r)) { $tpl_header = get_markup_template('profile_listing_header.tpl'); $o .= replace_macros($tpl_header, array('$header' => t('Edit/Manage Profiles'), '$chg_photo' => t('Change profile photo'), '$cr_new' => t('Create New Profile'))); $tpl = get_markup_template('profile_entry.tpl'); foreach ($r as $rr) { $o .= replace_macros($tpl, array('$photo' => $rr['thumb'], '$id' => $rr['id'], '$alt' => t('Profile Image'), '$profile_name' => $rr['profile-name'], '$visible' => $rr['is-default'] ? '<strong>' . t('visible to everybody') . '</strong>' : '<a href="' . $a->get_baseurl() . '/profperm/' . $rr['id'] . '" />' . t('Edit visibility') . '</a>')); } } return $o; } }
function import_account($account_id) { if (!$account_id) { logger("import_account: No account ID supplied"); return; } $max_identities = account_service_class_fetch($account_id, 'total_identities'); $max_friends = account_service_class_fetch($account_id, 'total_channels'); $max_feeds = account_service_class_fetch($account_id, 'total_feeds'); if ($max_identities !== false) { $r = q("select channel_id from channel where channel_account_id = %d", intval($account_id)); if ($r && count($r) > $max_identities) { notice(sprintf(t('Your service plan only allows %d channels.'), $max_identities) . EOL); return; } } $data = null; $seize = x($_REQUEST, 'make_primary') ? intval($_REQUEST['make_primary']) : 0; $import_posts = x($_REQUEST, 'import_posts') ? intval($_REQUEST['import_posts']) : 0; $src = $_FILES['filename']['tmp_name']; $filename = basename($_FILES['filename']['name']); $filesize = intval($_FILES['filename']['size']); $filetype = $_FILES['filename']['type']; $completed = array_key_exists('import_step', $_SESSION) ? intval($_SESSION['import_step']) : 0; if ($completed) { logger('saved import step: ' . $_SESSION['import_step']); } if ($src) { // This is OS specific and could also fail if your tmpdir isn't very large // mostly used for Diaspora which exports gzipped files. if (strpos($filename, '.gz')) { @rename($src, $src . '.gz'); @system('gunzip ' . escapeshellarg($src . '.gz')); } if ($filesize) { $data = @file_get_contents($src); } unlink($src); } if (!$src) { $old_address = x($_REQUEST, 'old_address') ? $_REQUEST['old_address'] : ''; if (!$old_address) { logger('mod_import: nothing to import.'); notice(t('Nothing to import.') . EOL); return; } $email = x($_REQUEST, 'email') ? $_REQUEST['email'] : ''; $password = x($_REQUEST, 'password') ? $_REQUEST['password'] : ''; $channelname = substr($old_address, 0, strpos($old_address, '@')); $servername = substr($old_address, strpos($old_address, '@') + 1); $scheme = 'https://'; $api_path = '/api/red/channel/export/basic?f=&channel=' . $channelname; if ($import_posts) { $api_path .= '&posts=1'; } $binary = false; $redirects = 0; $opts = array('http_auth' => $email . ':' . $password); $url = $scheme . $servername . $api_path; $ret = z_fetch_url($url, $binary, $redirects, $opts); if (!$ret['success']) { $ret = z_fetch_url('http://' . $servername . $api_path, $binary, $redirects, $opts); } if ($ret['success']) { $data = $ret['body']; } else { notice(t('Unable to download data from old server') . EOL); } } if (!$data) { logger('mod_import: empty file.'); notice(t('Imported file is empty.') . EOL); return; } $data = json_decode($data, true); // logger('import: data: ' . print_r($data,true)); // print_r($data); if (array_key_exists('user', $data) && array_key_exists('version', $data)) { require_once 'include/Import/import_diaspora.php'; import_diaspora($data); return; } $moving = false; if (array_key_exists('compatibility', $data) && array_key_exists('database', $data['compatibility'])) { $v1 = substr($data['compatibility']['database'], -4); $v2 = substr(DB_UPDATE_VERSION, -4); if ($v2 > $v1) { $t = sprintf(t('Warning: Database versions differ by %1$d updates.'), $v2 - $v1); notice($t); } if (array_key_exists('server_role', $data['compatibility']) && $data['compatibility']['server_role'] == 'basic') { $moving = true; } } if ($moving) { $seize = 1; } // import channel $relocate = array_key_exists('relocate', $data) ? $data['relocate'] : null; if (array_key_exists('channel', $data)) { if ($completed < 1) { $channel = import_channel($data['channel'], $account_id, $seize); } else { $r = q("select * from channel where channel_account_id = %d and channel_guid = '%s' limit 1", intval($account_id), dbesc($channel['channel_guid'])); if ($r) { $channel = $r[0]; } } if (!$channel) { logger('mod_import: channel not found. ', print_r($channel, true)); notice(t('Cloned channel not found. Import failed.') . EOL); return; } } if (!$channel) { $channel = \App::get_channel(); } if (!$channel) { logger('mod_import: channel not found. ', print_r($channel, true)); notice(t('No channel. Import failed.') . EOL); return; } if ($completed < 2) { if (is_array($data['config'])) { import_config($channel, $data['config']); } logger('import step 2'); $_SESSION['import_step'] = 2; } if ($completed < 3) { if ($data['photo']) { require_once 'include/photo/photo_driver.php'; import_channel_photo(base64url_decode($data['photo']['data']), $data['photo']['type'], $account_id, $channel['channel_id']); } if (is_array($data['profile'])) { import_profiles($channel, $data['profile']); } logger('import step 3'); $_SESSION['import_step'] = 3; } if ($completed < 4) { if (is_array($data['hubloc']) && !$moving) { import_hublocs($channel, $data['hubloc'], $seize); } logger('import step 4'); $_SESSION['import_step'] = 4; } if ($completed < 5) { // create new hubloc for the new channel at this site $r = q("insert into hubloc ( hubloc_guid, hubloc_guid_sig, hubloc_hash, hubloc_addr, hubloc_network, hubloc_primary, \n\t\t\t\thubloc_url, hubloc_url_sig, hubloc_host, hubloc_callback, hubloc_sitekey )\n\t\t\t\tvalues ( '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s' )", dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_hash']), dbesc(channel_reddress($channel)), dbesc('zot'), intval($seize ? 1 : 0), dbesc(z_root()), dbesc(base64url_encode(rsa_sign(z_root(), $channel['channel_prvkey']))), dbesc(\App::get_hostname()), dbesc(z_root() . '/post'), dbesc(get_config('system', 'pubkey'))); // reset the original primary hubloc if it is being seized if ($seize) { $r = q("update hubloc set hubloc_primary = 0 where hubloc_primary = 1 and hubloc_hash = '%s' and hubloc_url != '%s' ", dbesc($channel['channel_hash']), dbesc(z_root())); } logger('import step 5'); $_SESSION['import_step'] = 5; } if ($completed < 6) { // import xchans and contact photos if ($seize) { // replace any existing xchan we may have on this site if we're seizing control $r = q("delete from xchan where xchan_hash = '%s'", dbesc($channel['channel_hash'])); $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_guid_sig, xchan_pubkey, xchan_photo_l, xchan_photo_m, xchan_photo_s, xchan_addr, xchan_url, xchan_follow, xchan_connurl, xchan_name, xchan_network, xchan_photo_date, xchan_name_date, xchan_hidden, xchan_orphan, xchan_censored, xchan_selfcensored, xchan_system, xchan_pubforum, xchan_deleted ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, %d )", dbesc($channel['channel_hash']), dbesc($channel['channel_guid']), dbesc($channel['channel_guid_sig']), dbesc($channel['channel_pubkey']), dbesc(z_root() . "/photo/profile/l/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/m/" . $channel['channel_id']), dbesc(z_root() . "/photo/profile/s/" . $channel['channel_id']), dbesc(channel_reddress($channel)), dbesc(z_root() . '/channel/' . $channel['channel_address']), dbesc(z_root() . '/follow?f=&url=%s'), dbesc(z_root() . '/poco/' . $channel['channel_address']), dbesc($channel['channel_name']), dbesc('zot'), dbesc(datetime_convert()), dbesc(datetime_convert()), 0, 0, 0, 0, 0, 0, 0); } logger('import step 6'); $_SESSION['import_step'] = 6; } if ($completed < 7) { $xchans = $data['xchan']; if ($xchans) { foreach ($xchans as $xchan) { $hash = make_xchan_hash($xchan['xchan_guid'], $xchan['xchan_guid_sig']); if ($xchan['xchan_network'] === 'zot' && $hash !== $xchan['xchan_hash']) { logger('forged xchan: ' . print_r($xchan, true)); continue; } if (!array_key_exists('xchan_hidden', $xchan)) { $xchan['xchan_hidden'] = $xchan['xchan_flags'] & 0x1 ? 1 : 0; $xchan['xchan_orphan'] = $xchan['xchan_flags'] & 0x2 ? 1 : 0; $xchan['xchan_censored'] = $xchan['xchan_flags'] & 0x4 ? 1 : 0; $xchan['xchan_selfcensored'] = $xchan['xchan_flags'] & 0x8 ? 1 : 0; $xchan['xchan_system'] = $xchan['xchan_flags'] & 0x10 ? 1 : 0; $xchan['xchan_pubforum'] = $xchan['xchan_flags'] & 0x20 ? 1 : 0; $xchan['xchan_deleted'] = $xchan['xchan_flags'] & 0x1000 ? 1 : 0; } $r = q("select xchan_hash from xchan where xchan_hash = '%s' limit 1", dbesc($xchan['xchan_hash'])); if ($r) { continue; } dbesc_array($xchan); $r = dbq("INSERT INTO xchan (`" . implode("`, `", array_keys($xchan)) . "`) VALUES ('" . implode("', '", array_values($xchan)) . "')"); require_once 'include/photo/photo_driver.php'; $photos = import_xchan_photo($xchan['xchan_photo_l'], $xchan['xchan_hash']); if ($photos[4]) { $photodate = NULL_DATE; } else { $photodate = $xchan['xchan_photo_date']; } $r = q("update xchan set xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s', xchan_photo_date = '%s'\n\t\t\t\t\t\twhere xchan_hash = '%s'", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($photodate), dbesc($xchan['xchan_hash'])); } } logger('import step 7'); $_SESSION['import_step'] = 7; } // FIXME - ensure we have an xchan if somebody is trying to pull a fast one if ($completed < 8) { $friends = 0; $feeds = 0; // import contacts $abooks = $data['abook']; if ($abooks) { foreach ($abooks as $abook) { $abook_copy = $abook; $abconfig = null; if (array_key_exists('abconfig', $abook) && is_array($abook['abconfig']) && count($abook['abconfig'])) { $abconfig = $abook['abconfig']; } unset($abook['abook_id']); unset($abook['abook_rating']); unset($abook['abook_rating_text']); unset($abook['abconfig']); unset($abook['abook_their_perms']); unset($abook['abook_my_perms']); $abook['abook_account'] = $account_id; $abook['abook_channel'] = $channel['channel_id']; if (!array_key_exists('abook_blocked', $abook)) { $abook['abook_blocked'] = $abook['abook_flags'] & 0x1 ? 1 : 0; $abook['abook_ignored'] = $abook['abook_flags'] & 0x2 ? 1 : 0; $abook['abook_hidden'] = $abook['abook_flags'] & 0x4 ? 1 : 0; $abook['abook_archived'] = $abook['abook_flags'] & 0x8 ? 1 : 0; $abook['abook_pending'] = $abook['abook_flags'] & 0x10 ? 1 : 0; $abook['abook_unconnected'] = $abook['abook_flags'] & 0x20 ? 1 : 0; $abook['abook_self'] = $abook['abook_flags'] & 0x80 ? 1 : 0; $abook['abook_feed'] = $abook['abook_flags'] & 0x100 ? 1 : 0; } if ($abook['abook_self']) { $role = get_pconfig($channel['channel_id'], 'system', 'permissions_role'); if ($role === 'forum' || $abook['abook_my_perms'] & PERMS_W_TAGWALL) { q("update xchan set xchan_pubforum = 1 where xchan_hash = '%s' ", dbesc($abook['abook_xchan'])); } } else { if ($max_friends !== false && $friends > $max_friends) { continue; } if ($max_feeds !== false && intval($abook['abook_feed']) && $feeds > $max_feeds) { continue; } } dbesc_array($abook); $r = dbq("INSERT INTO abook (`" . implode("`, `", array_keys($abook)) . "`) VALUES ('" . implode("', '", array_values($abook)) . "')"); $friends++; if (intval($abook['abook_feed'])) { $feeds++; } translate_abook_perms_inbound($channel, $abook_copy); if ($abconfig) { // @fixme does not handle sync of del_abconfig foreach ($abconfig as $abc) { set_abconfig($channel['channel_id'], $abc['xchan'], $abc['cat'], $abc['k'], $abc['v']); } } } } logger('import step 8'); $_SESSION['import_step'] = 8; } if ($completed < 9) { $groups = $data['group']; if ($groups) { $saved = array(); foreach ($groups as $group) { $saved[$group['hash']] = array('old' => $group['id']); if (array_key_exists('name', $group)) { $group['gname'] = $group['name']; unset($group['name']); } unset($group['id']); $group['uid'] = $channel['channel_id']; dbesc_array($group); $r = dbq("INSERT INTO groups (`" . implode("`, `", array_keys($group)) . "`) VALUES ('" . implode("', '", array_values($group)) . "')"); } $r = q("select * from `groups` where uid = %d", intval($channel['channel_id'])); if ($r) { foreach ($r as $rr) { $saved[$rr['hash']]['new'] = $rr['id']; } } } $group_members = $data['group_member']; if ($group_members) { foreach ($group_members as $group_member) { unset($group_member['id']); $group_member['uid'] = $channel['channel_id']; foreach ($saved as $x) { if ($x['old'] == $group_member['gid']) { $group_member['gid'] = $x['new']; } } dbesc_array($group_member); $r = dbq("INSERT INTO group_member (`" . implode("`, `", array_keys($group_member)) . "`) VALUES ('" . implode("', '", array_values($group_member)) . "')"); } } logger('import step 9'); $_SESSION['import_step'] = 9; } if (is_array($data['obj'])) { import_objs($channel, $data['obj']); } if (is_array($data['likes'])) { import_likes($channel, $data['likes']); } if (is_array($data['app'])) { import_apps($channel, $data['app']); } if (is_array($data['chatroom'])) { import_chatrooms($channel, $data['chatroom']); } if (is_array($data['conv'])) { import_conv($channel, $data['conv']); } if (is_array($data['mail'])) { import_mail($channel, $data['mail']); } if (is_array($data['event'])) { import_events($channel, $data['event']); } if (is_array($data['event_item'])) { import_items($channel, $data['event_item'], false, $relocate); } if (is_array($data['menu'])) { import_menus($channel, $data['menu']); } $addon = array('channel' => $channel, 'data' => $data); call_hooks('import_channel', $addon); $saved_notification_flags = notifications_off($channel['channel_id']); if ($import_posts && array_key_exists('item', $data) && $data['item']) { import_items($channel, $data['item'], false, $relocate); } notifications_on($channel['channel_id'], $saved_notification_flags); if (array_key_exists('item_id', $data) && $data['item_id']) { import_item_ids($channel, $data['item_id']); } // FIXME - ensure we have a self entry if somebody is trying to pull a fast one // send out refresh requests // notify old server that it may no longer be primary. \Zotlabs\Daemon\Master::Summon(array('Notifier', 'location', $channel['channel_id'])); // This will indirectly perform a refresh_all *and* update the directory \Zotlabs\Daemon\Master::Summon(array('Directory', $channel['channel_id'])); notice(t('Import completed.') . EOL); change_channel($channel['channel_id']); unset($_SESSION['import_step']); goaway(z_root() . '/network'); }
function import_conv($channel, $convs) { if ($channel && $convs) { foreach ($convs as $conv) { if ($conv['deleted']) { q("delete from conv where guid = '%s' and uid = %d limit 1", dbesc($conv['guid']), intval($channel['channel_id'])); continue; } unset($conv['id']); $conv['uid'] = $channel['channel_id']; $conv['subject'] = str_rot47(base64url_encode($conv['subject'])); $r = q("select id from conv where guid = '%s' and uid = %d limit 1", dbesc($conv['guid']), intval($channel['channel_id'])); if ($r) { continue; } dbesc_array($conv); $r = dbq("INSERT INTO conv (`" . implode("`, `", array_keys($conv)) . "`) VALUES ('" . implode("', '", array_values($conv)) . "')"); } } }
function mail_store($arr) { if (!$arr['channel_id']) { logger('mail_store: no uid'); return 0; } if (strpos($arr['body'], '<') !== false || strpos($arr['body'], '>') !== false) { $arr['body'] = escape_tags($arr['body']); } if (array_key_exists('attach', $arr) && is_array($arr['attach'])) { $arr['attach'] = json_encode($arr['attach']); } $arr['account_id'] = x($arr, 'account_id') ? intval($arr['account_id']) : 0; $arr['mid'] = x($arr, 'mid') ? notags(trim($arr['mid'])) : random_string(); $arr['from_xchan'] = x($arr, 'from_xchan') ? notags(trim($arr['from_xchan'])) : ''; $arr['to_xchan'] = x($arr, 'to_xchan') ? notags(trim($arr['to_xchan'])) : ''; $arr['created'] = x($arr, 'created') !== false ? datetime_convert('UTC', 'UTC', $arr['created']) : datetime_convert(); $arr['expires'] = x($arr, 'expires') !== false ? datetime_convert('UTC', 'UTC', $arr['expires']) : NULL_DATE; $arr['title'] = x($arr, 'title') ? notags(trim($arr['title'])) : ''; $arr['parent_mid'] = x($arr, 'parent_mid') ? notags(trim($arr['parent_mid'])) : ''; $arr['body'] = x($arr, 'body') ? trim($arr['body']) : ''; $arr['mail_flags'] = x($arr, 'mail_flags') ? intval($arr['mail_flags']) : 0; if (!$arr['parent_mid']) { logger('mail_store: missing parent'); $arr['parent_mid'] = $arr['mid']; } $r = q("SELECT `id` FROM mail WHERE `mid` = '%s' AND channel_id = %d LIMIT 1", dbesc($arr['mid']), intval($arr['channel_id'])); if ($r) { logger('mail_store: duplicate item ignored. ' . print_r($arr, true)); return 0; } call_hooks('post_mail', $arr); if (x($arr, 'cancel')) { logger('mail_store: post cancelled by plugin.'); return 0; } dbesc_array($arr); logger('mail_store: ' . print_r($arr, true), LOGGER_DATA); $r = dbq("INSERT INTO mail (`" . implode("`, `", array_keys($arr)) . "`) VALUES ('" . implode("', '", array_values($arr)) . "')"); // find the item we just created $r = q("SELECT `id` FROM mail WHERE `mid` = '%s' AND `channel_id` = %d ORDER BY `id` ASC ", $arr['mid'], intval($arr['channel_id'])); if ($r) { $current_post = $r[0]['id']; logger('mail_store: created item ' . $current_post, LOGGER_DEBUG); $arr['id'] = $current_post; // for notification } else { logger('mail_store: could not locate created item'); return 0; } if (count($r) > 1) { logger('mail_store: duplicated post occurred. Removing duplicates.'); q("DELETE FROM mail WHERE `mid` = '%s' AND `channel_id` = %d AND `id` != %d ", $arr['mid'], intval($arr['channel_id']), intval($current_post)); } else { require_once 'include/enotify.php'; $notif_params = array('from_xchan' => $arr['from_xchan'], 'to_xchan' => $arr['to_xchan'], 'type' => NOTIFY_MAIL, 'item' => $arr, 'verb' => ACTIVITY_POST, 'otype' => 'mail'); notification($notif_params); } call_hooks('post_mail_end', $arr); return $current_post; }
function profiles_content(&$a) { if (!local_user()) { notice(t('Permission denied.') . EOL); return; } if ($a->argc > 2 && $a->argv[1] == "drop" && intval($a->argv[2])) { $r = q("SELECT * FROM `profile` WHERE `id` = %d AND `is-default` = 0 AND `self` = 0 LIMIT 1", intval($a->argv[2])); if (!count($r)) { notice(t('Profile not found.') . EOL); goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } // move every contact using this profile as their default to the user default $r = q("UPDATE `contact` SET `profile-id` = (SELECT `profile`.`id` AS `profile-id` FROM `profile` WHERE `profile`.`is-default` = 1 LIMIT 1) WHERE `profile-id` = %d ", intval($a->argv[2])); $r = q("DELETE FROM `profile` WHERE `id` = %d LIMIT 1", intval($a->argv[2])); if ($r) { notice(t('Profile deleted.') . EOL); } goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } if ($a->argc > 1 && $a->argv[1] == 'new') { $r0 = q("SELECT `id` FROM `profile` WHERE 1"); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT `name`, `photo`, `thumb` FROM `profile` WHERE `is-default` = 1 LIMIT 1"); $r2 = q("INSERT INTO `profile` (`profile-name` , `name`, `photo`, `thumb`)\n\t\t\tVALUES ( '%s', '%s', '%s', '%s' )", dbesc($name), dbesc($r1[0]['name']), dbesc($r1[0]['photo']), dbesc($ra[0]['thumb'])); $r3 = q("SELECT `id` FROM `profile` WHERE `profile-name` = '%s' LIMIT 1", dbesc($name)); notice(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl() . '/profiles'); } if ($a->argc > 2 && $a->argv[1] == 'clone') { $r0 = q("SELECT `id` FROM `profile` WHERE 1"); $num_profiles = count($r0); $name = t('Profile-') . ($num_profiles + 1); $r1 = q("SELECT * FROM `profile` WHERE `id` = %d LIMIT 1", intval($a->argv[2])); if (!count($r1)) { notice(t('Profile unavailable to clone.') . EOL); return; } unset($r1[0]['id']); $r1[0]['is-default'] = 0; $r1[0]['publish'] = 0; $r1[0]['net-publish'] = 0; $r1[0]['profile-name'] = dbesc($name); dbesc_array($r1[0]); $r2 = q("INSERT INTO `profile` (`" . implode("`, `", array_keys($r1[0])) . "`) VALUES ('" . implode("', '", array_values($r1[0])) . "')"); $r3 = q("SELECT `id` FROM `profile` WHERE `profile-name` = '%s' LIMIT 1", dbesc($name)); notice(t('New profile created.') . EOL); if (count($r3) == 1) { goaway($a->get_baseurl() . '/profiles/' . $r3[0]['id']); } goaway($a->get_baseurl() . '/profiles'); return; // NOTREACHED } if (intval($a->argv[1])) { $r = q("SELECT * FROM `profile` WHERE `id` = %d LIMIT 1", intval($a->argv[1])); if (!count($r)) { notice(t('Profile not found.') . EOL); return; } require_once 'mod/profile.php'; profile_load($a, $a->user['nickname'], $r[0]['id']); require_once 'view/profile_selectors.php'; $tpl = file_get_contents('view/profed_head.tpl'); $opt_tpl = file_get_contents("view/profile-hide-friends.tpl"); $hide_friends = replace_macros($opt_tpl, array('$yes_selected' => $r[0]['hide-friends'] ? " checked=\"checked\" " : "", '$no_selected' => $r[0]['hide-friends'] == 0 ? " checked=\"checked\" " : "")); $a->page['htmlhead'] .= replace_macros($tpl, array('$baseurl' => $a->get_baseurl())); $a->page['htmlhead'] .= "<script type=\"text/javascript\" src=\"include/country.js\" ></script>"; $is_default = $r[0]['is-default'] ? 1 : 0; $tpl = file_get_contents("view/profile_edit.tpl"); $o .= replace_macros($tpl, array('$disabled' => $is_default ? 'onclick="return false;" style="color: #BBBBFF;"' : '', '$baseurl' => $a->get_baseurl(), '$profile_id' => $r[0]['id'], '$profile_name' => $r[0]['profile-name'], '$default' => $is_default ? '<p id="profile-edit-default-desc">' . t('This is your <strong>public</strong> profile.<br />It <strong>may</strong> be visible to anybody using the internet.') . '</p>' : "", '$name' => $r[0]['name'], '$dob' => dob($r[0]['dob']), '$hide_friends' => $hide_friends, '$address' => $r[0]['address'], '$locality' => $r[0]['locality'], '$region' => $r[0]['region'], '$postal_code' => $r[0]['postal-code'], '$country_name' => $r[0]['country-name'], '$age' => intval($r[0]['dob']) ? '(' . t('Age: ') . age($r[0]['dob'], $a->user['timezone'], $a->user['timezone']) . ')' : '', '$gender' => gender_selector($r[0]['gender']), '$marital' => marital_selector($r[0]['marital']), '$sexual' => sexpref_selector($r[0]['sexual']), '$about' => $r[0]['about'], '$homepage' => $r[0]['homepage'], '$politic' => $r[0]['politic'], '$religion' => $r[0]['religion'], '$music' => $r[0]['music'], '$book' => $r[0]['book'], '$tv' => $r[0]['tv'], '$film' => $r[0]['film'], '$interest' => $r[0]['interest'], '$romance' => $r[0]['romance'], '$work' => $r[0]['work'], '$education' => $r[0]['education'], '$contact' => $r[0]['contact'])); return $o; } else { $r = q("SELECT * FROM `profile` WHERE 1"); if (count($r)) { $o .= file_get_contents('view/profile_listing_header.tpl'); $tpl_default = file_get_contents('view/profile_entry_default.tpl'); $tpl = file_get_contents('view/profile_entry.tpl'); foreach ($r as $rr) { $template = $rr['is-default'] ? $tpl_default : $tpl; $o .= replace_macros($template, array('$photo' => $rr['thumb'], '$id' => $rr['id'], '$profile_name' => $rr['profile-name'])); } } return $o; } }