function ws_images_addFlickr($photo, &$service)
{
    if (!is_admin()) {
        return new PwgError(403, 'Forbidden');
    }
    global $conf;
    if (empty($conf['flickr2piwigo']['api_key']) or empty($conf['flickr2piwigo']['secret_key'])) {
        return new PwgError(null, l10n('Please fill your API keys on the configuration tab'));
    }
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    include_once PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php';
    include_once FLICKR_PATH . 'include/functions.inc.php';
    if (test_remote_download() === false) {
        return new PwgError(null, l10n('No download method available'));
    }
    // init flickr API
    include_once FLICKR_PATH . 'include/phpFlickr/phpFlickr.php';
    $flickr = new phpFlickr($conf['flickr2piwigo']['api_key'], $conf['flickr2piwigo']['secret_key']);
    $flickr->enableCache('fs', FLICKR_FS_CACHE);
    // user
    $u = $flickr->test_login();
    if ($u === false or empty($_SESSION['phpFlickr_auth_token'])) {
        return new PwgError(403, l10n('API not authenticated'));
    }
    // photos infos
    $photo_f = $flickr->photos_getInfo($photo['id']);
    $photo = array_merge($photo, $photo_f['photo']);
    $photo['url'] = $flickr->get_biggest_size($photo['id'], 'original');
    $photo['path'] = FLICKR_FS_CACHE . 'flickr-' . $u['username'] . '-' . $photo['id'] . '.' . get_extension($photo['url']);
    // copy file
    if (download_remote_file($photo['url'], $photo['path']) == false) {
        return new PwgError(null, l10n('Can\'t download file'));
    }
    // category
    if (!preg_match('#^[0-9]+$#', $photo['category'])) {
        $categories_names = explode(',', $photo['category']);
        $photo['category'] = array();
        foreach ($categories_names as $category_name) {
            $query = '
SELECT id FROM ' . CATEGORIES_TABLE . '
  WHERE LOWER(name) = "' . strtolower($category_name) . '"
;';
            $result = pwg_query($query);
            if (pwg_db_num_rows($result)) {
                list($cat_id) = pwg_db_fetch_row($result);
                $photo['category'][] = $cat_id;
            } else {
                $cat = create_virtual_category($category_name);
                $photo['category'][] = $cat['id'];
            }
        }
    } else {
        $photo['category'] = array($photo['category']);
    }
    // add photo
    $photo['image_id'] = add_uploaded_file($photo['path'], basename($photo['path']), $photo['category']);
    // do some updates
    if (!empty($photo['fills'])) {
        $photo['fills'] = rtrim($photo['fills'], ',');
        $photo['fills'] = explode(',', $photo['fills']);
        $updates = array();
        if (in_array('fill_name', $photo['fills'])) {
            $updates['name'] = pwg_db_real_escape_string($photo['title']);
        }
        if (in_array('fill_posted', $photo['fills'])) {
            $updates['date_available'] = date('Y-m-d H:i:s', $photo['dates']['posted']);
        }
        if (in_array('fill_taken', $photo['fills'])) {
            $updates['date_creation'] = $photo['dates']['taken'];
        }
        if (in_array('fill_author', $photo['fills'])) {
            $updates['author'] = pwg_db_real_escape_string($photo['owner']['username']);
        }
        if (in_array('fill_description', $photo['fills'])) {
            $updates['comment'] = pwg_db_real_escape_string(@$photo['description']);
        }
        if (in_array('fill_geotag', $photo['fills']) and !empty($photo['location'])) {
            $updates['latitude'] = pwg_db_real_escape_string($photo['location']['latitude']);
            $updates['longitude'] = pwg_db_real_escape_string($photo['location']['longitude']);
        }
        if (in_array('level', $photo['fills']) && !$photo['visibility']['ispublic']) {
            $updates['level'] = 8;
            if ($photo['visibility']['isfamily']) {
                $updates['level'] = 4;
            }
            if ($photo['visibility']['isfriend']) {
                $updates['level'] = 2;
            }
        }
        if (count($updates)) {
            single_update(IMAGES_TABLE, $updates, array('id' => $photo['image_id']));
        }
        if (!empty($photo['tags']['tag']) and in_array('fill_tags', $photo['fills'])) {
            $raw_tags = array_map(create_function('$t', 'return $t["_content"];'), $photo['tags']['tag']);
            $raw_tags = implode(',', $raw_tags);
            set_tags(get_tag_ids($raw_tags), $photo['image_id']);
        }
    }
    return l10n('Photo "%s" imported', $photo['title']);
}
function ws_images_addRemote($params, &$service)
{
    global $conf;
    if (!is_admin()) {
        return new PwgError(401, 'Access denied');
    }
    load_language('plugin.lang', URLUPLOADER_PATH);
    $params = array_map('trim', $params);
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
    $allowed_mimes = array('image/jpeg', 'image/png', 'image/gif');
    // check empty url
    if (empty($params['file_url'])) {
        return new PwgError(WS_ERR_INVALID_PARAM, l10n('File URL is empty'));
    }
    // check remote url
    if (!url_is_remote($params['file_url'])) {
        return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file URL'));
    }
    // check file extension
    if (!in_array(strtolower(get_extension($params['file_url'])), $allowed_extensions)) {
        return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file type'));
    }
    // download file
    include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
    $temp_filename = $conf['data_location'] . basename($params['file_url']);
    $file = fopen($temp_filename, 'w+');
    $result = fetchRemote($params['file_url'], $file);
    fclose($file);
    // download failed ?
    if (!$result) {
        @unlink($temp_filename);
        return new PwgError(WS_ERR_INVALID_PARAM, l10n('Unable to download file'));
    }
    // check mime-type
    if (!in_array(get_mime($temp_filename, $allowed_mimes[0]), $allowed_mimes)) {
        @unlink($temp_filename);
        return new PwgError(WS_ERR_INVALID_PARAM, l10n('Invalid file type'));
    }
    // add photo
    include_once PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php';
    $image_id = add_uploaded_file($temp_filename, basename($temp_filename), array($params['category']), $params['level']);
    $updates = array();
    if (!empty($params['name'])) {
        $updates['name'] = $params['name'];
    }
    if ($params['url_in_comment'] == 'true') {
        $url = parse_url($params['file_url']);
        $url = $url['scheme'] . '://' . $url['host'];
        $updates['comment'] = '<a href="' . $url . '">' . $url . '</a>';
    }
    single_update(IMAGES_TABLE, $updates, array('id' => $image_id));
    // return infos
    $query = '
SELECT id, name, permalink
  FROM ' . CATEGORIES_TABLE . '
  WHERE id = ' . $params['category'] . '
;';
    $category = pwg_db_fetch_assoc(pwg_query($query));
    $url_params = array('image_id' => $image_id, 'section' => 'categories', 'category' => $category);
    $query = '
SELECT id, path, name
  FROM ' . IMAGES_TABLE . '
  WHERE id = ' . $image_id . '
;';
    $image_infos = pwg_db_fetch_assoc(pwg_query($query));
    $query = '
SELECT
    COUNT(*) AS nb_photos
  FROM ' . IMAGE_CATEGORY_TABLE . '
  WHERE category_id = ' . $params['category'] . '
;';
    $category_infos = pwg_db_fetch_assoc(pwg_query($query));
    $category_name = get_cat_display_name_from_id($params['category'], null);
    return array('image_id' => $image_id, 'url' => make_picture_url($url_params), 'src' => DerivativeImage::thumb_url($image_infos), 'name' => $image_infos['name'], 'category' => array('id' => $params['category'], 'nb_photos' => $category_infos['nb_photos'], 'label' => $category_name));
}
function pfemail_check_accounts()
{
    global $conf, $user;
    conf_update_param('pfemail_last_check', date('Y-m-d H:i:s'));
    require_once PFEMAIL_PATH . 'include/ImapMailbox.php';
    $image_ids = array();
    $query = '
SELECT
    *
  FROM ' . PFEMAIL_MAILBOXES_TABLE . '
;';
    $accounts = query2array($query);
    foreach ($accounts as $account) {
        $mailbox = new ImapMailbox($account['path'], $account['login'], $account['password'], $conf['upload_dir'] . '/buffer', 'utf-8');
        $mails = array();
        // Get some mail
        $mailsIds = $mailbox->searchMailBox('UNSEEN');
        if (!$mailsIds) {
            continue;
            // check next email account
        }
        $mailId = reset($mailsIds);
        $mail = $mailbox->getMail($mailId);
        $attachments = $mail->getAttachments();
        include_once PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php';
        foreach ($attachments as $attachment) {
            $extension = strtolower(get_extension($attachment->{'name'}));
            if (!in_array($extension, $conf['picture_ext'])) {
                // the file has been downloaded, we have to remove it now
                unlink($attachment->{'filePath'});
                continue;
            }
            $moderate = get_boolean($account['moderated']);
            $image_id = add_uploaded_file($attachment->{'filePath'}, stripslashes($attachment->{'name'}), array($account['category_id']), $moderate ? 16 : 0, null);
            // the photo is added by nobody (using the current user may make the
            // photo editable by her with Admin Tools...)
            single_update(IMAGES_TABLE, array('added_by' => null, 'name' => pfemail_clean_email_subject($mail->subject)), array('id' => $image_id));
            $state = 'auto_validated';
            if ($moderate) {
                $state = 'moderation_pending';
            }
            list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
            single_insert(PFEMAIL_PENDINGS_TABLE, array('image_id' => $image_id, 'state' => $state, 'added_on' => $dbnow, 'from_name' => $mail->fromName, 'from_address' => $mail->fromAddress, 'subject' => $mail->subject));
            $image_ids[] = $image_id;
        }
    }
    if (count($image_ids) > 0) {
        include_once PHPWG_ROOT_PATH . 'admin/include/functions.php';
        invalidate_user_cache();
        // let's notify administrators
        $query = '
SELECT id
  FROM ' . GROUPS_TABLE . '
;';
        $group_ids = query2array($query, null, 'id');
        if (count($group_ids) > 0) {
            include_once PHPWG_ROOT_PATH . 'include/functions_mail.inc.php';
            $thumb_urls = array();
            // force $conf['derivative_url_style'] to 2 (script) to make sure we
            // will use i.php?/upload and not _data/i/upload because you don't
            // know when the cache will be flushed
            $previous_derivative_url_style = $conf['derivative_url_style'];
            $conf['derivative_url_style'] = 2;
            $query = '
SELECT
    id,
    path
  FROM ' . IMAGES_TABLE . '
  WHERE id IN (' . implode(',', $image_ids) . ')
;';
            $result = pwg_query($query);
            while ($row = pwg_db_fetch_assoc($result)) {
                $thumb = DerivativeImage::thumb_url(array('id' => $row['id'], 'path' => $row['path']));
                $thumb_urls[] = $thumb;
            }
            // restore configuration setting
            $conf['derivative_url_style'] = $previous_derivative_url_style;
            $thumbs_html_string = '';
            foreach ($thumb_urls as $thumb_url) {
                if (!empty($thumbs_html_string)) {
                    $thumbs_html_string .= '&nbsp;';
                }
                $thumbs_html_string .= '<img src="' . $thumb_url . '">';
            }
            $content = $thumbs_html_string;
            // how many photos pending?
            $pendings = pfemail_get_pending_ids();
            if (count($pendings) > 0) {
                $content .= '<br><br>';
                $content .= '<a href="' . get_absolute_root_url() . 'admin.php?page=plugin-photo_from_email-pendings' . '">';
                $content .= l10n('%d photos pending for validation', count($pendings));
                $content .= '</a>';
            }
            $real_user_id = $user['id'];
            $user['id'] = $conf['guest_id'];
            $subject = l10n('%d photos added by email', count($thumb_urls));
            foreach ($group_ids as $group_id) {
                pwg_mail_group($group_id, array('subject' => '[' . $conf['gallery_title'] . '] ' . $subject, 'mail_title' => $conf['gallery_title'], 'mail_subtitle' => $subject, 'content' => $content, 'content_format' => 'text/html'));
            }
        }
        // restore current user
        $user['id'] = $real_user_id;
    }
}
Example #4
0
/**
 * API method
 * Adds a image (simple way)
 * @param mixed[] $params
 *    @option int[] category
 *    @option string name (optional)
 *    @option string author (optional)
 *    @option string comment (optional)
 *    @option int level
 *    @option string|string[] tags
 *    @option int image_id (optional)
 */
function ws_images_upload($params, $service)
{
    global $conf;
    if (get_pwg_token() != $params['pwg_token']) {
        return new PwgError(403, 'Invalid security token');
    }
    // usleep(100000);
    // if (!isset($_FILES['image']))
    // {
    //   return new PwgError(405, 'The image (file) is missing');
    // }
    // file_put_contents('/tmp/plupload.log', "[".date('c')."] ".__FUNCTION__."\n\n", FILE_APPEND);
    // file_put_contents('/tmp/plupload.log', '$_FILES = '.var_export($_FILES, true)."\n", FILE_APPEND);
    // file_put_contents('/tmp/plupload.log', '$_POST = '.var_export($_POST, true)."\n", FILE_APPEND);
    $upload_dir = $conf['upload_dir'] . '/buffer';
    // create the upload directory tree if not exists
    if (!mkgetdir($upload_dir, MKGETDIR_DEFAULT & ~MKGETDIR_DIE_ON_ERROR)) {
        return new PwgError(500, 'error during buffer directory creation');
    }
    // Get a file name
    if (isset($_REQUEST["name"])) {
        $fileName = $_REQUEST["name"];
    } elseif (!empty($_FILES)) {
        $fileName = $_FILES["file"]["name"];
    } else {
        $fileName = uniqid("file_");
    }
    $filePath = $upload_dir . DIRECTORY_SEPARATOR . $fileName;
    // Chunking might be enabled
    $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
    $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
    // file_put_contents('/tmp/plupload.log', "[".date('c')."] ".__FUNCTION__.', '.$fileName.' '.($chunk+1).'/'.$chunks."\n", FILE_APPEND);
    // Open temp file
    if (!($out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb"))) {
        die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
    }
    if (!empty($_FILES)) {
        if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        }
        // Read binary input stream and append it to temp file
        if (!($in = @fopen($_FILES["file"]["tmp_name"], "rb"))) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
        }
    } else {
        if (!($in = @fopen("php://input", "rb"))) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
        }
    }
    while ($buff = fread($in, 4096)) {
        fwrite($out, $buff);
    }
    @fclose($out);
    @fclose($in);
    // Check if file has been uploaded
    if (!$chunks || $chunk == $chunks - 1) {
        // Strip the temp .part suffix off
        rename("{$filePath}.part", $filePath);
        include_once PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php';
        $image_id = add_uploaded_file($filePath, stripslashes($params['name']), $params['category'], $params['level'], null);
        $query = '
SELECT
    id,
    name,
    representative_ext,
    path
  FROM ' . IMAGES_TABLE . '
  WHERE id = ' . $image_id . '
;';
        $image_infos = pwg_db_fetch_assoc(pwg_query($query));
        $query = '
SELECT
    COUNT(*) AS nb_photos
  FROM ' . IMAGE_CATEGORY_TABLE . '
  WHERE category_id = ' . $params['category'][0] . '
;';
        $category_infos = pwg_db_fetch_assoc(pwg_query($query));
        $category_name = get_cat_display_name_from_id($params['category'][0], null);
        return array('image_id' => $image_id, 'src' => DerivativeImage::thumb_url($image_infos), 'name' => $image_infos['name'], 'category' => array('id' => $params['category'][0], 'nb_photos' => $category_infos['nb_photos'], 'label' => $category_name));
    }
}