コード例 #1
0
ファイル: chat.php プロジェクト: Mauru/red
/** @file */
function chatroom_create($channel, $arr)
{
    $ret = array('success' => false);
    $name = trim($arr['name']);
    if (!$name) {
        $ret['message'] = t('Missing room name');
        return $ret;
    }
    $r = q("select cr_id from chatroom where cr_uid = %d and cr_name = '%s' limit 1", intval($channel['channel_id']), dbesc($name));
    if ($r) {
        $ret['message'] = t('Duplicate room name');
        return $ret;
    }
    $r = q("select count(cr_id) as total from chatroom where cr_aid = %d", intval($channel['channel_account_id']));
    if ($r) {
        $limit = service_class_fetch($channel_id, 'chatrooms');
    }
    if ($r && $limit !== false && $r[0]['total'] >= $limit) {
        $ret['message'] = upgrade_message();
        return $ret;
    }
    if (!array_key_exists('expire', $arr)) {
        $arr['expire'] = 120;
    }
    // minutes, e.g. 2 hours
    $created = datetime_convert();
    $x = q("insert into chatroom ( cr_aid, cr_uid, cr_name, cr_created, cr_edited, cr_expire, allow_cid, allow_gid, deny_cid, deny_gid )\n\t\tvalues ( %d, %d , '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel['channel_id']), dbesc($name), dbesc($created), dbesc($created), intval($arr['expire']), dbesc($arr['allow_cid']), dbesc($arr['allow_gid']), dbesc($arr['deny_cid']), dbesc($arr['deny_gid']));
    if ($x) {
        $ret['success'] = true;
    }
    return $ret;
}
コード例 #2
0
ファイル: identity.php プロジェクト: Mauru/red
/**
 * @function identity_check_service_class($account_id)
 *     Called when creating a new channel. Checks the account's service class and number
 * of current channels to determine whether creating a new channel is within the current
 * service class constraints.
 *
 * @param int $account_id
 *     Account_id used for this request
 *
 * @returns array
 *       'success' => boolean true if creating a new channel is allowed for this account
 *       'message' => if success is false, optional error text
 */
function identity_check_service_class($account_id)
{
    $ret = array('success' => false, $message => '');
    $r = q("select count(channel_id) as total from channel where channel_account_id = %d and not ( channel_pageflags & %d ) ", intval($account_id), intval(PAGE_REMOVED));
    if (!($r && count($r))) {
        $ret['message'] = t('Unable to obtain identity information from database');
        return $ret;
    }
    if (!service_class_allows($account_id, 'total_identities', $r[0]['total'])) {
        $result['message'] .= upgrade_message();
        return $result;
    }
    $ret['success'] = true;
    return $ret;
}
コード例 #3
0
ファイル: identity.php プロジェクト: 23n/hubzilla
/**
 * @brief Called when creating a new channel.
 *
 * Checks the account's service class and number of current channels to determine
 * whether creating a new channel is within the current service class constraints.
 *
 * @param int $account_id
 *     Account_id used for this request
 *
 * @returns assoziative array with:
 *  * \e boolean \b success boolean true if creating a new channel is allowed for this account
 *  * \e string \b message (optional) if success is false, optional error text
 *  * \e int \b total_identities
 */
function identity_check_service_class($account_id)
{
    $ret = array('success' => false, 'message' => '');
    $r = q("select count(channel_id) as total from channel where channel_account_id = %d and channel_removed = 0 ", intval($account_id));
    if (!($r && count($r))) {
        $ret['total_identities'] = 0;
        $ret['message'] = t('Unable to obtain identity information from database');
        return $ret;
    }
    $ret['total_identities'] = intval($r[0]['total']);
    if (!account_service_class_allows($account_id, 'total_identities', $r[0]['total'])) {
        $ret['message'] .= upgrade_message();
        return $ret;
    }
    $ret['success'] = true;
    return $ret;
}
コード例 #4
0
ファイル: wall_upload.php プロジェクト: ZerGabriel/friendica
function wall_upload_post(&$a, $desktopmode = true)
{
    logger("wall upload: starting new upload", LOGGER_DEBUG);
    $r_json = x($_GET, 'response') && $_GET['response'] == 'json';
    if ($a->argc > 1) {
        if (!x($_FILES, 'media')) {
            $nick = $a->argv[1];
            $r = q("SELECT `user`.*, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`  WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1", dbesc($nick));
            if (!count($r)) {
                if ($r_json) {
                    echo json_encode(['error' => t('Invalid request.')]);
                    killme();
                }
                return;
            }
        } else {
            $user_info = api_get_user($a);
            $r = q("SELECT `user`.*, `contact`.`id` FROM `user` INNER JOIN `contact` on `user`.`uid` = `contact`.`uid`  WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1", dbesc($user_info['screen_name']));
        }
    } else {
        if ($r_json) {
            echo json_encode(['error' => t('Invalid request.')]);
            killme();
        }
        return;
    }
    $can_post = false;
    $visitor = 0;
    $page_owner_uid = $r[0]['uid'];
    $default_cid = $r[0]['id'];
    $page_owner_nick = $r[0]['nickname'];
    $community_page = $r[0]['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $page_owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            $cid = 0;
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $page_owner_uid) {
                        $cid = $v['cid'];
                        break;
                    }
                }
            }
            if ($cid) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($cid), intval($page_owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $visitor = $cid;
                }
            }
        }
    }
    if (!$can_post) {
        if ($r_json) {
            echo json_encode(['error' => t('Permission denied.')]);
            killme();
        }
        notice(t('Permission denied.') . EOL);
        killme();
    }
    if (!x($_FILES, 'userfile') && !x($_FILES, 'media')) {
        if ($r_json) {
            echo json_encode(['error' => t('Invalid request.')]);
            killme();
        }
        killme();
    }
    $src = "";
    if (x($_FILES, 'userfile')) {
        $src = $_FILES['userfile']['tmp_name'];
        $filename = basename($_FILES['userfile']['name']);
        $filesize = intval($_FILES['userfile']['size']);
        $filetype = $_FILES['userfile']['type'];
    } elseif (x($_FILES, 'media')) {
        if (is_array($_FILES['media']['tmp_name'])) {
            $src = $_FILES['media']['tmp_name'][0];
        } else {
            $src = $_FILES['media']['tmp_name'];
        }
        if (is_array($_FILES['media']['name'])) {
            $filename = basename($_FILES['media']['name'][0]);
        } else {
            $filename = basename($_FILES['media']['name']);
        }
        if (is_array($_FILES['media']['size'])) {
            $filesize = intval($_FILES['media']['size'][0]);
        } else {
            $filesize = intval($_FILES['media']['size']);
        }
        if (is_array($_FILES['media']['type'])) {
            $filetype = $_FILES['media']['type'][0];
        } else {
            $filetype = $_FILES['media']['type'];
        }
    }
    if ($src == "") {
        if ($r_json) {
            echo json_encode(['error' => t('Invalid request.')]);
            killme();
        }
        notice(t('Invalid request.') . EOL);
        killme();
    }
    // This is a special treatment for picture upload from Twidere
    if ($filename == "octet-stream" and $filetype != "") {
        $filename = $filetype;
        $filetype = "";
    }
    if ($filetype == "") {
        $filetype = guess_image_type($filename);
    }
    // If there is a temp name, then do a manual check
    // This is more reliable than the provided value
    $imagedata = getimagesize($src);
    if ($imagedata) {
        $filetype = $imagedata['mime'];
    }
    logger("File upload src: " . $src . " - filename: " . $filename . " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
    $maximagesize = get_config('system', 'maximagesize');
    if ($maximagesize && $filesize > $maximagesize) {
        $msg = sprintf(t('Image exceeds size limit of %s'), formatBytes($maximagesize));
        if ($r_json) {
            echo json_encode(['error' => $msg]);
        } else {
            echo $msg . EOL;
        }
        @unlink($src);
        killme();
    }
    $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ", intval($page_owner_uid));
    $limit = service_class_fetch($page_owner_uid, 'photo_upload_limit');
    if ($limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        $msg = upgrade_message(true);
        if ($r_json) {
            echo json_encode(['error' => $msg]);
        } else {
            echo $msg . EOL;
        }
        @unlink($src);
        killme();
    }
    $imagedata = @file_get_contents($src);
    $ph = new Photo($imagedata, $filetype);
    if (!$ph->is_valid()) {
        $msg = t('Unable to process image.');
        if ($r_json) {
            echo json_encode(['error' => $msg]);
        } else {
            echo $msg . EOL;
        }
        @unlink($src);
        killme();
    }
    $ph->orient($src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
        logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $hash = photo_new_resource();
    $smallest = 0;
    $defperm = '<' . $default_cid . '>';
    $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 0, 0, $defperm);
    if (!$r) {
        $msg = t('Image upload failed.');
        if ($r_json) {
            echo json_encode(['error' => $msg]);
        } else {
            echo $msg . EOL;
        }
        killme();
    }
    if ($width > 640 || $height > 640) {
        $ph->scaleImage(640);
        $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 1, 0, $defperm);
        if ($r) {
            $smallest = 1;
        }
    }
    if ($width > 320 || $height > 320) {
        $ph->scaleImage(320);
        $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 2, 0, $defperm);
        if ($r and $smallest == 0) {
            $smallest = 2;
        }
    }
    $basename = basename($filename);
    if (!$desktopmode) {
        $r = q("SELECT `id`, `datasize`, `width`, `height`, `type` FROM `photo` WHERE `resource-id` = '%s' ORDER BY `width` DESC LIMIT 1", $hash);
        if (!$r) {
            if ($r_json) {
                echo json_encode(['error' => '']);
                killme();
            }
            return false;
        }
        $picture = array();
        $picture["id"] = $r[0]["id"];
        $picture["size"] = $r[0]["datasize"];
        $picture["width"] = $r[0]["width"];
        $picture["height"] = $r[0]["height"];
        $picture["type"] = $r[0]["type"];
        $picture["albumpage"] = $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash;
        $picture["picture"] = $a->get_baseurl() . "/photo/{$hash}-0." . $ph->getExt();
        $picture["preview"] = $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt();
        if ($r_json) {
            echo json_encode(['picture' => $picture]);
            killme();
        }
        return $picture;
    }
    if ($r_json) {
        echo json_encode(['ok' => true]);
        killme();
    }
    /* mod Waitman Gobble NO WARRANTY */
    //if we get the signal then return the image url info in BBCODE, otherwise this outputs the info and bails (for the ajax image uploader on wall post)
    if ($_REQUEST['hush'] != 'yeah') {
        if (local_user() && (!feature_enabled(local_user(), 'richtext') || x($_REQUEST['nomce']))) {
            echo "\n\n" . '[url=' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '][img]' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "[/img][/url]\n\n";
        } else {
            echo '<br /><br /><a href="' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '" ><img src="' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "\" alt=\"{$basename}\" /></a><br /><br />";
        }
    } else {
        $m = '[url=' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '][img]' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "[/img][/url]";
        return $m;
    }
    /* mod Waitman Gobble NO WARRANTY */
    killme();
    // NOTREACHED
}
コード例 #5
0
ファイル: item.php プロジェクト: einervonvielen/redmatrix
function item_check_service_class($channel_id, $iswebpage)
{
    $ret = array('success' => false, 'message' => '');
    if ($iswebpage) {
        // note: we aren't counting comanche templates and blocks, only webpages
        $r = q("select count(id) as total from item where parent = id \n\t\t\tand ( item_restrict & %d ) > 0 and ( item_restrict & %d ) = 0 and uid = %d ", intval(ITEM_WEBPAGE), intval(ITEM_DELETED), intval($channel_id));
    } else {
        $r = q("select count(id) as total from item where parent = id and item_restrict = 0 and (item_flags & %d) > 0 and uid = %d ", intval(ITEM_WALL), intval($channel_id));
    }
    if (!$r) {
        $ret['message'] = t('Unable to obtain post information from database.');
        return $ret;
    }
    if (!$iswebpage) {
        $max = service_class_fetch($channel_id, 'total_items');
        if (!service_class_allows($channel_id, 'total_items', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t('You have reached your limit of %1$.0f top level posts.'), $max);
            return $result;
        }
    } else {
        $max = service_class_fetch($channel_id, 'total_pages');
        if (!service_class_allows($channel_id, 'total_pages', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t('You have reached your limit of %1$.0f webpages.'), $max);
            return $result;
        }
    }
    $ret['success'] = true;
    return $ret;
}
コード例 #6
0
ファイル: attach.php プロジェクト: spthaolt/hubzilla
/**
 * A lot going on in this function, and some of it is old cruft and some is new cruft
 * and the entire thing probably needs to be refactored. It started out just storing
 * files, before we had DAV. It was made extensible to do extra stuff like edit an 
 * existing file or optionally store a separate revision using $options to choose between different
 * storage models. Along the way we moved from
 * DB data storage to file system storage. 
 * Then DAV came along and used different upload methods depending on whether the 
 * file was stored as a DAV directory object or updated as a file object. One of these 
 * is essentially an update and the other is basically an upload, but doesn't use the traditional PHP
 * upload workflow. 
 * Then came hubzilla and we tried to merge photo functionality with the file storage. Most of
 * that integration occurs within this function. 
 * This required overlap with the old photo_upload stuff and photo albums were
 * completely different concepts from directories which needed to be reconciled somehow.
 * The old revision stuff is kind of orphaned currently. There's new revision stuff for photos
 * which attaches (2) etc. onto the name, but doesn't integrate with the attach table revisioning.
 * That's where it sits currently. I repeat it needs to be refactored, and this note is here
 * for future explorers and those who may be doing that work to understand where it came
 * from and got to be the monstrosity of tangled unrelated code that it currently is.
 */
function attach_store($channel, $observer_hash, $options = '', $arr = null)
{
    require_once 'include/photos.php';
    call_hooks('photo_upload_begin', $arr);
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $sql_options = '';
    $source = $arr ? $arr['source'] : '';
    $album = $arr ? $arr['album'] : '';
    $newalbum = $arr ? $arr['newalbum'] : '';
    $hash = $arr && $arr['hash'] ? $arr['hash'] : null;
    $upload_path = $arr && $arr['directory'] ? $arr['directory'] : '';
    $visible = $arr && $arr['visible'] ? $arr['visible'] : '';
    $observer = array();
    if ($observer_hash) {
        $x = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($observer_hash));
        if ($x) {
            $observer = $x[0];
        }
    }
    logger('arr: ' . print_r($arr, true));
    if (!perm_is_allowed($channel_id, $observer_hash, 'write_storage')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    $str_group_allow = perms2str($arr['group_allow']);
    $str_contact_allow = perms2str($arr['contact_allow']);
    $str_group_deny = perms2str($arr['group_deny']);
    $str_contact_deny = perms2str($arr['contact_deny']);
    // The 'update' option sets db values without uploading a new attachment
    // 'replace' replaces the existing uploaded data
    // 'revision' creates a new revision with new upload data
    // Default is to upload a new file
    // revise or update must provide $arr['hash'] of the thing to revise/update
    // By default remove $src when finished
    $remove_when_processed = true;
    if ($options === 'import') {
        $src = $arr['src'];
        $filename = $arr['filename'];
        $filesize = @filesize($src);
        $hash = $arr['resource_id'];
        if (array_key_exists('hash', $arr)) {
            $hash = $arr['hash'];
        }
        if (array_key_exists('type', $arr)) {
            $type = $arr['type'];
        }
        if ($arr['preserve_original']) {
            $remove_when_processed = false;
        }
        // if importing a directory, just do it now and go home - we're done.
        if (array_key_exists('is_dir', $arr) && intval($arr['is_dir'])) {
            $x = attach_mkdir($channel, $observer_hash, $arr);
            if ($x['message']) {
                logger('import_directory: ' . $x['message']);
            }
            return;
        }
    } elseif ($options !== 'update') {
        $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
        call_hooks('photo_upload_file', $f);
        call_hooks('attach_upload_file', $f);
        if (x($f, 'src') && x($f, 'filesize')) {
            $src = $f['src'];
            $filename = $f['filename'];
            $filesize = $f['filesize'];
            $type = $f['type'];
        } else {
            if (!x($_FILES, 'userfile')) {
                $ret['message'] = t('No source file.');
                return $ret;
            }
            $src = $_FILES['userfile']['tmp_name'];
            $filename = basename($_FILES['userfile']['name']);
            $filesize = intval($_FILES['userfile']['size']);
        }
    }
    $existing_size = 0;
    if ($options === 'replace') {
        $x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1", intval($arr['id']), intval($channel_id));
        if (!$x) {
            $ret['message'] = t('Cannot locate file to replace');
            return $ret;
        }
        $existing_id = $x[0]['id'];
        $existing_size = intval($x[0]['filesize']);
        $hash = $x[0]['hash'];
    }
    if ($options === 'revise' || $options === 'update') {
        $sql_options = " order by revision desc ";
        if ($options === 'update' && $arr && array_key_exists('revision', $arr)) {
            $sql_options = " and revision = " . intval($arr['revision']) . " ";
        }
        $x = q("select id, aid, uid, filename, filetype, filesize, hash, revision, folder, os_storage, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where hash = '%s' and uid = %d {$sql_options} limit 1", dbesc($arr['hash']), intval($channel_id));
        if (!$x) {
            $ret['message'] = t('Cannot locate file to revise/update');
            return $ret;
        }
        $hash = $x[0]['hash'];
    }
    $def_extension = '';
    $is_photo = 0;
    $gis = @getimagesize($src);
    logger('getimagesize: ' . print_r($gis, true), LOGGER_DATA);
    if ($gis && ($gis[2] === IMAGETYPE_GIF || $gis[2] === IMAGETYPE_JPEG || $gis[2] === IMAGETYPE_PNG)) {
        $is_photo = 1;
        if ($gis[2] === IMAGETYPE_GIF) {
            $def_extension = '.gif';
        }
        if ($gis[2] === IMAGETYPE_JPEG) {
            $def_extension = '.jpg';
        }
        if ($gis[2] === IMAGETYPE_PNG) {
            $def_extension = '.png';
        }
    }
    $pathname = '';
    if ($is_photo) {
        if ($newalbum) {
            $pathname = filepath_macro($newalbum);
        } elseif (array_key_exists('folder', $arr)) {
            $x = q("select filename from attach where hash = '%s' and uid = %d limit 1", dbesc($arr['folder']), intval($channel['channel_id']));
            if ($x) {
                $pathname = $x[0]['filename'];
            }
        } else {
            $pathname = filepath_macro($album);
        }
    } else {
        $pathname = filepath_macro($upload_path);
    }
    $darr = array('pathname' => $pathname);
    // if we need to create a directory, use the channel default permissions.
    $darr['allow_cid'] = $channel['allow_cid'];
    $darr['allow_gid'] = $channel['allow_gid'];
    $darr['deny_cid'] = $channel['deny_cid'];
    $darr['deny_gid'] = $channel['deny_gid'];
    $direct = null;
    if ($pathname) {
        $x = attach_mkdirp($channel, $observer_hash, $darr);
        $folder_hash = $x['success'] ? $x['data']['hash'] : '';
        $direct = $x['success'] ? $x['data'] : null;
        if (!$str_contact_allow && !$str_group_allow && !$str_contact_deny && !$str_group_deny) {
            $str_contact_allow = $x['data']['allow_cid'];
            $str_group_allow = $x['data']['allow_gid'];
            $str_contact_deny = $x['data']['deny_cid'];
            $str_group_deny = $x['data']['deny_gid'];
        }
    } else {
        $folder_hash = $arr && array_key_exists('folder', $arr) ? $arr['folder'] : '';
    }
    if (!$options || $options === 'import') {
        // A freshly uploaded file. Check for duplicate and resolve with the channel's overwrite settings.
        $r = q("select filename, id, hash, filesize from attach where filename = '%s' and folder = '%s' ", dbesc($filename), dbesc($folder_hash));
        if ($r) {
            $overwrite = get_pconfig($channel_id, 'system', 'overwrite_dup_files');
            if ($overwrite) {
                $options = 'replace';
                $existing_id = $x[0]['id'];
                $existing_size = intval($x[0]['filesize']);
                $hash = $x[0]['hash'];
            } else {
                if (strpos($filename, '.') !== false) {
                    $basename = substr($filename, 0, strrpos($filename, '.'));
                    $ext = substr($filename, strrpos($filename, '.'));
                } else {
                    $basename = $filename;
                    $ext = $def_extension;
                }
                $r = q("select filename from attach where ( filename = '%s' OR filename like '%s' ) and folder = '%s' ", dbesc($basename . $ext), dbesc($basename . '(%)' . $ext), dbesc($folder_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);
                    $filename = $basename . '(' . $x . ')' . $ext;
                } else {
                    $filename = $basename . $ext;
                }
            }
        }
    }
    if (!$hash) {
        $hash = random_string();
    }
    // Check storage limits
    if ($options !== 'update') {
        $maxfilesize = get_config('system', 'maxfilesize');
        if ($maxfilesize && $filesize > $maxfilesize) {
            $ret['message'] = sprintf(t('File exceeds size limit of %d'), $maxfilesize);
            if ($remove_when_processed) {
                @unlink($src);
            }
            call_hooks('photo_upload_end', $ret);
            return $ret;
        }
        $limit = service_class_fetch($channel_id, 'attach_upload_limit');
        if ($limit !== false) {
            $r = q("select sum(filesize) as total from attach where aid = %d ", intval($channel['channel_account_id']));
            if ($r && $r[0]['total'] + $filesize > $limit - $existing_size) {
                $ret['message'] = upgrade_message(true) . sprintf(t("You have reached your limit of %1\$.0f Mbytes attachment storage."), $limit / 1024000);
                if ($remove_when_processed) {
                    @unlink($src);
                }
                call_hooks('photo_upload_end', $ret);
                return $ret;
            }
        }
        $mimetype = isset($type) && $type ? $type : z_mime_content_type($filename);
    }
    $os_basepath = 'store/' . $channel['channel_address'] . '/';
    $os_relpath = '';
    if ($folder_hash) {
        $curr = find_folder_hash_by_attach_hash($channel_id, $folder_hash, true);
        if ($curr) {
            $os_relpath .= $curr . '/';
        }
        $os_relpath .= $folder_hash . '/';
    }
    $os_relpath .= $hash;
    if ($src) {
        @file_put_contents($os_basepath . $os_relpath, @file_get_contents($src));
    }
    if (array_key_exists('created', $arr)) {
        $created = $arr['created'];
    } else {
        $created = datetime_convert();
    }
    if (array_key_exists('edited', $arr)) {
        $edited = $arr['edited'];
    } else {
        $edited = $created;
    }
    if ($options === 'replace') {
        $r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', filesize = %d, os_storage = %d, is_photo = %d, data = '%s', edited = '%s' where id = %d and uid = %d", dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval(1), intval($is_photo), dbesc($os_relpath), dbesc($created), intval($existing_id), intval($channel_id));
    } elseif ($options === 'revise') {
        $r = q("insert into attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, data, created, edited, allow_cid, allow_gid, deny_cid, deny_gid )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($x[0]['aid']), intval($channel_id), dbesc($x[0]['hash']), dbesc($observer_hash), dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval($x[0]['revision'] + 1), intval(1), intval($is_photo), dbesc($os_relpath), dbesc($created), dbesc($created), dbesc($x[0]['allow_cid']), dbesc($x[0]['allow_gid']), dbesc($x[0]['deny_cid']), dbesc($x[0]['deny_gid']));
    } elseif ($options === 'update') {
        $r = q("update attach set filename = '%s', filetype = '%s', folder = '%s', edited = '%s', os_storage = %d, is_photo = %d, \n\t\t\tallow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid  = '%s' where id = %d and uid = %d", dbesc(array_key_exists('filename', $arr) ? $arr['filename'] : $x[0]['filename']), dbesc(array_key_exists('filetype', $arr) ? $arr['filetype'] : $x[0]['filetype']), dbesc($folder_hash ? $folder_hash : $x[0]['folder']), dbesc($created), dbesc(array_key_exists('os_storage', $arr) ? $arr['os_storage'] : $x[0]['os_storage']), dbesc(array_key_exists('is_photo', $arr) ? $arr['is_photo'] : $x[0]['is_photo']), dbesc(array_key_exists('allow_cid', $arr) ? $arr['allow_cid'] : $x[0]['allow_cid']), dbesc(array_key_exists('allow_gid', $arr) ? $arr['allow_gid'] : $x[0]['allow_gid']), dbesc(array_key_exists('deny_cid', $arr) ? $arr['deny_cid'] : $x[0]['deny_cid']), dbesc(array_key_exists('deny_gid', $arr) ? $arr['deny_gid'] : $x[0]['deny_gid']), intval($x[0]['id']), intval($x[0]['uid']));
    } else {
        $r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, folder, filesize, revision, os_storage, is_photo, data, created, edited, allow_cid, allow_gid,deny_cid, deny_gid )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel_id), dbesc($hash), dbesc(get_observer_hash()), dbesc($filename), dbesc($mimetype), dbesc($folder_hash), intval($filesize), intval(0), intval(1), intval($is_photo), dbesc($os_relpath), dbesc($created), dbesc($created), dbesc($arr && array_key_exists('allow_cid', $arr) ? $arr['allow_cid'] : $str_contact_allow), dbesc($arr && array_key_exists('allow_gid', $arr) ? $arr['allow_gid'] : $str_group_allow), dbesc($arr && array_key_exists('deny_cid', $arr) ? $arr['deny_cid'] : $str_contact_deny), dbesc($arr && array_key_exists('deny_gid', $arr) ? $arr['deny_gid'] : $str_group_deny));
    }
    if ($is_photo) {
        $args = array('source' => $source, 'visible' => $visible, 'resource_id' => $hash, 'album' => basename($pathname), 'os_path' => $os_basepath . $os_relpath, 'filename' => $filename, 'getimagesize' => $gis, 'directory' => $direct);
        if ($arr['contact_allow']) {
            $args['contact_allow'] = $arr['contact_allow'];
        }
        if ($arr['group_allow']) {
            $args['group_allow'] = $arr['group_allow'];
        }
        if ($arr['contact_deny']) {
            $args['contact_deny'] = $arr['contact_deny'];
        }
        if ($arr['group_deny']) {
            $args['group_deny'] = $arr['group_deny'];
        }
        if (array_key_exists('allow_cid', $arr)) {
            $args['allow_cid'] = $arr['allow_cid'];
        }
        if (array_key_exists('allow_gid', $arr)) {
            $args['allow_gid'] = $arr['allow_gid'];
        }
        if (array_key_exists('deny_cid', $arr)) {
            $args['deny_cid'] = $arr['deny_cid'];
        }
        if (array_key_exists('deny_gid', $arr)) {
            $args['deny_gid'] = $arr['deny_gid'];
        }
        $args['created'] = $created;
        $args['edited'] = $edited;
        if ($arr['item']) {
            $args['item'] = $arr['item'];
        }
        $p = photo_upload($channel, $observer, $args);
        if ($p['success']) {
            $ret['body'] = $p['body'];
        }
    }
    if ($options !== 'update' && $remove_when_processed) {
        @unlink($src);
    }
    if (!$r) {
        $ret['message'] = t('File upload failed. Possible system limit or action terminated.');
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    // Caution: This re-uses $sql_options set further above
    $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, os_storage, is_photo, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d and hash = '%s' {$sql_options} limit 1", intval($channel_id), dbesc($hash));
    if (!$r) {
        $ret['message'] = t('Stored file could not be verified. Upload failed.');
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    $ret['success'] = true;
    $ret['data'] = $r[0];
    if (!$is_photo) {
        // This would've been called already with a success result in photos_upload() if it was a photo.
        call_hooks('photo_upload_end', $ret);
    }
    return $ret;
}
コード例 #7
0
ファイル: follow.php プロジェクト: ZerGabriel/friendica
function new_contact($uid, $url, $interactive = false)
{
    $result = array('cid' => -1, 'success' => false, 'message' => '');
    $a = get_app();
    // remove ajax junk, e.g. Twitter
    $url = str_replace('/#!/', '/', $url);
    if (!allowed_url($url)) {
        $result['message'] = t('Disallowed profile URL.');
        return $result;
    }
    if (!$url) {
        $result['message'] = t('Connect URL missing.');
        return $result;
    }
    $arr = array('url' => $url, 'contact' => array());
    call_hooks('follow', $arr);
    if (x($arr['contact'], 'name')) {
        $ret = $arr['contact'];
    } else {
        $ret = probe_url($url);
    }
    if ($ret['network'] === NETWORK_DFRN) {
        if ($interactive) {
            if (strlen($a->path)) {
                $myaddr = bin2hex($a->get_baseurl() . '/profile/' . $a->user['nickname']);
            } else {
                $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
            }
            goaway($ret['request'] . "&addr={$myaddr}");
            // NOTREACHED
        }
    } else {
        if (get_config('system', 'dfrn_only')) {
            $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
            $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
            return $result;
        }
    }
    // This extra param just confuses things, remove it
    if ($ret['network'] === NETWORK_DIASPORA) {
        $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
    }
    // do we have enough information?
    if (!(x($ret, 'name') && x($ret, 'poll') && (x($ret, 'url') || x($ret, 'addr')))) {
        $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
        if (!x($ret, 'poll')) {
            $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
        }
        if (!x($ret, 'name')) {
            $result['message'] .= t('An author or name was not found.') . EOL;
        }
        if (!x($ret, 'url')) {
            $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
        }
        if (strpos($url, '@') !== false) {
            $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
            $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
        }
        return $result;
    }
    if ($ret['network'] === NETWORK_OSTATUS && get_config('system', 'ostatus_disabled')) {
        $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
        $ret['notify'] = '';
    }
    if (!$ret['notify']) {
        $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
    }
    $writeable = $ret['network'] === NETWORK_OSTATUS && $ret['notify'] ? 1 : 0;
    $subhub = $ret['network'] === NETWORK_OSTATUS ? true : false;
    $hidden = $ret['network'] === NETWORK_MAIL ? 1 : 0;
    if ($ret['network'] === NETWORK_MAIL) {
        $writeable = 1;
    }
    if ($ret['network'] === NETWORK_DIASPORA) {
        $writeable = 1;
    }
    // check if we already have a contact
    // the poll url is more reliable than the profile url, as we may have
    // indirect links or webfinger links
    $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1", intval($uid), dbesc($ret['poll']), dbesc(normalise_link($ret['poll'])), dbesc($ret['network']));
    if (!count($r)) {
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1", intval($uid), dbesc(normalise_link($url)), dbesc($ret['network']));
    }
    if (count($r)) {
        // update contact
        if ($r[0]['rel'] == CONTACT_IS_FOLLOWER || $network === NETWORK_DIASPORA && $r[0]['rel'] == CONTACT_IS_SHARING) {
            q("UPDATE `contact` SET `rel` = %d , `subhub` = %d, `readonly` = 0 WHERE `id` = %d AND `uid` = %d", intval(CONTACT_IS_FRIEND), intval($subhub), intval($r[0]['id']), intval($uid));
        }
    } else {
        // check service class limits
        $r = q("select count(*) as total from contact where uid = %d and pending = 0 and self = 0", intval($uid));
        if (count($r)) {
            $total_contacts = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_contacts', $total_contacts)) {
            $result['message'] .= upgrade_message();
            return $result;
        }
        $r = q("select count(network) as total from contact where uid = %d and network = '%s' and pending = 0 and self = 0", intval($uid), dbesc($network));
        if (count($r)) {
            $total_network = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_contacts_' . $network, $total_network)) {
            $result['message'] .= upgrade_message();
            return $result;
        }
        $new_relation = $ret['network'] === NETWORK_MAIL ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING;
        if ($ret['network'] === NETWORK_DIASPORA) {
            $new_relation = CONTACT_IS_FOLLOWER;
        }
        // create contact record
        $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `batch`, `notify`, `poll`, `poco`, `name`, `nick`, `network`, `pubkey`, `rel`, `priority`,\n\t\t\t`writable`, `hidden`, `blocked`, `readonly`, `pending`, `subhub` )\n\t\t\tVALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, 0, 0, 0, %d ) ", intval($uid), dbesc(datetime_convert()), dbesc($ret['url']), dbesc(normalise_link($ret['url'])), dbesc($ret['addr']), dbesc($ret['alias']), dbesc($ret['batch']), dbesc($ret['notify']), dbesc($ret['poll']), dbesc($ret['poco']), dbesc($ret['name']), dbesc($ret['nick']), dbesc($ret['network']), dbesc($ret['pubkey']), intval($new_relation), intval($ret['priority']), intval($writeable), intval($hidden), intval($subhub));
    }
    $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1", dbesc($ret['url']), dbesc($ret['network']), intval($uid));
    if (!count($r)) {
        $result['message'] .= t('Unable to retrieve contact information.') . EOL;
        return $result;
    }
    $contact = $r[0];
    $contact_id = $r[0]['id'];
    $result['cid'] = $contact_id;
    $g = q("select def_gid from user where uid = %d limit 1", intval($uid));
    if ($g && intval($g[0]['def_gid'])) {
        require_once 'include/group.php';
        group_add_member($uid, '', $contact_id, $g[0]['def_gid']);
    }
    require_once "include/Photo.php";
    $photos = import_profile_photo($ret['photo'], $uid, $contact_id);
    $r = q("UPDATE `contact` SET `photo` = '%s',\n\t\t\t`thumb` = '%s',\n\t\t\t`micro` = '%s',\n\t\t\t`name-date` = '%s',\n\t\t\t`uri-date` = '%s',\n\t\t\t`avatar-date` = '%s'\n\t\t\tWHERE `id` = %d", dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert()), intval($contact_id));
    // pull feed and consume it, which should subscribe to the hub.
    proc_run('php', "include/onepoll.php", "{$contact_id}", "force");
    // create a follow slap
    $tpl = get_markup_template('follow_slap.tpl');
    $slap = replace_macros($tpl, array('$name' => $a->user['username'], '$profile_page' => $a->get_baseurl() . '/profile/' . $a->user['nickname'], '$photo' => $a->contact['photo'], '$thumb' => $a->contact['thumb'], '$published' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME), '$item_id' => 'urn:X-dfrn:' . $a->get_hostname() . ':follow:' . get_guid(32), '$title' => '', '$type' => 'text', '$content' => t('following'), '$nick' => $a->user['nickname'], '$verb' => ACTIVITY_FOLLOW, '$ostat_follow' => ''));
    $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`\n\t\t\tWHERE `user`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1", intval($uid));
    if (count($r)) {
        if ($contact['network'] == NETWORK_OSTATUS && strlen($contact['notify'])) {
            require_once 'include/salmon.php';
            slapper($r[0], $contact['notify'], $slap);
        }
        if ($contact['network'] == NETWORK_DIASPORA) {
            require_once 'include/diaspora.php';
            $ret = diaspora_share($a->user, $contact);
            logger('mod_follow: diaspora_share returns: ' . $ret);
        }
    }
    $result['success'] = true;
    return $result;
}
コード例 #8
0
ファイル: follow.php プロジェクト: kenrestivo/hubzilla
function new_contact($uid, $url, $channel, $interactive = false, $confirm = false)
{
    $result = array('success' => false, 'message' => '');
    $a = get_app();
    $is_red = false;
    $is_http = strpos($url, '://') !== false ? true : false;
    if ($is_http && substr($url, -1, 1) === '/') {
        $url = substr($url, 0, -1);
    }
    if (!allowed_url($url)) {
        $result['message'] = t('Channel is blocked on this site.');
        return $result;
    }
    if (!$url) {
        $result['message'] = t('Channel location missing.');
        return $result;
    }
    // check service class limits
    $r = q("select count(*) as total from abook where abook_channel = %d and abook_self = 0 ", intval($uid));
    if ($r) {
        $total_channels = $r[0]['total'];
    }
    if (!service_class_allows($uid, 'total_channels', $total_channels)) {
        $result['message'] = upgrade_message();
        return $result;
    }
    $arr = array('url' => $url, 'channel' => array());
    call_hooks('follow', $arr);
    if ($arr['channel']['success']) {
        $ret = $arr['channel'];
    } elseif (!$is_http) {
        $ret = zot_finger($url, $channel);
    }
    if ($ret && $ret['success']) {
        $is_red = true;
        $j = json_decode($ret['body'], true);
    }
    $my_perms = get_channel_default_perms($uid);
    $role = get_pconfig($uid, 'system', 'permissions_role');
    if ($role) {
        $x = get_role_perms($role);
        if ($x['perms_follow']) {
            $my_perms = $x['perms_follow'];
        }
    }
    if ($is_red && $j) {
        logger('follow: ' . $url . ' ' . print_r($j, true), LOGGER_DEBUG);
        if (!($j['success'] && $j['guid'])) {
            $result['message'] = t('Response from remote channel was incomplete.');
            logger('mod_follow: ' . $result['message']);
            return $result;
        }
        // Premium channel, set confirm before callback to avoid recursion
        if (array_key_exists('connect_url', $j) && $interactive && !$confirm) {
            goaway(zid($j['connect_url']));
        }
        // do we have an xchan and hubloc?
        // If not, create them.
        $x = import_xchan($j);
        if (array_key_exists('deleted', $j) && intval($j['deleted'])) {
            $result['message'] = t('Channel was deleted and no longer exists.');
            return $result;
        }
        if (!$x['success']) {
            return $x;
        }
        $xchan_hash = $x['hash'];
        $their_perms = 0;
        $global_perms = get_perms();
        if (array_key_exists('permissions', $j) && array_key_exists('data', $j['permissions'])) {
            $permissions = crypto_unencapsulate(array('data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']);
            if ($permissions) {
                $permissions = json_decode($permissions, true);
            }
            logger('decrypted permissions: ' . print_r($permissions, true), LOGGER_DATA);
        } else {
            $permissions = $j['permissions'];
        }
        foreach ($permissions as $k => $v) {
            if ($v) {
                $their_perms = $their_perms | intval($global_perms[$k][1]);
            }
        }
    } else {
        $their_perms = 0;
        $xchan_hash = '';
        $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
        if (!$r) {
            // attempt network auto-discovery
            if (strpos($url, '@') && !$is_http) {
                $r = discover_by_webbie($url);
            } elseif ($is_http) {
                $r = discover_by_url($url);
                $r['allowed'] = intval(get_config('system', 'feed_contacts'));
            }
            if ($r) {
                $r['channel_id'] = $uid;
                call_hooks('follow_allow', $r);
                if (!$r['allowed']) {
                    $result['message'] = t('Protocol disabled.');
                    return $result;
                }
                $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
            }
        }
        if ($r) {
            $xchan_hash = $r[0]['xchan_hash'];
            $their_perms = 0;
        }
    }
    if (!$xchan_hash) {
        $result['message'] = t('Channel discovery failed.');
        logger('follow: ' . $result['message']);
        return $result;
    }
    if (local_channel() && $uid == local_channel()) {
        $aid = get_account_id();
        $hash = get_observer_hash();
        $ch = $a->get_channel();
        $default_group = $ch['channel_default_group'];
    } else {
        $r = q("select * from channel where channel_id = %d limit 1", intval($uid));
        if (!$r) {
            $result['message'] = t('local account not found.');
            return $result;
        }
        $aid = $r[0]['channel_account_id'];
        $hash = $r[0]['channel_hash'];
        $default_group = $r[0]['channel_default_group'];
    }
    if ($is_http) {
        $r = q("select count(*) as total from abook where abook_account = %d and abook_feed = 1 ", intval($aid));
        if ($r) {
            $total_feeds = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_feeds', $total_feeds)) {
            $result['message'] = upgrade_message();
            return $result;
        }
    }
    if ($hash == $xchan_hash) {
        $result['message'] = t('Cannot connect to yourself.');
        return $result;
    }
    $r = q("select abook_xchan from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $x = q("update abook set abook_their_perms = %d where abook_id = %d", intval($their_perms), intval($r[0]['abook_id']));
    } else {
        $closeness = get_pconfig($uid, 'system', 'new_abook_closeness');
        if ($closeness === false) {
            $closeness = 80;
        }
        $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_feed, abook_their_perms, abook_my_perms, abook_created, abook_updated )\n\t\t\tvalues( %d, %d, %d, '%s', %d, %d, %d, '%s', '%s' ) ", intval($aid), intval($uid), intval($closeness), dbesc($xchan_hash), intval($is_http ? 1 : 0), intval($is_http ? $their_perms | PERMS_R_STREAM | PERMS_A_REPUBLISH : $their_perms), intval($my_perms), dbesc(datetime_convert()), dbesc(datetime_convert()));
    }
    if (!$r) {
        logger('mod_follow: abook creation failed');
    }
    $r = q("select abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash \n\t\twhere abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $result['abook'] = $r[0];
        proc_run('php', 'include/notifier.php', 'permission_update', $result['abook']['abook_id']);
    }
    $arr = array('channel_id' => $uid, 'abook' => $result['abook']);
    call_hooks('follow', $arr);
    /** If there is a default group for this channel, add this member to it */
    if ($default_group) {
        require_once 'include/group.php';
        $g = group_rec_byhash($uid, $default_group);
        if ($g) {
            group_add_member($uid, '', $xchan_hash, $g['id']);
        }
    }
    $result['success'] = true;
    return $result;
}
コード例 #9
0
ファイル: item.php プロジェクト: Mauru/red
function item_check_service_class($channel_id, $iswebpage)
{
    $ret = array('success' => false, $message => '');
    if ($iswebpage) {
        $r = q("select count(i.id)  as total from item i \n\t\t\tright join channel c on (i.author_xchan=c.channel_hash and i.uid=c.channel_id )  \n\t\t\tand i.parent=i.id and (i.item_restrict & %d) and not (i.item_restrict & %d) and i.uid= %d ", intval(ITEM_WEBPAGE), intval(ITEM_DELETED), intval($channel_id));
    } else {
        $r = q("select count(i.id)  as total from item i \n\t\t\tright join channel c on (i.author_xchan=c.channel_hash and i.uid=c.channel_id )  \n\t\t\tand i.parent=i.id and (i.item_restrict=0) and i.uid= %d ", intval($channel_id));
    }
    if (!($r && count($r))) {
        $ret['message'] = t('Unable to obtain identity information from database');
        return $ret;
    }
    if (!$iswebpage) {
        if (!service_class_allows($channel_id, 'total_items', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t("You have reached your limit of %1\$.0f top level posts."), $r[0]['total']);
            return $result;
        }
    } else {
        if (!service_class_allows($channel_id, 'total_pages', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t("You have reached your limit of %1\$.0f webpages."), $r[0]['total']);
            return $result;
        }
    }
    $ret['success'] = true;
    return $ret;
}
コード例 #10
0
ファイル: wall_attach.php プロジェクト: jzacman/friendica
function wall_attach_post(&$a)
{
    if ($a->argc > 1) {
        $nick = $a->argv[1];
        $r = q("SELECT `user`.*, `contact`.`id` FROM `user` LEFT JOIN `contact` on `user`.`uid` = `contact`.`uid`  WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1", dbesc($nick));
        if (!count($r)) {
            return;
        }
    } else {
        return;
    }
    $can_post = false;
    $visitor = 0;
    $page_owner_uid = $r[0]['uid'];
    $page_owner_cid = $r[0]['id'];
    $page_owner_nick = $r[0]['nickname'];
    $community_page = $r[0]['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $page_owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            $cid = 0;
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $page_owner_uid) {
                        $cid = $v['cid'];
                        break;
                    }
                }
            }
            if ($cid) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($cid), intval($page_owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $visitor = $cid;
                }
            }
        }
    }
    if (!$can_post) {
        notice(t('Permission denied.') . EOL);
        killme();
    }
    if (!x($_FILES, 'userfile')) {
        killme();
    }
    $src = $_FILES['userfile']['tmp_name'];
    $filename = basename($_FILES['userfile']['name']);
    $filesize = intval($_FILES['userfile']['size']);
    $maxfilesize = get_config('system', 'maxfilesize');
    /* Found html code written in text field of form,
     * when trying to upload a file with filesize
     * greater than upload_max_filesize. Cause is unknown.
     * Then Filesize gets <= 0.
     */
    if ($filesize <= 0) {
        notice(t('Sorry, maybe your upload is bigger than the PHP configuration allows') . EOL . t('Or - did you try to upload an empty file?') . EOL);
        @unlink($src);
        killme();
    }
    if ($maxfilesize && $filesize > $maxfilesize) {
        notice(sprintf(t('File exceeds size limit of %d'), $maxfilesize) . EOL);
        @unlink($src);
        return;
    }
    $r = q("select sum(octet_length(data)) as total from attach where uid = %d ", intval($page_owner_uid));
    $limit = service_class_fetch($page_owner_uid, 'attach_upload_limit');
    if ($limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        echo upgrade_message(true) . EOL;
        @unlink($src);
        killme();
    }
    $filedata = @file_get_contents($src);
    $mimetype = z_mime_content_type($filename);
    $hash = random_string();
    $created = datetime_convert();
    $r = q("INSERT INTO `attach` ( `uid`, `hash`, `filename`, `filetype`, `filesize`, `data`, `created`, `edited`, `allow_cid`, `allow_gid`,`deny_cid`, `deny_gid` )\n\t\tVALUES ( %d, '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($page_owner_uid), dbesc($hash), dbesc($filename), dbesc($mimetype), intval($filesize), dbesc($filedata), dbesc($created), dbesc($created), dbesc('<' . $page_owner_cid . '>'), dbesc(''), dbesc(''), dbesc(''));
    @unlink($src);
    if (!$r) {
        echo t('File upload failed.') . EOL;
        killme();
    }
    $r = q("SELECT `id` FROM `attach` WHERE `uid` = %d AND `created` = '%s' AND `hash` = '%s' LIMIT 1", intval($page_owner_uid), dbesc($created), dbesc($hash));
    if (!count($r)) {
        echo t('File upload failed.') . EOL;
        killme();
    }
    $lf = "\n";
    echo $lf . $lf . '[attachment]' . $r[0]['id'] . '[/attachment]' . $lf;
    killme();
    // NOTREACHED
}
コード例 #11
0
ファイル: photos.php プロジェクト: jzacman/friendica
function photos_post(&$a)
{
    logger('mod-photos: photos_post: begin', LOGGER_DEBUG);
    logger('mod_photos: REQUEST ' . print_r($_REQUEST, true), LOGGER_DATA);
    logger('mod_photos: FILES ' . print_r($_FILES, true), LOGGER_DATA);
    $phototypes = Photo::supportedTypes();
    $can_post = false;
    $visitor = 0;
    $page_owner_uid = $a->data['user']['uid'];
    $community_page = $a->data['user']['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $page_owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            $cid = 0;
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $page_owner_uid) {
                        $cid = $v['cid'];
                        break;
                    }
                }
            }
            if ($cid) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($cid), intval($page_owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $visitor = $cid;
                }
            }
        }
    }
    if (!$can_post) {
        notice(t('Permission denied.') . EOL);
        killme();
    }
    $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` \n\t\tWHERE `user`.`uid` = %d AND `self` = 1 LIMIT 1", intval($page_owner_uid));
    if (!count($r)) {
        notice(t('Contact information unavailable') . EOL);
        logger('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
        killme();
    }
    $owner_record = $r[0];
    if ($a->argc > 3 && $a->argv[2] === 'album') {
        $album = hex2bin($a->argv[3]);
        if ($album === t('Profile Photos') || $album === 'Contact Photos' || $album === t('Contact Photos')) {
            goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
            return;
            // NOTREACHED
        }
        $r = q("SELECT count(*) FROM `photo` WHERE `album` = '%s' AND `uid` = %d", dbesc($album), intval($page_owner_uid));
        if (!count($r)) {
            notice(t('Album not found.') . EOL);
            goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
            return;
            // NOTREACHED
        }
        // Check if the user has responded to a delete confirmation query
        if ($_REQUEST['canceled']) {
            goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
        }
        $newalbum = notags(trim($_POST['albumname']));
        if ($newalbum != $album) {
            q("UPDATE `photo` SET `album` = '%s' WHERE `album` = '%s' AND `uid` = %d", dbesc($newalbum), dbesc($album), intval($page_owner_uid));
            $newurl = str_replace(bin2hex($album), bin2hex($newalbum), $_SESSION['photo_return']);
            goaway($a->get_baseurl() . '/' . $newurl);
            return;
            // NOTREACHED
        }
        if ($_POST['dropalbum'] == t('Delete Album')) {
            // Check if we should do HTML-based delete confirmation
            if ($_REQUEST['confirm']) {
                $drop_url = $a->query_string;
                $extra_inputs = array(array('name' => 'albumname', 'value' => $_POST['albumname']));
                $a->page['content'] = replace_macros(get_markup_template('confirm.tpl'), array('$method' => 'post', '$message' => t('Do you really want to delete this photo album and all its photos?'), '$extra_inputs' => $extra_inputs, '$confirm' => t('Delete Album'), '$confirm_url' => $drop_url, '$confirm_name' => 'dropalbum', '$cancel' => t('Cancel')));
                $a->error = 1;
                // Set $a->error so the other module functions don't execute
                return;
            }
            $res = array();
            // get the list of photos we are about to delete
            if ($visitor) {
                $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `album` = '%s'", intval($visitor), intval($page_owner_uid), dbesc($album));
            } else {
                $r = q("SELECT distinct(`resource-id`) as `rid` FROM `photo` WHERE `uid` = %d AND `album` = '%s'", intval(local_user()), dbesc($album));
            }
            if (count($r)) {
                foreach ($r as $rr) {
                    $res[] = "'" . dbesc($rr['rid']) . "'";
                }
            } else {
                goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
                return;
                // NOTREACHED
            }
            $str_res = implode(',', $res);
            // remove the associated photos
            q("DELETE FROM `photo` WHERE `resource-id` IN ( {$str_res} ) AND `uid` = %d", intval($page_owner_uid));
            // find and delete the corresponding item with all the comments and likes/dislikes
            $r = q("SELECT `parent-uri` FROM `item` WHERE `resource-id` IN ( {$str_res} ) AND `uid` = %d", intval($page_owner_uid));
            if (count($r)) {
                foreach ($r as $rr) {
                    q("UPDATE `item` SET `deleted` = 1, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($rr['parent-uri']), intval($page_owner_uid));
                    create_tags_from_itemuri($rr['parent-uri'], $page_owner_uid);
                    delete_thread_uri($rr['parent-uri'], $page_owner_uid);
                    $drop_id = intval($rr['id']);
                    // send the notification upstream/downstream as the case may be
                    if ($rr['visible']) {
                        proc_run('php', "include/notifier.php", "drop", "{$drop_id}");
                    }
                }
            }
        }
        goaway($a->get_baseurl() . '/photos/' . $a->data['user']['nickname']);
        return;
        // NOTREACHED
    }
    // Check if the user has responded to a delete confirmation query for a single photo
    if ($a->argc > 2 && $_REQUEST['canceled']) {
        goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    }
    if ($a->argc > 2 && x($_POST, 'delete') && $_POST['delete'] == t('Delete Photo')) {
        // same as above but remove single photo
        // Check if we should do HTML-based delete confirmation
        if ($_REQUEST['confirm']) {
            $drop_url = $a->query_string;
            $a->page['content'] = replace_macros(get_markup_template('confirm.tpl'), array('$method' => 'post', '$message' => t('Do you really want to delete this photo?'), '$extra_inputs' => array(), '$confirm' => t('Delete Photo'), '$confirm_url' => $drop_url, '$confirm_name' => 'delete', '$cancel' => t('Cancel')));
            $a->error = 1;
            // Set $a->error so the other module functions don't execute
            return;
        }
        if ($visitor) {
            $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d AND `resource-id` = '%s' LIMIT 1", intval($visitor), intval($page_owner_uid), dbesc($a->argv[2]));
        } else {
            $r = q("SELECT `id`, `resource-id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' LIMIT 1", intval(local_user()), dbesc($a->argv[2]));
        }
        if (count($r)) {
            q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'", intval($page_owner_uid), dbesc($r[0]['resource-id']));
            $i = q("SELECT * FROM `item` WHERE `resource-id` = '%s' AND `uid` = %d LIMIT 1", dbesc($r[0]['resource-id']), intval($page_owner_uid));
            if (count($i)) {
                q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($i[0]['uri']), intval($page_owner_uid));
                create_tags_from_itemuri($i[0]['uri'], $page_owner_uid);
                delete_thread_uri($i[0]['uri'], $page_owner_uid);
                $url = $a->get_baseurl();
                $drop_id = intval($i[0]['id']);
                if ($i[0]['visible']) {
                    proc_run('php', "include/notifier.php", "drop", "{$drop_id}");
                }
            }
        }
        goaway($a->get_baseurl() . '/photos/' . $a->data['user']['nickname']);
        return;
        // NOTREACHED
    }
    if ($a->argc > 2 && (x($_POST, 'desc') !== false || x($_POST, 'newtag') !== false) || x($_POST, 'albname') !== false) {
        $desc = x($_POST, 'desc') ? notags(trim($_POST['desc'])) : '';
        $rawtags = x($_POST, 'newtag') ? notags(trim($_POST['newtag'])) : '';
        $item_id = x($_POST, 'item_id') ? intval($_POST['item_id']) : 0;
        $albname = x($_POST, 'albname') ? notags(trim($_POST['albname'])) : '';
        $str_group_allow = perms2str($_POST['group_allow']);
        $str_contact_allow = perms2str($_POST['contact_allow']);
        $str_group_deny = perms2str($_POST['group_deny']);
        $str_contact_deny = perms2str($_POST['contact_deny']);
        $resource_id = $a->argv[2];
        if (!strlen($albname)) {
            $albname = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
        }
        if (x($_POST, 'rotate') !== false && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
            logger('rotate');
            $r = q("select * from photo where `resource-id` = '%s' and uid = %d and scale = 0 limit 1", dbesc($resource_id), intval($page_owner_uid));
            if (count($r)) {
                $ph = new Photo($r[0]['data'], $r[0]['type']);
                if ($ph->is_valid()) {
                    $rotate_deg = intval($_POST['rotate']) == 1 ? 270 : 90;
                    $ph->rotate($rotate_deg);
                    $width = $ph->getWidth();
                    $height = $ph->getHeight();
                    $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 0", dbesc($ph->imageString()), intval($height), intval($width), dbesc($resource_id), intval($page_owner_uid));
                    if ($width > 640 || $height > 640) {
                        $ph->scaleImage(640);
                        $width = $ph->getWidth();
                        $height = $ph->getHeight();
                        $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 1", dbesc($ph->imageString()), intval($height), intval($width), dbesc($resource_id), intval($page_owner_uid));
                    }
                    if ($width > 320 || $height > 320) {
                        $ph->scaleImage(320);
                        $width = $ph->getWidth();
                        $height = $ph->getHeight();
                        $x = q("update photo set data = '%s', height = %d, width = %d where `resource-id` = '%s' and uid = %d and scale = 2", dbesc($ph->imageString()), intval($height), intval($width), dbesc($resource_id), intval($page_owner_uid));
                    }
                }
            }
        }
        $p = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ORDER BY `scale` DESC", dbesc($resource_id), intval($page_owner_uid));
        if (count($p)) {
            $ext = $phototypes[$p[0]['type']];
            $r = q("UPDATE `photo` SET `desc` = '%s', `album` = '%s', `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `resource-id` = '%s' AND `uid` = %d", dbesc($desc), dbesc($albname), dbesc($str_contact_allow), dbesc($str_group_allow), dbesc($str_contact_deny), dbesc($str_group_deny), dbesc($resource_id), intval($page_owner_uid));
        }
        /* Don't make the item visible if the only change was the album name */
        $visibility = 0;
        if ($p[0]['desc'] !== $desc || strlen($rawtags)) {
            $visibility = 1;
        }
        if (!$item_id) {
            // Create item container
            $title = '';
            $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
            $arr = array();
            $arr['uid'] = $page_owner_uid;
            $arr['uri'] = $uri;
            $arr['parent-uri'] = $uri;
            $arr['type'] = 'photo';
            $arr['wall'] = 1;
            $arr['resource-id'] = $p[0]['resource-id'];
            $arr['contact-id'] = $owner_record['id'];
            $arr['owner-name'] = $owner_record['name'];
            $arr['owner-link'] = $owner_record['url'];
            $arr['owner-avatar'] = $owner_record['thumb'];
            $arr['author-name'] = $owner_record['name'];
            $arr['author-link'] = $owner_record['url'];
            $arr['author-avatar'] = $owner_record['thumb'];
            $arr['title'] = $title;
            $arr['allow_cid'] = $p[0]['allow_cid'];
            $arr['allow_gid'] = $p[0]['allow_gid'];
            $arr['deny_cid'] = $p[0]['deny_cid'];
            $arr['deny_gid'] = $p[0]['deny_gid'];
            $arr['last-child'] = 1;
            $arr['visible'] = $visibility;
            $arr['origin'] = 1;
            $arr['body'] = '[url=' . $a->get_baseurl() . '/photos/' . $a->data['user']['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . '[img]' . $a->get_baseurl() . '/photo/' . $p[0]['resource-id'] . '-' . $p[0]['scale'] . '.' . $ext . '[/img]' . '[/url]';
            $item_id = item_store($arr);
        }
        if ($item_id) {
            $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($item_id), intval($page_owner_uid));
        }
        if (count($r)) {
            $old_tag = $r[0]['tag'];
            $old_inform = $r[0]['inform'];
        }
        if (strlen($rawtags)) {
            $str_tags = '';
            $inform = '';
            // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag
            $x = substr($rawtags, 0, 1);
            if ($x !== '@' && $x !== '#') {
                $rawtags = '#' . $rawtags;
            }
            $taginfo = array();
            $tags = get_tags($rawtags);
            if (count($tags)) {
                foreach ($tags as $tag) {
                    if (isset($profile)) {
                        unset($profile);
                    }
                    if (strpos($tag, '@') === 0) {
                        $name = substr($tag, 1);
                        if (strpos($name, '@') || strpos($name, 'http://')) {
                            $newname = $name;
                            $links = @lrdd($name);
                            if (count($links)) {
                                foreach ($links as $link) {
                                    if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
                                        $profile = $link['@attributes']['href'];
                                    }
                                    if ($link['@attributes']['rel'] === 'salmon') {
                                        $salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
                                        if (strlen($inform)) {
                                            $inform .= ',';
                                        }
                                        $inform .= $salmon;
                                    }
                                }
                            }
                            $taginfo[] = array($newname, $profile, $salmon);
                        } else {
                            $newname = $name;
                            $alias = '';
                            $tagcid = 0;
                            if (strrpos($newname, '+')) {
                                $tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
                            }
                            if ($tagcid) {
                                $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($tagcid), intval($profile_uid));
                            } else {
                                $newname = str_replace('_', ' ', $name);
                                //select someone from this user's contacts by name
                                $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1", dbesc($newname), intval($page_owner_uid));
                                if (!$r) {
                                    //select someone by attag or nick and the name passed in
                                    $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1", dbesc($name), dbesc($name), intval($page_owner_uid));
                                }
                            }
                            /*							elseif(strstr($name,'_') || strstr($name,' ')) {
                            								$newname = str_replace('_',' ',$name);
                            								$r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
                            									dbesc($newname),
                            									intval($page_owner_uid)
                            								);
                            							}
                            							else {
                            								$r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
                            									dbesc($name),
                            									dbesc($name),
                            									intval($page_owner_uid)
                            								);
                            							}*/
                            if (count($r)) {
                                $newname = $r[0]['name'];
                                $profile = $r[0]['url'];
                                $notify = 'cid:' . $r[0]['id'];
                                if (strlen($inform)) {
                                    $inform .= ',';
                                }
                                $inform .= $notify;
                            }
                        }
                        if ($profile) {
                            if (substr($notify, 0, 4) === 'cid:') {
                                $taginfo[] = array($newname, $profile, $notify, $r[0], '@[url=' . str_replace(',', '%2c', $profile) . ']' . $newname . '[/url]');
                            } else {
                                $taginfo[] = array($newname, $profile, $notify, null, $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]');
                            }
                            if (strlen($str_tags)) {
                                $str_tags .= ',';
                            }
                            $profile = str_replace(',', '%2c', $profile);
                            $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]';
                        }
                    } elseif (strpos($tag, '#') === 0) {
                        $tagname = substr($tag, 1);
                        $str_tags .= '#[url=' . $a->get_baseurl() . "/search?tag=" . $tagname . ']' . $tagname . '[/url]';
                    }
                }
            }
            $newtag = $old_tag;
            if (strlen($newtag) && strlen($str_tags)) {
                $newtag .= ',';
            }
            $newtag .= $str_tags;
            $newinform = $old_inform;
            if (strlen($newinform) && strlen($inform)) {
                $newinform .= ',';
            }
            $newinform .= $inform;
            $r = q("UPDATE `item` SET `tag` = '%s', `inform` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d", dbesc($newtag), dbesc($newinform), dbesc(datetime_convert()), dbesc(datetime_convert()), intval($item_id), intval($page_owner_uid));
            create_tags_from_item($item_id);
            update_thread($item_id);
            $best = 0;
            foreach ($p as $scales) {
                if (intval($scales['scale']) == 2) {
                    $best = 2;
                    break;
                }
                if (intval($scales['scale']) == 4) {
                    $best = 4;
                    break;
                }
            }
            if (count($taginfo)) {
                foreach ($taginfo as $tagged) {
                    $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
                    $arr = array();
                    $arr['uid'] = $page_owner_uid;
                    $arr['uri'] = $uri;
                    $arr['parent-uri'] = $uri;
                    $arr['type'] = 'activity';
                    $arr['wall'] = 1;
                    $arr['contact-id'] = $owner_record['id'];
                    $arr['owner-name'] = $owner_record['name'];
                    $arr['owner-link'] = $owner_record['url'];
                    $arr['owner-avatar'] = $owner_record['thumb'];
                    $arr['author-name'] = $owner_record['name'];
                    $arr['author-link'] = $owner_record['url'];
                    $arr['author-avatar'] = $owner_record['thumb'];
                    $arr['title'] = '';
                    $arr['allow_cid'] = $p[0]['allow_cid'];
                    $arr['allow_gid'] = $p[0]['allow_gid'];
                    $arr['deny_cid'] = $p[0]['deny_cid'];
                    $arr['deny_gid'] = $p[0]['deny_gid'];
                    $arr['last-child'] = 1;
                    $arr['visible'] = 1;
                    $arr['verb'] = ACTIVITY_TAG;
                    $arr['object-type'] = ACTIVITY_OBJ_PERSON;
                    $arr['target-type'] = ACTIVITY_OBJ_PHOTO;
                    $arr['tag'] = $tagged[4];
                    $arr['inform'] = $tagged[2];
                    $arr['origin'] = 1;
                    $arr['body'] = sprintf(t('%1$s was tagged in %2$s by %3$s'), '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]', '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . t('a photo') . '[/url]', '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]');
                    $arr['body'] .= "\n\n" . '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . ']' . '[img]' . $a->get_baseurl() . "/photo/" . $p[0]['resource-id'] . '-' . $best . '.' . $ext . '[/img][/url]' . "\n";
                    $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $tagged[0] . '</title><id>' . $tagged[1] . '/' . $tagged[0] . '</id>';
                    $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $tagged[1] . '" />' . "\n");
                    if ($tagged[3]) {
                        $arr['object'] .= xmlify('<link rel="photo" type="' . $p[0]['type'] . '" href="' . $tagged[3]['photo'] . '" />' . "\n");
                    }
                    $arr['object'] .= '</link></object>' . "\n";
                    $arr['target'] = '<target><type>' . ACTIVITY_OBJ_PHOTO . '</type><title>' . $p[0]['desc'] . '</title><id>' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '</id>';
                    $arr['target'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $p[0]['resource-id'] . '" />' . "\n" . '<link rel="preview" type="' . $p[0]['type'] . '" href="' . $a->get_baseurl() . "/photo/" . $p[0]['resource-id'] . '-' . $best . '.' . $ext . '" />') . '</link></target>';
                    $item_id = item_store($arr);
                    if ($item_id) {
                        //q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d",
                        //	dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
                        //	intval($page_owner_uid),
                        //	intval($item_id)
                        //);
                        proc_run('php', "include/notifier.php", "tag", "{$item_id}");
                    }
                }
            }
        }
        goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
        return;
        // NOTREACHED
    }
    /**
     * default post action - upload a photo
     */
    call_hooks('photo_post_init', $_POST);
    /**
     * Determine the album to use
     */
    $album = notags(trim($_REQUEST['album']));
    $newalbum = notags(trim($_REQUEST['newalbum']));
    logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum, LOGGER_DEBUG);
    if (!strlen($album)) {
        if (strlen($newalbum)) {
            $album = $newalbum;
        } else {
            $album = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y');
        }
    }
    /**
     *
     * We create a wall item for every photo, but we don't want to
     * overwhelm the data stream with a hundred newly uploaded photos.
     * So we will make the first photo uploaded to this album in the last several hours
     * visible by default, the rest will become visible over time when and if
     * they acquire comments, likes, dislikes, and/or tags 
     *
     */
    $r = q("SELECT * FROM `photo` WHERE `album` = '%s' AND `uid` = %d AND `created` > UTC_TIMESTAMP() - INTERVAL 3 HOUR ", dbesc($album), intval($page_owner_uid));
    if (!count($r) || $album == t('Profile Photos')) {
        $visible = 1;
    } else {
        $visible = 0;
    }
    if (intval($_REQUEST['not_visible']) || $_REQUEST['not_visible'] === 'true') {
        $visible = 0;
    }
    $str_group_allow = perms2str(is_array($_REQUEST['group_allow']) ? $_REQUEST['group_allow'] : explode(',', $_REQUEST['group_allow']));
    $str_contact_allow = perms2str(is_array($_REQUEST['contact_allow']) ? $_REQUEST['contact_allow'] : explode(',', $_REQUEST['contact_allow']));
    $str_group_deny = perms2str(is_array($_REQUEST['group_deny']) ? $_REQUEST['group_deny'] : explode(',', $_REQUEST['group_deny']));
    $str_contact_deny = perms2str(is_array($_REQUEST['contact_deny']) ? $_REQUEST['contact_deny'] : explode(',', $_REQUEST['contact_deny']));
    $ret = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
    call_hooks('photo_post_file', $ret);
    if (x($ret, 'src') && x($ret, 'filesize')) {
        $src = $ret['src'];
        $filename = $ret['filename'];
        $filesize = $ret['filesize'];
        $type = $ret['type'];
    } else {
        $src = $_FILES['userfile']['tmp_name'];
        $filename = basename($_FILES['userfile']['name']);
        $filesize = intval($_FILES['userfile']['size']);
        $type = $_FILES['userfile']['type'];
    }
    if ($type == "") {
        $type = guess_image_type($filename);
    }
    logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
    $maximagesize = get_config('system', 'maximagesize');
    if ($maximagesize && $filesize > $maximagesize) {
        notice(t('Image exceeds size limit of ') . $maximagesize . EOL);
        @unlink($src);
        $foo = 0;
        call_hooks('photo_post_end', $foo);
        return;
    }
    if (!$filesize) {
        notice(t('Image file is empty.') . EOL);
        @unlink($src);
        $foo = 0;
        call_hooks('photo_post_end', $foo);
        return;
    }
    logger('mod/photos.php: photos_post(): loading the contents of ' . $src, LOGGER_DEBUG);
    $imagedata = @file_get_contents($src);
    $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ", intval($a->data['user']['uid']));
    $limit = service_class_fetch($a->data['user']['uid'], 'photo_upload_limit');
    if ($limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        notice(upgrade_message() . EOL);
        @unlink($src);
        $foo = 0;
        call_hooks('photo_post_end', $foo);
        killme();
    }
    $ph = new Photo($imagedata, $type);
    if (!$ph->is_valid()) {
        logger('mod/photos.php: photos_post(): unable to process image', LOGGER_DEBUG);
        notice(t('Unable to process image.') . EOL);
        @unlink($src);
        $foo = 0;
        call_hooks('photo_post_end', $foo);
        killme();
    }
    $ph->orient($src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $smallest = 0;
    $photo_hash = photo_new_resource();
    $r = $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 0, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
    if (!$r) {
        logger('mod/photos.php: photos_post(): image store failed', LOGGER_DEBUG);
        notice(t('Image upload failed.') . EOL);
        killme();
    }
    if ($width > 640 || $height > 640) {
        $ph->scaleImage(640);
        $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 1, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
        $smallest = 1;
    }
    if ($width > 320 || $height > 320) {
        $ph->scaleImage(320);
        $ph->store($page_owner_uid, $visitor, $photo_hash, $filename, $album, 2, 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
        $smallest = 2;
    }
    $basename = basename($filename);
    $uri = item_new_uri($a->get_hostname(), $page_owner_uid);
    // Create item container
    $arr = array();
    $arr['uid'] = $page_owner_uid;
    $arr['uri'] = $uri;
    $arr['parent-uri'] = $uri;
    $arr['type'] = 'photo';
    $arr['wall'] = 1;
    $arr['resource-id'] = $photo_hash;
    $arr['contact-id'] = $owner_record['id'];
    $arr['owner-name'] = $owner_record['name'];
    $arr['owner-link'] = $owner_record['url'];
    $arr['owner-avatar'] = $owner_record['thumb'];
    $arr['author-name'] = $owner_record['name'];
    $arr['author-link'] = $owner_record['url'];
    $arr['author-avatar'] = $owner_record['thumb'];
    $arr['title'] = '';
    $arr['allow_cid'] = $str_contact_allow;
    $arr['allow_gid'] = $str_group_allow;
    $arr['deny_cid'] = $str_contact_deny;
    $arr['deny_gid'] = $str_group_deny;
    $arr['last-child'] = 1;
    $arr['visible'] = $visible;
    $arr['origin'] = 1;
    $arr['body'] = '[url=' . $a->get_baseurl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo_hash . ']' . '[img]' . $a->get_baseurl() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/img]' . '[/url]';
    $item_id = item_store($arr);
    //if($item_id) {
    //	q("UPDATE `item` SET `plink` = '%s' WHERE `uid` = %d AND `id` = %d",
    //		dbesc($a->get_baseurl() . '/display/' . $owner_record['nickname'] . '/' . $item_id),
    //		intval($page_owner_uid),
    //		intval($item_id)
    //	);
    //}
    if ($visible) {
        proc_run('php', "include/notifier.php", 'wall-new', $item_id);
    }
    call_hooks('photo_post_end', intval($item_id));
    // addon uploaders should call "killme()" [e.g. exit] within the photo_post_end hook
    // if they do not wish to be redirected
    goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    // NOTREACHED
}
コード例 #12
0
ファイル: attach.php プロジェクト: Mauru/red
/**
 * @brief 
 *
 * @param $channel channel array of owner
 * @param $observer_hash hash of current observer
 * @param $options (optional)
 * @param $arr (optional)
 */
function attach_store($channel, $observer_hash, $options = '', $arr = null)
{
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $sql_options = '';
    if (!perm_is_allowed($channel_id, get_observer_hash(), 'write_storage')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    // The 'update' option sets db values without uploading a new attachment
    // 'replace' replaces the existing uploaded data
    // 'revision' creates a new revision with new upload data
    // Default is to upload a new file
    // revise or update must provide $arr['hash'] of the thing to revise/update
    if ($options !== 'update') {
        if (!x($_FILES, 'userfile')) {
            $ret['message'] = t('No source file.');
            return $ret;
        }
        $src = $_FILES['userfile']['tmp_name'];
        $filename = basename($_FILES['userfile']['name']);
        $filesize = intval($_FILES['userfile']['size']);
    }
    $existing_size = 0;
    if ($options === 'replace') {
        $x = q("select id, hash, filesize from attach where id = %d and uid = %d limit 1", intval($replace), intval($channel_id));
        if (!$x) {
            $ret['message'] = t('Cannot locate file to replace');
            return $ret;
        }
        $existing_id = $x[0]['id'];
        $existing_size = intval($x[0]['filesize']);
        $hash = $x[0]['hash'];
    }
    if ($options === 'revise' || $options === 'update') {
        $sql_options = " order by revision desc ";
        if ($options === 'update' && $arr && array_key_exists('revision', $arr)) {
            $sql_options = " and revision = " . intval($arr['revision']) . " ";
        }
        $x = q("select id, aid, uid, filename, filetype, filesize, hash, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where hash = '%s' and uid = %d {$sql_options} limit 1", dbesc($arr['hash']), intval($channel_id));
        if (!$x) {
            $ret['message'] = t('Cannot locate file to revise/update');
            return $ret;
        }
        $hash = $x[0]['hash'];
    }
    // Check storage limits
    if ($options !== 'update') {
        $maxfilesize = get_config('system', 'maxfilesize');
        if ($maxfilesize && $filesize > $maxfilesize) {
            $ret['message'] = sprintf(t('File exceeds size limit of %d'), $maxfilesize);
            @unlink($src);
            return $ret;
        }
        $limit = service_class_fetch($channel_id, 'attach_upload_limit');
        if ($limit !== false) {
            $r = q("select sum(filesize) as total from attach where aid = %d ", intval($channel['channel_account_id']));
            if ($r && $r[0]['total'] + $filesize > $limit - $existing_size) {
                $ret['message'] = upgrade_message(true) . sprintf(t("You have reached your limit of %1\$.0f Mbytes attachment storage."), $limit / 1024000);
                @unlink($src);
                return $ret;
            }
        }
        $mimetype = z_mime_content_type($filename);
    }
    if (!isset($hash)) {
        $hash = random_string();
    }
    $created = datetime_convert();
    if ($options === 'replace') {
        $r = q("update attach set filename = '%s', filetype = '%s', filesize = %d, data = '%s', edited = '%s' where id = %d and uid = %d limit 1", dbesc($filename), dbesc($mimetype), intval($filesize), dbesc(@file_get_contents($src)), dbesc($created), intval($existing_id), intval($channel_id));
    } elseif ($options === 'revise') {
        $r = q("insert into attach ( aid, uid, hash, creator, filename, filetype, filesize, revision, data, created, edited, allow_cid, allow_gid, deny_cid, deny_gid )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($x[0]['aid']), intval($channel_id), dbesc($x[0]['hash']), dbesc(get_observer_hash()), dbesc($filename), dbesc($mimetype), intval($filesize), intval($x[0]['revision'] + 1), dbesc(@file_get_contents($src)), dbesc($created), dbesc($created), dbesc($x[0]['allow_cid']), dbesc($x[0]['allow_gid']), dbesc($x[0]['deny_cid']), dbesc($x[0]['deny_gid']));
    } elseif ($options === 'update') {
        $r = q("update attach set filename = '%s', filetype = '%s', edited = '%s', \n\t\t\tallow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid  = '%s' where id = %d and uid = %d limit 1", dbesc(array_key_exists('filename', $arr) ? $arr['filename'] : $x[0]['filename']), dbesc(array_key_exists('filetype', $arr) ? $arr['filetype'] : $x[0]['filetype']), dbesc($created), dbesc(array_key_exists('allow_cid', $arr) ? $arr['allow_cid'] : $x[0]['allow_cid']), dbesc(array_key_exists('allow_gid', $arr) ? $arr['allow_gid'] : $x[0]['allow_gid']), dbesc(array_key_exists('deny_cid', $arr) ? $arr['deny_cid'] : $x[0]['deny_cid']), dbesc(array_key_exists('deny_gid', $arr) ? $arr['deny_gid'] : $x[0]['deny_gid']), intval($x[0]['id']), intval($x[0]['uid']));
    } else {
        $r = q("INSERT INTO attach ( aid, uid, hash, creator, filename, filetype, filesize, revision, data, created, edited, allow_cid, allow_gid,deny_cid, deny_gid )\n\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($channel['channel_account_id']), intval($channel_id), dbesc($hash), dbesc(get_observer_hash()), dbesc($filename), dbesc($mimetype), intval($filesize), intval(0), dbesc(@file_get_contents($src)), dbesc($created), dbesc($created), dbesc($arr && array_key_exists('allow_cid', $arr) ? $arr['allow_cid'] : '<' . $channel['channel_hash'] . '>'), dbesc($arr && array_key_exists('allow_gid', $arr) ? $arr['allow_gid'] : ''), dbesc($arr && array_key_exists('deny_cid', $arr) ? $arr['deny_cid'] : ''), dbesc($arr && array_key_exists('deny_gid', $arr) ? $arr['deny_gid'] : ''));
    }
    if ($options !== 'update') {
        @unlink($src);
    }
    if (!$r) {
        $ret['message'] = t('File upload failed. Possible system limit or action terminated.');
        return $ret;
    }
    // Caution: This re-uses $sql_options set further above
    $r = q("select id, aid, uid, hash, creator, filename, filetype, filesize, revision, folder, flags, created, edited, allow_cid, allow_gid, deny_cid, deny_gid from attach where uid = %d and hash = '%s' {$sql_options} limit 1", intval($channel_id), dbesc($hash));
    if (!$r) {
        $ret['message'] = t('Stored file could not be verified. Upload failed.');
        return $ret;
    }
    $ret['success'] = true;
    $ret['data'] = $r[0];
    return $ret;
}
コード例 #13
0
ファイル: wall_upload.php プロジェクト: ridcully/friendica
function wall_upload_post(&$a)
{
    logger("wall upload: starting new upload", LOGGER_DEBUG);
    if ($a->argc > 1) {
        if (!x($_FILES, 'media')) {
            $nick = $a->argv[1];
            $r = q("SELECT `user`.*, `contact`.`id` FROM `user` LEFT JOIN `contact` on `user`.`uid` = `contact`.`uid`  WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1", dbesc($nick));
            if (!count($r)) {
                return;
            }
        } else {
            $user_info = api_get_user($a);
            $r = q("SELECT `user`.*, `contact`.`id` FROM `user` LEFT JOIN `contact` on `user`.`uid` = `contact`.`uid`  WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1", dbesc($user_info['screen_name']));
        }
    } else {
        return;
    }
    $can_post = false;
    $visitor = 0;
    $page_owner_uid = $r[0]['uid'];
    $default_cid = $r[0]['id'];
    $page_owner_nick = $r[0]['nickname'];
    $community_page = $r[0]['page-flags'] == PAGE_COMMUNITY ? true : false;
    if (local_user() && local_user() == $page_owner_uid) {
        $can_post = true;
    } else {
        if ($community_page && remote_user()) {
            $cid = 0;
            if (is_array($_SESSION['remote'])) {
                foreach ($_SESSION['remote'] as $v) {
                    if ($v['uid'] == $page_owner_uid) {
                        $cid = $v['cid'];
                        break;
                    }
                }
            }
            if ($cid) {
                $r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1", intval($cid), intval($page_owner_uid));
                if (count($r)) {
                    $can_post = true;
                    $visitor = $cid;
                }
            }
        }
    }
    if (!$can_post) {
        notice(t('Permission denied.') . EOL);
        killme();
    }
    if (!x($_FILES, 'userfile') && !x($_FILES, 'media')) {
        killme();
    }
    if (x($_FILES, 'userfile')) {
        $src = $_FILES['userfile']['tmp_name'];
        $filename = basename($_FILES['userfile']['name']);
        $filesize = intval($_FILES['userfile']['size']);
        $filetype = $_FILES['userfile']['type'];
    } elseif (x($_FILES, 'media')) {
        $src = $_FILES['media']['tmp_name'];
        $filename = basename($_FILES['media']['name']);
        $filesize = intval($_FILES['media']['size']);
        $filetype = $_FILES['media']['type'];
    }
    if ($filetype == "") {
        $filetype = guess_image_type($filename);
    }
    $maximagesize = get_config('system', 'maximagesize');
    if ($maximagesize && $filesize > $maximagesize) {
        echo sprintf(t('Image exceeds size limit of %d'), $maximagesize) . EOL;
        @unlink($src);
        killme();
    }
    $r = q("select sum(octet_length(data)) as total from photo where uid = %d and scale = 0 and album != 'Contact Photos' ", intval($page_owner_uid));
    $limit = service_class_fetch($page_owner_uid, 'photo_upload_limit');
    if ($limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        echo upgrade_message(true) . EOL;
        @unlink($src);
        killme();
    }
    $imagedata = @file_get_contents($src);
    $ph = new Photo($imagedata, $filetype);
    if (!$ph->is_valid()) {
        echo t('Unable to process image.') . EOL;
        @unlink($src);
        killme();
    }
    $ph->orient($src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $hash = photo_new_resource();
    $smallest = 0;
    $defperm = '<' . $default_cid . '>';
    $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 0, 0, $defperm);
    if (!$r) {
        echo t('Image upload failed.') . EOL;
        killme();
    }
    if ($width > 640 || $height > 640) {
        $ph->scaleImage(640);
        $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 1, 0, $defperm);
        if ($r) {
            $smallest = 1;
        }
    }
    if ($width > 320 || $height > 320) {
        $ph->scaleImage(320);
        $r = $ph->store($page_owner_uid, $visitor, $hash, $filename, t('Wall Photos'), 2, 0, $defperm);
        if ($r) {
            $smallest = 2;
        }
    }
    $basename = basename($filename);
    /* mod Waitman Gobble NO WARRANTY */
    //if we get the signal then return the image url info in BBCODE, otherwise this outputs the info and bails (for the ajax image uploader on wall post)
    if ($_REQUEST['hush'] != 'yeah') {
        if (local_user() && (!feature_enabled(local_user(), 'richtext') || x($_REQUEST['nomce']))) {
            echo "\n\n" . '[url=' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '][img]' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "[/img][/url]\n\n";
        } else {
            echo '<br /><br /><a href="' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '" ><img src="' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "\" alt=\"{$basename}\" /></a><br /><br />";
        }
    } else {
        $m = '[url=' . $a->get_baseurl() . '/photos/' . $page_owner_nick . '/image/' . $hash . '][img]' . $a->get_baseurl() . "/photo/{$hash}-{$smallest}." . $ph->getExt() . "[/img][/url]";
        return $m;
    }
    /* mod Waitman Gobble NO WARRANTY */
    killme();
    // NOTREACHED
}
コード例 #14
0
ファイル: photos.php プロジェクト: einervonvielen/hubzilla
/**
 * @brief
 *
 * @param array $channel
 * @param array $observer
 * @param array $args
 * @return array
 */
function photo_upload($channel, $observer, $args)
{
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $account_id = $channel['channel_account_id'];
    if (!perm_is_allowed($channel_id, $observer['xchan_hash'], 'write_storage')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    //	call_hooks('photo_upload_begin', $args);
    /*
     * Determine the album to use
     */
    $album = $args['album'];
    if (intval($args['visible']) || $args['visible'] === 'true') {
        $visible = 1;
    } else {
        $visible = 0;
    }
    $deliver = true;
    if (array_key_exists('deliver', $args)) {
        $deliver = intval($args['deliver']);
    }
    // Set to default channel permissions. If the parent directory (album) has permissions set,
    // use those instead. If we have specific permissions supplied, they take precedence over
    // all other settings. 'allow_cid' being passed from an external source takes priority over channel settings.
    // ...messy... needs re-factoring once the photos/files integration stabilises
    $acl = new Zotlabs\Access\AccessList($channel);
    if (array_key_exists('directory', $args) && $args['directory']) {
        $acl->set($args['directory']);
    }
    if (array_key_exists('allow_cid', $args)) {
        $acl->set($args);
    }
    if (array_key_exists('group_allow', $args) || array_key_exists('contact_allow', $args) || array_key_exists('group_deny', $args) || array_key_exists('contact_deny', $args)) {
        $acl->set_from_array($args);
    }
    $ac = $acl->get();
    $os_storage = 0;
    if ($args['os_path'] && $args['getimagesize']) {
        $imagedata = @file_get_contents($args['os_path']);
        $filename = $args['filename'];
        $filesize = strlen($imagedata);
        // this is going to be deleted if it exists
        $src = '/tmp/deletemenow';
        $type = $args['getimagesize']['mime'];
        $os_storage = 1;
    } elseif ($args['data'] || $args['content']) {
        // allow an import from a binary string representing the image.
        // This bypasses the upload step and max size limit checking
        $imagedata = $args['content'] ? $args['content'] : $args['data'];
        $filename = $args['filename'];
        $filesize = strlen($imagedata);
        // this is going to be deleted if it exists
        $src = '/tmp/deletemenow';
        $type = $args['mimetype'] ? $args['mimetype'] : $args['type'];
    } else {
        $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
        //		call_hooks('photo_upload_file',$f);
        if (x($f, 'src') && x($f, 'filesize')) {
            $src = $f['src'];
            $filename = $f['filename'];
            $filesize = $f['filesize'];
            $type = $f['type'];
        } else {
            $src = $_FILES['userfile']['tmp_name'];
            $filename = basename($_FILES['userfile']['name']);
            $filesize = intval($_FILES['userfile']['size']);
            $type = $_FILES['userfile']['type'];
        }
        if (!$type) {
            $type = guess_image_type($filename);
        }
        logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
        $maximagesize = get_config('system', 'maximagesize');
        if ($maximagesize && $filesize > $maximagesize) {
            $ret['message'] = sprintf(t('Image exceeds website size limit of %lu bytes'), $maximagesize);
            @unlink($src);
            call_hooks('photo_upload_end', $ret);
            return $ret;
        }
        if (!$filesize) {
            $ret['message'] = t('Image file is empty.');
            @unlink($src);
            call_hooks('photo_post_end', $ret);
            return $ret;
        }
        logger('photo_upload: loading the contents of ' . $src, LOGGER_DEBUG);
        $imagedata = @file_get_contents($src);
    }
    $r = q("select sum(filesize) as total from photo where aid = %d and imgscale = 0 ", intval($account_id));
    $limit = engr_units_to_bytes(service_class_fetch($channel_id, 'photo_upload_limit'));
    if ($r && $limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        $ret['message'] = upgrade_message();
        @unlink($src);
        call_hooks('photo_post_end', $ret);
        return $ret;
    }
    $ph = photo_factory($imagedata, $type);
    if (!$ph->is_valid()) {
        $ret['message'] = t('Unable to process image');
        logger('photo_upload: unable to process image');
        @unlink($src);
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    $exif = $ph->orient($args['os_path'] ? $args['os_path'] : $src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $smallest = 0;
    $photo_hash = $args['resource_id'] ? $args['resource_id'] : photo_new_resource();
    $visitor = '';
    if ($channel['channel_hash'] !== $observer['xchan_hash']) {
        $visitor = $observer['xchan_hash'];
    }
    $errors = false;
    $p = array('aid' => $account_id, 'uid' => $channel_id, 'xchan' => $visitor, 'resource_id' => $photo_hash, 'filename' => $filename, 'album' => $album, 'imgscale' => 0, 'photo_usage' => PHOTO_NORMAL, 'allow_cid' => $ac['allow_cid'], 'allow_gid' => $ac['allow_gid'], 'deny_cid' => $ac['deny_cid'], 'deny_gid' => $ac['deny_gid'], 'os_storage' => $os_storage, 'os_path' => $args['os_path']);
    if ($args['created']) {
        $p['created'] = $args['created'];
    }
    if ($args['edited']) {
        $p['edited'] = $args['edited'];
    }
    if ($args['title']) {
        $p['title'] = $args['title'];
    }
    if ($args['description']) {
        $p['description'] = $args['description'];
    }
    $link = array();
    $r0 = $ph->save($p);
    $link[0] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => z_root() . '/photo/' . $photo_hash . '-0.' . $ph->getExt(), 'width' => $ph->getWidth(), 'height' => $ph->getHeight());
    if (!$r0) {
        $errors = true;
    }
    unset($p['os_storage']);
    unset($p['os_path']);
    if (($width > 1024 || $height > 1024) && !$errors) {
        $ph->scaleImage(1024);
    }
    $p['imgscale'] = 1;
    $r1 = $ph->save($p);
    $link[1] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => z_root() . '/photo/' . $photo_hash . '-1.' . $ph->getExt(), 'width' => $ph->getWidth(), 'height' => $ph->getHeight());
    if (!$r1) {
        $errors = true;
    }
    if (($width > 640 || $height > 640) && !$errors) {
        $ph->scaleImage(640);
    }
    $p['imgscale'] = 2;
    $r2 = $ph->save($p);
    $link[2] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => z_root() . '/photo/' . $photo_hash . '-2.' . $ph->getExt(), 'width' => $ph->getWidth(), 'height' => $ph->getHeight());
    if (!$r2) {
        $errors = true;
    }
    if (($width > 320 || $height > 320) && !$errors) {
        $ph->scaleImage(320);
    }
    $p['imgscale'] = 3;
    $r3 = $ph->save($p);
    $link[3] = array('rel' => 'alternate', 'type' => 'text/html', 'href' => z_root() . '/photo/' . $photo_hash . '-3.' . $ph->getExt(), 'width' => $ph->getWidth(), 'height' => $ph->getHeight());
    if (!$r3) {
        $errors = true;
    }
    if ($errors) {
        q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), intval($channel_id));
        $ret['message'] = t('Photo storage failed.');
        logger('photo_upload: photo store failed.');
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    $item_hidden = $visible ? 0 : 1;
    $lat = $lon = null;
    if ($exif && $exif['GPS']) {
        if (feature_enabled($channel_id, 'photo_location')) {
            $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
            $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
        }
    }
    $title = $args['description'] ? $args['description'] : $args['filename'];
    $large_photos = feature_enabled($channel['channel_id'], 'large_photos');
    linkify_tags($a, $args['body'], $channel_id);
    if ($large_photos) {
        $scale = 1;
        $width = $link[1]['width'];
        $height = $link[1]['height'];
        $tag = $r1 ? '[zmg=' . $width . 'x' . $height . ']' : '[zmg]';
    } else {
        $scale = 2;
        $width = $link[2]['width'];
        $height = $link[2]['height'];
        $tag = $r2 ? '[zmg=' . $width . 'x' . $height . ']' : '[zmg]';
    }
    $author_link = '[zrl=' . z_root() . '/channel/' . $channel['channel_address'] . ']' . $channel['channel_name'] . '[/zrl]';
    $photo_link = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . t('a new photo') . '[/zrl]';
    $album_link = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/album/' . bin2hex($album) . ']' . (strlen($album) ? $album : '/') . '[/zrl]';
    $activity_format = sprintf(t('%1$s posted %2$s to %3$s', 'photo_upload'), $author_link, $photo_link, $album_link);
    $summary = ($args['body'] ? $args['body'] : '') . '[footer]' . $activity_format . '[/footer]';
    $obj_body = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$scale}." . $ph->getExt() . '[/zmg]' . '[/zrl]';
    // Create item object
    $object = array('type' => ACTIVITY_OBJ_PHOTO, 'title' => $title, 'created' => $p['created'], 'edited' => $p['edited'], 'id' => z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash, 'link' => $link, 'body' => $obj_body);
    $target = array('type' => ACTIVITY_OBJ_ALBUM, 'title' => $album ? $album : '/', 'id' => z_root() . '/photos/' . $channel['channel_address'] . '/album/' . bin2hex($album));
    // Create item container
    if ($args['item']) {
        foreach ($args['item'] as $i) {
            $item = get_item_elements($i);
            $force = false;
            if ($item['mid'] === $item['parent_mid']) {
                $item['body'] = $summary;
                $item['obj_type'] = ACTIVITY_OBJ_PHOTO;
                $item['obj'] = json_encode($object);
                $item['tgt_type'] = ACTIVITY_OBJ_ALBUM;
                $item['target'] = json_encode($target);
                if ($item['author_xchan'] === $channel['channel_hash']) {
                    $item['sig'] = base64url_encode(rsa_sign($item['body'], $channel['channel_prvkey']));
                    $item['item_verified'] = 1;
                } else {
                    $item['sig'] = '';
                }
                $force = true;
            }
            $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'] || $force) {
                    $item['id'] = $r[0]['id'];
                    $item['uid'] = $channel['channel_id'];
                    item_store_update($item, false, $deliver);
                    continue;
                }
            } else {
                $item['aid'] = $channel['channel_account_id'];
                $item['uid'] = $channel['channel_id'];
                $item_result = item_store($item, false, $deliver);
            }
        }
    } else {
        $mid = item_message_id();
        $arr = array();
        if ($lat && $lon) {
            $arr['coord'] = $lat . ' ' . $lon;
        }
        $arr['aid'] = $account_id;
        $arr['uid'] = $channel_id;
        $arr['mid'] = $mid;
        $arr['parent_mid'] = $mid;
        $arr['item_hidden'] = $item_hidden;
        $arr['resource_type'] = 'photo';
        $arr['resource_id'] = $photo_hash;
        $arr['owner_xchan'] = $channel['channel_hash'];
        $arr['author_xchan'] = $observer['xchan_hash'];
        $arr['title'] = $title;
        $arr['allow_cid'] = $ac['allow_cid'];
        $arr['allow_gid'] = $ac['allow_gid'];
        $arr['deny_cid'] = $ac['deny_cid'];
        $arr['deny_gid'] = $ac['deny_gid'];
        $arr['verb'] = ACTIVITY_POST;
        $arr['obj_type'] = ACTIVITY_OBJ_PHOTO;
        $arr['obj'] = json_encode($object);
        $arr['tgt_type'] = ACTIVITY_OBJ_ALBUM;
        $arr['target'] = json_encode($target);
        $arr['item_wall'] = 1;
        $arr['item_origin'] = 1;
        $arr['item_thread_top'] = 1;
        $arr['item_private'] = intval($acl->is_private());
        $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid'];
        $arr['body'] = $summary;
        // this one is tricky because the item and the photo have the same permissions, those of the photo.
        // Use the channel read_stream permissions to get the correct public_policy for the item and recalculate the
        // private flag accordingly. This may cause subtle bugs due to custom permissions roles. We want to use
        // public policy when federating items to other sites, but should probably ignore them when accessing the item
        // in the photos pages - using the photos permissions instead. We need the public policy to keep the photo
        // linked item from leaking into the feed when somebody has a channel with read_stream restrictions.
        $arr['public_policy'] = map_scope($channel['channel_r_stream'], true);
        if ($arr['public_policy']) {
            $arr['item_private'] = 1;
        }
        $result = item_store($arr, false, $deliver);
        $item_id = $result['item_id'];
        if ($visible && $deliver) {
            Zotlabs\Daemon\Master::Summon(array('Notifier', 'wall-new', $item_id));
        }
    }
    $ret['success'] = true;
    $ret['item'] = $arr;
    $ret['body'] = $obj_body;
    $ret['resource_id'] = $photo_hash;
    $ret['photoitem_id'] = $item_id;
    call_hooks('photo_upload_end', $ret);
    return $ret;
}
コード例 #15
0
ファイル: photos.php プロジェクト: HaakonME/redmatrix
/**
 * @brief
 *
 * @param array $channel
 * @param array $observer
 * @param array $args
 * @return array
 */
function photo_upload($channel, $observer, $args)
{
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $account_id = $channel['channel_account_id'];
    if (!perm_is_allowed($channel_id, $observer['xchan_hash'], 'post_photos')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    call_hooks('photo_upload_begin', $args);
    /*
     * Determine the album to use
     */
    $album = $args['album'];
    $newalbum = $args['newalbum'];
    logger('photo_upload: album= ' . $album . ' newalbum= ' . $newalbum, LOGGER_DEBUG);
    if (!$album) {
        if ($newalbum) {
            $album = $newalbum;
        } else {
            $album = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y-m');
        }
    }
    if (intval($args['visible']) || $args['visible'] === 'true') {
        $visible = 1;
    } else {
        $visible = 0;
    }
    $str_group_allow = perms2str(is_array($args['group_allow']) ? $args['group_allow'] : explode(',', $args['group_allow']));
    $str_contact_allow = perms2str(is_array($args['contact_allow']) ? $args['contact_allow'] : explode(',', $args['contact_allow']));
    $str_group_deny = perms2str(is_array($args['group_deny']) ? $args['group_deny'] : explode(',', $args['group_deny']));
    $str_contact_deny = perms2str(is_array($args['contact_deny']) ? $args['contact_deny'] : explode(',', $args['contact_deny']));
    if ($args['data']) {
        // allow an import from a binary string representing the image.
        // This bypasses the upload step and max size limit checking
        $imagedata = $args['data'];
        $filename = $args['filename'];
        $filesize = strlen($imagedata);
        // this is going to be deleted if it exists
        $src = '/tmp/deletemenow';
        $type = $args['type'];
    } else {
        $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
        call_hooks('photo_upload_file', $f);
        if (x($f, 'src') && x($f, 'filesize')) {
            $src = $f['src'];
            $filename = $f['filename'];
            $filesize = $f['filesize'];
            $type = $f['type'];
        } else {
            $src = $_FILES['userfile']['tmp_name'];
            $filename = basename($_FILES['userfile']['name']);
            $filesize = intval($_FILES['userfile']['size']);
            $type = $_FILES['userfile']['type'];
        }
        if (!$type) {
            $type = guess_image_type($filename);
        }
        logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
        $maximagesize = get_config('system', 'maximagesize');
        if ($maximagesize && $filesize > $maximagesize) {
            $ret['message'] = sprintf(t('Image exceeds website size limit of %lu bytes'), $maximagesize);
            @unlink($src);
            call_hooks('photo_upload_end', $ret);
            return $ret;
        }
        if (!$filesize) {
            $ret['message'] = t('Image file is empty.');
            @unlink($src);
            call_hooks('photo_post_end', $ret);
            return $ret;
        }
        logger('photo_upload: loading the contents of ' . $src, LOGGER_DEBUG);
        $imagedata = @file_get_contents($src);
    }
    $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($account_id));
    $limit = service_class_fetch($channel_id, 'photo_upload_limit');
    if ($r && $limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        $ret['message'] = upgrade_message();
        @unlink($src);
        call_hooks('photo_post_end', $ret);
        return $ret;
    }
    $ph = photo_factory($imagedata, $type);
    if (!$ph->is_valid()) {
        $ret['message'] = t('Unable to process image');
        logger('photo_upload: unable to process image');
        @unlink($src);
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    $exif = $ph->orient($src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $smallest = 0;
    $photo_hash = $args['resource_id'] ? $args['resource_id'] : photo_new_resource();
    $visitor = '';
    if ($channel['channel_hash'] !== $observer['xchan_hash']) {
        $visitor = $observer['xchan_hash'];
    }
    $errors = false;
    $p = array('aid' => $account_id, 'uid' => $channel_id, 'xchan' => $visitor, 'resource_id' => $photo_hash, 'filename' => $filename, 'album' => $album, 'scale' => 0, 'photo_flags' => PHOTO_NORMAL, 'allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow, 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny);
    if ($args['created']) {
        $p['created'] = $args['created'];
    }
    if ($args['edited']) {
        $p['edited'] = $args['edited'];
    }
    if ($args['title']) {
        $p['title'] = $args['title'];
    }
    if ($args['description']) {
        $p['description'] = $args['description'];
    }
    $r1 = $ph->save($p);
    if (!$r1) {
        $errors = true;
    }
    if (($width > 640 || $height > 640) && !$errors) {
        $ph->scaleImage(640);
        $p['scale'] = 1;
        $r2 = $ph->save($p);
        $smallest = 1;
        if (!$r2) {
            $errors = true;
        }
    }
    if (($width > 320 || $height > 320) && !$errors) {
        $ph->scaleImage(320);
        $p['scale'] = 2;
        $r3 = $ph->save($p);
        $smallest = 2;
        if (!$r3) {
            $errors = true;
        }
    }
    if ($errors) {
        q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), intval($channel_id));
        $ret['message'] = t('Photo storage failed.');
        logger('photo_upload: photo store failed.');
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    // This will be the width and height of the smallest representation
    $width_x_height = $ph->getWidth() . 'x' . $ph->getHeight();
    $mid = item_message_id();
    // Create item container
    $lat = $lon = null;
    if ($exif && $exif['GPS']) {
        if (feature_enabled($channel_id, 'photo_location')) {
            $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
            $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
        }
    }
    $item_flags = ITEM_WALL | ITEM_ORIGIN | ITEM_THREAD_TOP;
    $item_restrict = $visible ? ITEM_VISIBLE : ITEM_HIDDEN;
    $title = '';
    $mid = item_message_id();
    $arr = array();
    if ($lat && $lon) {
        $arr['coord'] = $lat . ' ' . $lon;
    }
    $arr['aid'] = $account_id;
    $arr['uid'] = $channel_id;
    $arr['mid'] = $mid;
    $arr['parent_mid'] = $mid;
    $arr['item_flags'] = $item_flags;
    $arr['item_restrict'] = $item_restrict;
    $arr['resource_type'] = 'photo';
    $arr['resource_id'] = $photo_hash;
    $arr['owner_xchan'] = $channel['channel_hash'];
    $arr['author_xchan'] = $observer['xchan_hash'];
    $arr['title'] = $title;
    $arr['allow_cid'] = $str_contact_allow;
    $arr['allow_gid'] = $str_group_allow;
    $arr['deny_cid'] = $str_contact_deny;
    $arr['deny_gid'] = $str_group_deny;
    $arr['verb'] = ACTIVITY_POST;
    $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid'];
    // We should also put a width_x_height on large photos. Left as an exercise for
    // devs looking fo simple stuff to fix.
    $larger = feature_enabled($channel['channel_id'], 'large_photos');
    if ($larger) {
        $tag = '[zmg]';
        if ($r2) {
            $smallest = 1;
        } else {
            $smallest = 0;
        }
    } else {
        if ($width_x_height) {
            $tag = '[zmg=' . $width_x_height . ']';
        } else {
            $tag = '[zmg]';
        }
    }
    $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/zmg]' . '[/zrl]';
    $result = item_store($arr);
    $item_id = $result['item_id'];
    if ($visible) {
        proc_run('php', "include/notifier.php", 'wall-new', $item_id);
    }
    $ret['success'] = true;
    $ret['item'] = $arr;
    $ret['body'] = $arr['body'];
    $ret['resource_id'] = $photo_hash;
    $ret['photoitem_id'] = $item_id;
    call_hooks('photo_upload_end', $ret);
    return $ret;
}
コード例 #16
0
ファイル: item.php プロジェクト: kenrestivo/hubzilla
function item_check_service_class($channel_id, $iswebpage)
{
    $ret = array('success' => false, 'message' => '');
    if ($iswebpage) {
        $r = q("select count(i.id)  as total from item i \n\t\t\tright join channel c on (i.author_xchan=c.channel_hash and i.uid=c.channel_id )  \n\t\t\tand i.parent=i.id and i.item_type = %d and i.item_deleted = 0 and i.uid= %d ", intval(ITEM_TYPE_WEBPAGE), intval($channel_id));
    } else {
        $r = q("select count(id) as total from item where parent = id and item_wall = 1 and uid = %d " . item_normal(), intval($channel_id));
    }
    if (!$r) {
        $ret['message'] = t('Unable to obtain post information from database.');
        return $ret;
    }
    if (!$iswebpage) {
        $max = service_class_fetch($channel_id, 'total_items');
        if (!service_class_allows($channel_id, 'total_items', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t('You have reached your limit of %1$.0f top level posts.'), $max);
            return $result;
        }
    } else {
        $max = service_class_fetch($channel_id, 'total_pages');
        if (!service_class_allows($channel_id, 'total_pages', $r[0]['total'])) {
            $result['message'] .= upgrade_message() . sprintf(t('You have reached your limit of %1$.0f webpages.'), $max);
            return $result;
        }
    }
    $ret['success'] = true;
    return $ret;
}
コード例 #17
0
ファイル: follow.php プロジェクト: BlaBlaNet/hubzilla
function new_contact($uid, $url, $channel, $interactive = false, $confirm = false)
{
    $result = array('success' => false, 'message' => '');
    $is_red = false;
    $is_http = strpos($url, '://') !== false ? true : false;
    if ($is_http && substr($url, -1, 1) === '/') {
        $url = substr($url, 0, -1);
    }
    if (!allowed_url($url)) {
        $result['message'] = t('Channel is blocked on this site.');
        return $result;
    }
    if (!$url) {
        $result['message'] = t('Channel location missing.');
        return $result;
    }
    // check service class limits
    $r = q("select count(*) as total from abook where abook_channel = %d and abook_self = 0 ", intval($uid));
    if ($r) {
        $total_channels = $r[0]['total'];
    }
    if (!service_class_allows($uid, 'total_channels', $total_channels)) {
        $result['message'] = upgrade_message();
        return $result;
    }
    $arr = array('url' => $url, 'channel' => array());
    call_hooks('follow', $arr);
    if ($arr['channel']['success']) {
        $ret = $arr['channel'];
    } elseif (!$is_http) {
        $ret = Zotlabs\Zot\Finger::run($url, $channel);
    }
    if ($ret && is_array($ret) && $ret['success']) {
        $is_red = true;
        $j = $ret;
    }
    $my_perms = get_channel_default_perms($uid);
    $role = get_pconfig($uid, 'system', 'permissions_role');
    if ($role) {
        $x = \Zotlabs\Access\PermissionRoles::role_perms($role);
        if ($x['perms_connect']) {
            $my_perms = $x['perms_connect'];
        }
    }
    if ($is_red && $j) {
        logger('follow: ' . $url . ' ' . print_r($j, true), LOGGER_DEBUG);
        if (!($j['success'] && $j['guid'])) {
            $result['message'] = t('Response from remote channel was incomplete.');
            logger('mod_follow: ' . $result['message']);
            return $result;
        }
        // Premium channel, set confirm before callback to avoid recursion
        if (array_key_exists('connect_url', $j) && $interactive && !$confirm) {
            goaway(zid($j['connect_url']));
        }
        // do we have an xchan and hubloc?
        // If not, create them.
        $x = import_xchan($j);
        if (array_key_exists('deleted', $j) && intval($j['deleted'])) {
            $result['message'] = t('Channel was deleted and no longer exists.');
            return $result;
        }
        if (!$x['success']) {
            return $x;
        }
        $xchan_hash = $x['hash'];
        if (array_key_exists('permissions', $j) && array_key_exists('data', $j['permissions'])) {
            $permissions = crypto_unencapsulate(array('data' => $j['permissions']['data'], 'key' => $j['permissions']['key'], 'iv' => $j['permissions']['iv']), $channel['channel_prvkey']);
            if ($permissions) {
                $permissions = json_decode($permissions, true);
            }
            logger('decrypted permissions: ' . print_r($permissions, true), LOGGER_DATA);
        } else {
            $permissions = $j['permissions'];
        }
        if (is_array($permissions) && $permissions) {
            foreach ($permissions as $k => $v) {
                set_abconfig($channel['channel_uid'], $xchan_hash, 'their_perms', $k, intval($v));
            }
        }
    } else {
        $xchan_hash = '';
        $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
        if (!$r) {
            // attempt network auto-discovery
            $d = discover_by_webbie($url);
            if (!$d && $is_http) {
                // try RSS discovery
                if (get_config('system', 'feed_contacts')) {
                    $d = discover_by_url($url);
                } else {
                    $result['message'] = t('Protocol disabled.');
                    return $result;
                }
            }
            if ($d) {
                $r = q("select * from xchan where xchan_hash = '%s' or xchan_url = '%s' limit 1", dbesc($url), dbesc($url));
            }
        }
        // if discovery was a success we should have an xchan record in $r
        if ($r) {
            $xchan = $r[0];
            $xchan_hash = $r[0]['xchan_hash'];
            $their_perms = 0;
        }
    }
    if (!$xchan_hash) {
        $result['message'] = t('Channel discovery failed.');
        logger('follow: ' . $result['message']);
        return $result;
    }
    $allowed = $is_red || $r[0]['xchan_network'] === 'rss' ? 1 : 0;
    $x = array('channel_id' => $uid, 'follow_address' => $url, 'xchan' => $r[0], 'allowed' => $allowed, 'singleton' => 0);
    call_hooks('follow_allow', $x);
    if (!$x['allowed']) {
        $result['message'] = t('Protocol disabled.');
        return $result;
    }
    $singleton = intval($x['singleton']);
    $aid = $channel['channel_account_id'];
    $hash = get_observer_hash();
    $default_group = $channel['channel_default_group'];
    if ($xchan['xchan_network'] === 'rss') {
        // check service class feed limits
        $r = q("select count(*) as total from abook where abook_account = %d and abook_feed = 1 ", intval($aid));
        if ($r) {
            $total_feeds = $r[0]['total'];
        }
        if (!service_class_allows($uid, 'total_feeds', $total_feeds)) {
            $result['message'] = upgrade_message();
            return $result;
        }
    }
    if ($hash == $xchan_hash) {
        $result['message'] = t('Cannot connect to yourself.');
        return $result;
    }
    $r = q("select abook_xchan, abook_instance from abook where abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($is_http) {
        // Always set these "remote" permissions for feeds since we cannot interact with them
        // to negotiate a suitable permission response
        set_abconfig($uid, $xchan_hash, 'their_perms', 'view_stream', 1);
        set_abconfig($uid, $xchan_hash, 'their_perms', 'republish', 1);
    }
    if ($r) {
        $abook_instance = $r[0]['abook_instance'];
        if ($singleton && strpos($abook_instance, z_root()) === false) {
            if ($abook_instance) {
                $abook_instance .= ',';
            }
            $abook_instance .= z_root();
        }
        $x = q("update abook set abook_instance = '%s' where abook_id = %d", dbesc($abook_instance), intval($r[0]['abook_id']));
    } else {
        $closeness = get_pconfig($uid, 'system', 'new_abook_closeness');
        if ($closeness === false) {
            $closeness = 80;
        }
        $r = q("insert into abook ( abook_account, abook_channel, abook_closeness, abook_xchan, abook_feed, abook_created, abook_updated, abook_instance )\n\t\t\tvalues( %d, %d, %d, '%s', %d, '%s', '%s', '%s' ) ", intval($aid), intval($uid), intval($closeness), dbesc($xchan_hash), intval($is_http ? 1 : 0), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc($singleton ? z_root() : ''));
    }
    if (!$r) {
        logger('mod_follow: abook creation failed');
    }
    $all_perms = \Zotlabs\Access\Permissions::Perms();
    if ($all_perms) {
        foreach ($all_perms as $k => $v) {
            if (in_array($k, $my_perms)) {
                set_abconfig($uid, $xchan_hash, 'my_perms', $k, 1);
            } else {
                set_abconfig($uid, $xchan_hash, 'my_perms', $k, 0);
            }
        }
    }
    $r = q("select abook.*, xchan.* from abook left join xchan on abook_xchan = xchan_hash \n\t\twhere abook_xchan = '%s' and abook_channel = %d limit 1", dbesc($xchan_hash), intval($uid));
    if ($r) {
        $result['abook'] = $r[0];
        Zotlabs\Daemon\Master::Summon(array('Notifier', 'permission_create', $result['abook']['abook_id']));
    }
    $arr = array('channel_id' => $uid, 'channel' => $channel, 'abook' => $result['abook']);
    call_hooks('follow', $arr);
    /** If there is a default group for this channel, add this connection to it */
    if ($default_group) {
        require_once 'include/group.php';
        $g = group_rec_byhash($uid, $default_group);
        if ($g) {
            group_add_member($uid, '', $xchan_hash, $g['id']);
        }
    }
    $result['success'] = true;
    return $result;
}
コード例 #18
0
ファイル: photos.php プロジェクト: kenrestivo/hubzilla
/**
 * @brief
 *
 * @param array $channel
 * @param array $observer
 * @param array $args
 * @return array
 */
function photo_upload($channel, $observer, $args)
{
    $ret = array('success' => false);
    $channel_id = $channel['channel_id'];
    $account_id = $channel['channel_account_id'];
    if (!perm_is_allowed($channel_id, $observer['xchan_hash'], 'write_storage')) {
        $ret['message'] = t('Permission denied.');
        return $ret;
    }
    //	call_hooks('photo_upload_begin', $args);
    /*
     * Determine the album to use
     */
    $album = $args['album'];
    if (intval($args['visible']) || $args['visible'] === 'true') {
        $visible = 1;
    } else {
        $visible = 0;
    }
    // Set to default channel permissions. If the parent directory (album) has permissions set,
    // use those instead. If we have specific permissions supplied, they take precedence over
    // all other settings. 'allow_cid' being passed from an external source takes priority over channel settings.
    // ...messy... needs re-factoring once the photos/files integration stabilises
    $acl = new AccessList($channel);
    if (array_key_exists('directory', $args) && $args['directory']) {
        $acl->set($args['directory']);
    }
    if (array_key_exists('allow_cid', $args)) {
        $acl->set($args);
    }
    if (array_key_exists('group_allow', $args) || array_key_exists('contact_allow', $args) || array_key_exists('group_deny', $args) || array_key_exists('contact_deny', $args)) {
        $acl->set_from_array($args);
    }
    $ac = $acl->get();
    $os_storage = 0;
    if ($args['os_path'] && $args['getimagesize']) {
        $imagedata = @file_get_contents($args['os_path']);
        $filename = $args['filename'];
        $filesize = strlen($imagedata);
        // this is going to be deleted if it exists
        $src = '/tmp/deletemenow';
        $type = $args['getimagesize']['mime'];
        $os_storage = 1;
    } elseif ($args['data']) {
        // allow an import from a binary string representing the image.
        // This bypasses the upload step and max size limit checking
        $imagedata = $args['data'];
        $filename = $args['filename'];
        $filesize = strlen($imagedata);
        // this is going to be deleted if it exists
        $src = '/tmp/deletemenow';
        $type = $args['type'];
    } else {
        $f = array('src' => '', 'filename' => '', 'filesize' => 0, 'type' => '');
        //		call_hooks('photo_upload_file',$f);
        if (x($f, 'src') && x($f, 'filesize')) {
            $src = $f['src'];
            $filename = $f['filename'];
            $filesize = $f['filesize'];
            $type = $f['type'];
        } else {
            $src = $_FILES['userfile']['tmp_name'];
            $filename = basename($_FILES['userfile']['name']);
            $filesize = intval($_FILES['userfile']['size']);
            $type = $_FILES['userfile']['type'];
        }
        if (!$type) {
            $type = guess_image_type($filename);
        }
        logger('photo_upload: received file: ' . $filename . ' as ' . $src . ' (' . $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG);
        $maximagesize = get_config('system', 'maximagesize');
        if ($maximagesize && $filesize > $maximagesize) {
            $ret['message'] = sprintf(t('Image exceeds website size limit of %lu bytes'), $maximagesize);
            @unlink($src);
            call_hooks('photo_upload_end', $ret);
            return $ret;
        }
        if (!$filesize) {
            $ret['message'] = t('Image file is empty.');
            @unlink($src);
            call_hooks('photo_post_end', $ret);
            return $ret;
        }
        logger('photo_upload: loading the contents of ' . $src, LOGGER_DEBUG);
        $imagedata = @file_get_contents($src);
    }
    $r = q("select sum(size) as total from photo where aid = %d and scale = 0 ", intval($account_id));
    $limit = service_class_fetch($channel_id, 'photo_upload_limit');
    if ($r && $limit !== false && $r[0]['total'] + strlen($imagedata) > $limit) {
        $ret['message'] = upgrade_message();
        @unlink($src);
        call_hooks('photo_post_end', $ret);
        return $ret;
    }
    $ph = photo_factory($imagedata, $type);
    if (!$ph->is_valid()) {
        $ret['message'] = t('Unable to process image');
        logger('photo_upload: unable to process image');
        @unlink($src);
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    $exif = $ph->orient($args['os_path'] ? $args['os_path'] : $src);
    @unlink($src);
    $max_length = get_config('system', 'max_image_length');
    if (!$max_length) {
        $max_length = MAX_IMAGE_LENGTH;
    }
    if ($max_length > 0) {
        $ph->scaleImage($max_length);
    }
    $width = $ph->getWidth();
    $height = $ph->getHeight();
    $smallest = 0;
    $photo_hash = $args['resource_id'] ? $args['resource_id'] : photo_new_resource();
    $visitor = '';
    if ($channel['channel_hash'] !== $observer['xchan_hash']) {
        $visitor = $observer['xchan_hash'];
    }
    $errors = false;
    $p = array('aid' => $account_id, 'uid' => $channel_id, 'xchan' => $visitor, 'resource_id' => $photo_hash, 'filename' => $filename, 'album' => $album, 'scale' => 0, 'photo_usage' => PHOTO_NORMAL, 'allow_cid' => $ac['allow_cid'], 'allow_gid' => $ac['allow_gid'], 'deny_cid' => $ac['deny_cid'], 'deny_gid' => $ac['deny_gid'], 'os_storage' => $os_storage, 'os_path' => $args['os_path']);
    if ($args['created']) {
        $p['created'] = $args['created'];
    }
    if ($args['edited']) {
        $p['edited'] = $args['edited'];
    }
    if ($args['title']) {
        $p['title'] = $args['title'];
    }
    if ($args['description']) {
        $p['description'] = $args['description'];
    }
    $r1 = $ph->save($p);
    if (!$r1) {
        $errors = true;
    }
    unset($p['os_storage']);
    unset($p['os_path']);
    if (($width > 640 || $height > 640) && !$errors) {
        $ph->scaleImage(640);
        $p['scale'] = 1;
        $r2 = $ph->save($p);
        $smallest = 1;
        if (!$r2) {
            $errors = true;
        }
    }
    if (($width > 320 || $height > 320) && !$errors) {
        $ph->scaleImage(320);
        $p['scale'] = 2;
        $r3 = $ph->save($p);
        $smallest = 2;
        if (!$r3) {
            $errors = true;
        }
    }
    if ($errors) {
        q("delete from photo where resource_id = '%s' and uid = %d", dbesc($photo_hash), intval($channel_id));
        $ret['message'] = t('Photo storage failed.');
        logger('photo_upload: photo store failed.');
        call_hooks('photo_upload_end', $ret);
        return $ret;
    }
    // This will be the width and height of the smallest representation
    $width_x_height = $ph->getWidth() . 'x' . $ph->getHeight();
    // Create item container
    $item_hidden = $visible ? 0 : 1;
    $lat = $lon = null;
    if ($exif && $exif['GPS']) {
        if (feature_enabled($channel_id, 'photo_location')) {
            $lat = getGps($exif['GPS']['GPSLatitude'], $exif['GPS']['GPSLatitudeRef']);
            $lon = getGps($exif['GPS']['GPSLongitude'], $exif['GPS']['GPSLongitudeRef']);
        }
    }
    if ($args['item']) {
        foreach ($args['item'] as $i) {
            $item = get_item_elements($i);
            $force = false;
            if ($item['mid'] === $item['parent_mid']) {
                $item['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/zmg]' . '[/zrl]';
                if ($item['author_xchan'] === $channel['channel_hash']) {
                    $item['sig'] = base64url_encode(rsa_sign($item['body'], $channel['channel_prvkey']));
                    $item['item_verified'] = 1;
                } else {
                    $item['sig'] = '';
                }
                $force = true;
            }
            $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'] || $force) {
                    $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);
            }
        }
    } else {
        $title = '';
        $mid = item_message_id();
        $arr = array();
        if ($lat && $lon) {
            $arr['coord'] = $lat . ' ' . $lon;
        }
        $arr['aid'] = $account_id;
        $arr['uid'] = $channel_id;
        $arr['mid'] = $mid;
        $arr['parent_mid'] = $mid;
        $arr['item_hidden'] = $item_hidden;
        $arr['resource_type'] = 'photo';
        $arr['resource_id'] = $photo_hash;
        $arr['owner_xchan'] = $channel['channel_hash'];
        $arr['author_xchan'] = $observer['xchan_hash'];
        $arr['title'] = $title;
        $arr['allow_cid'] = $ac['allow_cid'];
        $arr['allow_gid'] = $ac['allow_gid'];
        $arr['deny_cid'] = $ac['deny_cid'];
        $arr['deny_gid'] = $ac['deny_gid'];
        $arr['verb'] = ACTIVITY_POST;
        $arr['item_wall'] = 1;
        $arr['item_origin'] = 1;
        $arr['item_thread_top'] = 1;
        $arr['item_private'] = intval($acl->is_private());
        $arr['plink'] = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $arr['mid'];
        // We should also put a width_x_height on large photos. Left as an exercise for
        // devs looking for simple stuff to fix.
        $larger = feature_enabled($channel['channel_id'], 'large_photos');
        if ($larger) {
            $tag = '[zmg]';
            if ($r2) {
                $smallest = 1;
            } else {
                $smallest = 0;
            }
        } else {
            if ($width_x_height) {
                $tag = '[zmg=' . $width_x_height . ']';
            } else {
                $tag = '[zmg]';
            }
        }
        $arr['body'] = '[zrl=' . z_root() . '/photos/' . $channel['channel_address'] . '/image/' . $photo_hash . ']' . $tag . z_root() . "/photo/{$photo_hash}-{$smallest}." . $ph->getExt() . '[/zmg]' . '[/zrl]';
        $result = item_store($arr);
        $item_id = $result['item_id'];
        if ($visible) {
            proc_run('php', "include/notifier.php", 'wall-new', $item_id);
        }
    }
    $ret['success'] = true;
    $ret['item'] = $arr;
    $ret['body'] = $arr['body'];
    $ret['resource_id'] = $photo_hash;
    $ret['photoitem_id'] = $item_id;
    call_hooks('photo_upload_end', $ret);
    return $ret;
}