/**
 * Uploads image given as a binnary stream or the base64 data.
 */
function imgevr_upload_image()
{
    $mime = !empty($_POST['imgMime']) ? $_POST['imgMime'] : null;
    if ('null' === $mime) {
        $mime = null;
    }
    $name = !empty($_POST['imgName']) ? $_POST['imgName'] : null;
    if ('null' === $name) {
        $name = null;
    }
    $parentId = isset($_POST['imgParent']) ? intval($_POST['imgParent']) : 0;
    $ref = isset($_POST['imgRef']) ? $_POST['imgRef'] : false;
    if (empty($mime)) {
        if (!empty($_POST['file']) && preg_match('/image\\/[a-z0-9]+/', $_POST['file'], $matches)) {
            $mime = $matches[0];
        } else {
            factory_325_json_error('Unable to get mime type of the file.');
        }
    }
    // gets extension
    $parts = explode('/', $mime);
    $ext = empty($parts[1]) ? 'png' : $parts[1];
    // check the path to upload
    $uploadInfo = wp_upload_dir();
    $targetPath = $uploadInfo['path'];
    if (!is_dir($targetPath)) {
        mkdir($targetPath, 0777, true);
    }
    // move the uploaded file to the upload path
    $imageName = !empty($name) && $name !== 'undefined' ? factory_325_filename_without_ext($name) : 'img_' . uniqid();
    $target = $targetPath . '/' . $imageName . '.' . $ext;
    if (isset($_FILES['file'])) {
        if (empty($_FILES['file']['size'])) {
            factory_325_json_error('Sorry, the error of reading image data occured. May be the image is empty of has incorrect format.');
        }
        $source = $_FILES['file']['tmp_name'];
        move_uploaded_file($source, $target);
    } else {
        if (preg_match('/base64,(.*)/', $_POST['file'], $matches)) {
            $img = str_replace(' ', '+', $matches[1]);
            $data = base64_decode($img);
            $success = file_put_contents($target, $data);
            if (!$success) {
                factory_325_json_error('Unable to save the image.');
            }
        } else {
            factory_325_json_error('Incorrect file format (base64).');
        }
    }
    $media = array();
    $media['base'] = array('guid' => $uploadInfo['url'] . '/' . $imageName . '.' . $ext, 'path' => $target, 'name' => $imageName);
    $resizingEnabled = false;
    $compressionEnabled = false;
    // for the function wp_generate_attachment_metadata() to work
    require_once ABSPATH . 'wp-admin/includes/image.php';
    foreach ($media as $key => $item) {
        $attachment = array('guid' => $item['guid'], 'post_mime_type' => $mime, 'post_title' => $item['name'], 'post_name' => $item['name'], 'post_content' => '', 'post_status' => 'inherit');
        $media[$key]['id'] = wp_insert_attachment($attachment, $item['path'], $parentId);
        $attach_data = wp_generate_attachment_metadata($media[$key]['id'], $item['path']);
        wp_update_attachment_metadata($media[$key]['id'], $attach_data);
    }
    $id = $media['base']['id'];
    $cssClasses = ' ' . trim(get_option('imgevr_css_class', ''));
    if (!empty($id)) {
        $html = "<img alt='' class='alignnone size-full wp-image-" . $id . $cssClasses . "' src='" . $media['base']['guid'] . "' />";
    } else {
        $html = "<img alt='' class='alignnone size-full" . $cssClasses . "' src='" . $media['base']['guid'] . "' />";
    }
    $linksEnabled = get_option('imgevr_links_enable', false);
    if ($linksEnabled) {
        $saveOriginal = get_option('imgevr_resizing_save_original', false);
        if ($resizingEnabled && $saveOriginal) {
            $html = "<a href='" . $media['original']['guid'] . "'>" . $html . '</a>';
        } else {
            $html = "<a href='" . $media['base']['guid'] . "'>" . $html . '</a>';
        }
    }
    $result = array('html' => $html);
    echo json_encode($result);
    exit;
}
/**
 * Renames the given image. May return a confirmation request.
 */
function imgevr_rename_image()
{
    global $clipImages;
    if (in_array($clipImages->license->type, array('free'))) {
        return;
    }
    // value of the 'src' attribute of a given image
    $imgUrl = trim($_POST['imgUrl']);
    // a new image name specified by a user
    $imgName = sanitize_title(trim($_POST['imgName']));
    // image attachment id, may be missed
    $imgId = isset($_POST['imgId']) ? intval($_POST['imgId']) : 0;
    // post id where a given image is
    $postId = isset($_POST['imgPostId']) ? intval($_POST['imgPostId']) : 0;
    // post id where a given image is
    $overwrite = isset($_POST['imgOverwrite']) && $_POST['imgOverwrite'] ? true : false;
    if (empty($imgUrl) || empty($imgName)) {
        exit;
    }
    // extracts relative image path from url
    $uploadData = wp_upload_dir();
    $siteUrl = trailingslashit(site_url());
    // default 'wp-content/uploads/'
    $term = trailingslashit(str_replace($siteUrl, '', $uploadData['baseurl']));
    $partPos = strpos($imgUrl, $term);
    if ($partPos === false) {
        factory_325_json_error('Sorry, the file for renaming has been not found on your server.');
    }
    $relPath = substr($imgUrl, $partPos + strlen($term), strlen($imgUrl));
    $absPath = $uploadData['basedir'] . '/' . $relPath;
    $orgData = factory_325_pathinfo($relPath);
    if (!is_file($absPath)) {
        factory_325_json_error('Sorry, the file for renaming is not found on your server.');
    }
    // if original file already has a given name
    if ($orgData['basename'] == $imgName) {
        return;
    }
    $newRelPath = $orgData['dirname'] . '/' . $imgName . '.' . $orgData['extension'];
    $newAbsPath = $uploadData['basedir'] . '/' . $newRelPath;
    $newAbsUrl = $uploadData['baseurl'] . '/' . $newRelPath;
    // checks if the file with the specified name already exist
    if (is_file($newAbsPath) && !$overwrite) {
        echo json_encode(array('confirm' => 'The file <strong>' . $imgName . '.' . $orgData['extension'] . '</strong> already exists on the server. What to do?', 'src' => $newAbsUrl));
        exit;
    }
    // updates a post content to avoid the situation
    // when the a user have renamed an images, but did't not save the post
    if (!empty($postId)) {
        $post = get_post($postId);
        $content = str_replace($relPath, $newRelPath, $post->post_content);
        wp_update_post(array('ID' => $post->ID, 'post_content' => $content));
    }
    // deletes the existing file if a user asked to overwrite it
    if (is_file($newAbsPath) && $overwrite) {
        unlink($newAbsPath);
    }
    // renames the file
    rename($absPath, $newAbsPath);
    // updates attachemnt data if the image id is specified
    if (!empty($imgId)) {
        $data = array('ID' => $imgId, 'guid' => $newAbsUrl, 'post_name' => $imgName, 'post_title' => $imgName);
        wp_update_post($data);
        $attach_data = wp_generate_attachment_metadata($imgId, $newAbsPath);
        wp_update_attachment_metadata($imgId, $attach_data);
        update_post_meta($imgId, '_wp_attached_file', $newRelPath);
    }
    echo json_encode(array('src' => $newAbsUrl));
    exit;
}