<?php

/**
 * Unlink an attachment
 *
 * @category Messagerie
 * @package  Mediboard
 * @author   SARL OpenXtrem <*****@*****.**>
 * @license  GNU General Public License, see http://www.gnu.org/licenses/gpl.html
 * @version  SVN: $Id:\$
 * @link     http://www.mediboard.org
 */
CCanDo::checkEdit();
$attachment_id = CValue::get("attachment_id");
//open the attachment
$attachment = new CMailAttachments();
$attachment->load($attachment_id);
$attachment->loadFiles();
//work
$file = $attachment->_file;
$file->setObject($attachment);
if (!($msg = $file->store())) {
    $attachment->file_id = "";
    if (!($msg2 = $attachment->store())) {
        CAppUI::stepAjax("CMailAttachments-unlinked", UI_MSG_OK);
    } else {
        CAppUI::stepAjax("CMailAttachments-unlinked-failed", UI_MSG_ERROR, $msg2);
    }
}
$mail->load($mail_id);
if (!$object->_id) {
    CAppUI::stepAjax("CUserMail-link-objectNull", UI_MSG_ERROR);
}
if (str_replace("-", "", $attach_list) == "" && !$text_plain && !$text_html) {
    CAppUI::stepAjax("CMailAttachments-msg-no_object_to_attach", UI_MSG_ERROR);
}
$attachments = trim($attach_list) ? explode("-", $attach_list) : array();
foreach ($attachments as $_attachment) {
    //no attachment value
    if (!$_attachment) {
        continue;
    }
    $attachment = new CMailAttachments();
    if ($_attachment != "") {
        $attachment->load($_attachment);
        $attachment->loadRefsFwd();
        //already linked = skip, no id, skip
        if ($attachment->file_id || !$attachment->_id) {
            continue;
        }
    }
    //linking
    if ($attachment->_file->_id) {
        $attachment->_file->setObject($object);
        if ($msg = $attachment->_file->store()) {
            CAppUI::setMsg($msg, UI_MSG_ERROR);
        } else {
            $attachment->file_id = $attachment->_file->_id;
            if ($msg = $attachment->store()) {
                CAppUI::setMsg($msg, UI_MSG_ERROR);