function saveFile($document, $portal = false)
 {
     global $sugar_config;
     $focus = new Document();
     if (!empty($document['id'])) {
         $focus->retrieve($document['id']);
     } else {
         return '-1';
     }
     if (!empty($document['file'])) {
         $decodedFile = base64_decode($document['file']);
         $this->upload_file->set_for_soap($document['filename'], $decodedFile);
         $ext_pos = strrpos($this->upload_file->stored_file_name, ".");
         $this->upload_file->file_ext = substr($this->upload_file->stored_file_name, $ext_pos + 1);
         if (in_array($this->upload_file->file_ext, $sugar_config['upload_badext'])) {
             $this->upload_file->stored_file_name .= ".txt";
             $this->upload_file->file_ext = "txt";
         }
         $revision = new DocumentRevision();
         $revision->filename = $this->upload_file->get_stored_file_name();
         $revision->file_mime_type = $this->upload_file->getMimeSoap($revision->filename);
         $revision->file_ext = $this->upload_file->file_ext;
         //$revision->document_name = ;
         $revision->revision = $document['revision'];
         $revision->document_id = $document['id'];
         $revision->save();
         $focus->document_revision_id = $revision->id;
         $focus->save();
         $return_id = $revision->id;
         $this->upload_file->final_move($revision->id);
     } else {
         return '-1';
     }
     return $return_id;
 }
function get_all_linked_attachment_revisions($attachmentsequence)
{
    $attachmentIds = explode(' ', trim($attachmentsequence));
    $attachments = array();
    foreach ($attachmentIds as $id) {
        $revision = new DocumentRevision();
        if (!$revision->retrieve($id)) {
            // if in old format try to recover by document id
            $attachment = new Document();
            if ($attachment->retrieve($id)) {
                $attachment->revision = '';
                $attachment->doc_rev_id = '';
                $attachments[] = $attachment;
            }
        } else {
            $attachment = new Document();
            if ($attachment->retrieve($revision->document_id)) {
                $attachment->revision = $revision->revision;
                $attachment->doc_rev_id = $revision->id;
                $attachments[] = $attachment;
            }
        }
    }
    return $attachments;
}
Example #3
0
 function testRevisionSave()
 {
     $ret = $GLOBALS['db']->query("SELECT COUNT(*) AS rowcount1 FROM document_revisions WHERE document_id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertEquals($row['rowcount1'], 0, 'We created an empty revision');
     $ret = $GLOBALS['db']->query("SELECT document_revision_id FROM documents WHERE id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertTrue(empty($row['document_revision_id']), 'We linked the document to a fake document_revision');
     $ds = new DocumentSoap();
     $revision_stuff = array('file' => base64_encode('Pickles has an extravagant beard of pine fur.'), 'filename' => 'a_file_about_pickles.txt', 'id' => $this->doc->id, 'revision' => '1');
     $revisionId = $ds->saveFile($revision_stuff);
     $ret = $GLOBALS['db']->query("SELECT COUNT(*) AS rowcount1 FROM document_revisions WHERE document_id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertEquals($row['rowcount1'], 1, 'We didn\'t create a revision when we should have');
     $ret = $GLOBALS['db']->query("SELECT document_revision_id FROM documents WHERE id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertEquals($row['document_revision_id'], $revisionId, 'We didn\'t link the newly created document revision to the document');
     // Double saving doesn't work because save doesn't reset the new_with_id
     $newDoc = new Document();
     $newDoc->retrieve($this->doc->id);
     $newDoc->document_revision_id = $revisionId;
     $newDoc->save(FALSE);
     $ret = $GLOBALS['db']->query("SELECT COUNT(*) AS rowcount1 FROM document_revisions WHERE document_id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertEquals($row['rowcount1'], 1, 'We didn\'t create a revision when we should have');
     $ret = $GLOBALS['db']->query("SELECT document_revision_id FROM documents WHERE id = '{$this->doc->id}'");
     $row = $GLOBALS['db']->fetchByAssoc($ret);
     $this->assertEquals($row['document_revision_id'], $revisionId, 'We didn\'t link the newly created document revision to the document');
 }
 function fill_in_relationship_fields()
 {
     parent::fill_in_relationship_fields();
     if (!empty($this->signedcontractdocument_id)) {
         $document = new Document();
         if ($document->retrieve($this->signedcontractdocument_id)) {
             $this->signedcontractdocument = $document->document_name;
         }
     }
 }
function getRevisionBean()
{
    $document = new Document();
    // Dokument wiederfinden -> Todo: anhand der field_defs generisch suchen
    if ($_REQUEST['return_id'] != "" && $_REQUEST['return_id'] != "undefined") {
        $document_id = $_REQUEST['return_id'];
        if ($document->retrieve($document_id)) {
            return $document;
        }
    } else {
        die('Could not get document id!');
    }
}
Example #6
0
 public function testSaveAndGet_document_name()
 {
     error_reporting(E_ERROR | E_PARSE);
     $document = new Document();
     $document->filename = 'test';
     $document->file_url = 'test_url';
     $document->file_url_noimage = 'test_image_url';
     $document->last_rev_created_name = 'test';
     $document->category_id = '1';
     $document->subcategory_id = '1';
     $document->document_name = 'test';
     $document->save();
     //test for record ID to verify that record is saved
     $this->assertTrue(isset($document->id));
     $this->assertEquals(36, strlen($document->id));
     //execute Get_document_name() method and verify it gets the name correctly
     $this->assertEquals(null, $document->get_document_name(1));
     $this->assertEquals('test', $document->get_document_name($document->id));
     //mark the record as deleted and verify that this record cannot be retrieved anymore.
     $document->mark_deleted($document->id);
     $result = $document->retrieve($document->id);
     $this->assertEquals(null, $result);
 }
Example #7
0
 require_once 'modules/' . $module . '/' . $bean_name . '.php';
 $focus = new $bean_name();
 $focus->retrieve($_REQUEST['id']);
 if (!$focus->ACLAccess('view')) {
     die($mod_strings['LBL_NO_ACCESS']);
 }
 // if
 // Pull up the document revision, if it's of type Document
 if (isset($focus->object_name) && $focus->object_name == 'Document') {
     // It's a document, get the revision that really stores this file
     $focusRevision = new DocumentRevision();
     $focusRevision->retrieve($_REQUEST['id']);
     if (empty($focusRevision->id)) {
         // This wasn't a document revision id, it's probably actually a document id, we need to grab that, get the latest revision and use that
         $focusDocument = new Document();
         $focusDocument->retrieve($_REQUEST['id']);
         $focusRevision->retrieve($focusDocument->document_revision_id);
         if (!empty($focusRevision->id)) {
             $_REQUEST['id'] = $focusRevision->id;
         }
     }
 }
 // See if it is a remote file, if so, send them that direction
 if (isset($focus->doc_url) && !empty($focus->doc_url)) {
     header('Location: ' . $focus->doc_url);
     sugar_die();
 }
 if (isset($focusRevision) && isset($focusRevision->doc_url) && !empty($focusRevision->doc_url)) {
     header('Location: ' . $focusRevision->doc_url);
     sugar_die();
 }
Example #8
0
 function save($check_notify = false)
 {
     if (empty($this->doc_type)) {
         $this->doc_type = 'Sugar';
     }
     if (empty($this->id) || $this->new_with_id) {
         if (empty($this->id)) {
             $this->id = create_guid();
             $this->new_with_id = true;
         }
         if (isset($_REQUEST) && isset($_REQUEST['duplicateSave']) && $_REQUEST['duplicateSave'] == true && isset($_REQUEST['filename_old_doctype'])) {
             $this->doc_type = $_REQUEST['filename_old_doctype'];
             $isDuplicate = true;
         } else {
             $isDuplicate = false;
         }
         $Revision = new DocumentRevision();
         //save revision.
         $Revision->in_workflow = true;
         $Revision->not_use_rel_in_req = true;
         $Revision->new_rel_id = $this->id;
         $Revision->new_rel_relname = 'Documents';
         $Revision->change_log = translate('DEF_CREATE_LOG', 'Documents');
         $Revision->revision = $this->revision;
         $Revision->document_id = $this->id;
         $Revision->filename = $this->filename;
         if (isset($this->file_ext)) {
             $Revision->file_ext = $this->file_ext;
         }
         if (isset($this->file_mime_type)) {
             $Revision->file_mime_type = $this->file_mime_type;
         }
         $Revision->doc_type = $this->doc_type;
         if (isset($this->doc_id)) {
             $Revision->doc_id = $this->doc_id;
         }
         if (isset($this->doc_url)) {
             $Revision->doc_url = $this->doc_url;
         }
         $Revision->id = create_guid();
         $Revision->new_with_id = true;
         $createRevision = false;
         //Move file saved during populatefrompost to match the revision id rather than document id
         if (!empty($_FILES['filename_file'])) {
             rename("upload://{$this->id}", "upload://{$Revision->id}");
             $createRevision = true;
         } else {
             if ($isDuplicate && (empty($this->doc_type) || $this->doc_type == 'Sugar')) {
                 // Looks like we need to duplicate a file, this is tricky
                 $oldDocument = new Document();
                 $oldDocument->retrieve($_REQUEST['duplicateId']);
                 $old_name = "upload://{$oldDocument->document_revision_id}";
                 $new_name = "upload://{$Revision->id}";
                 $GLOBALS['log']->debug("Attempting to copy from {$old_name} to {$new_name}");
                 copy($old_name, $new_name);
                 $createRevision = true;
             }
         }
         // For external documents, we just need to make sure we have a doc_id
         if (!empty($this->doc_id) && $this->doc_type != 'Sugar') {
             $createRevision = true;
         }
         if ($createRevision) {
             $Revision->save();
             //update document with latest revision id
             $this->process_save_dates = false;
             //make sure that conversion does not happen again.
             $this->document_revision_id = $Revision->id;
         }
         //set relationship field values if contract_id is passed (via subpanel create)
         if (!empty($_POST['contract_id'])) {
             $save_revision['document_revision_id'] = $this->document_revision_id;
             $this->load_relationship('contracts');
             $this->contracts->add($_POST['contract_id'], $save_revision);
         }
         if (isset($_POST['load_signed_id']) and !empty($_POST['load_signed_id'])) {
             $query = "update linked_documents set deleted=1 where id='" . $_POST['load_signed_id'] . "'";
             $this->db->query($query);
         }
     }
     return parent::save($check_notify);
 }
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize;
     global $mod_strings;
     global $sugar_config;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     //process the text only flag
     if (isset($_POST['text_only']) && $_POST['text_only'] == '1') {
         $focus->text_only = 1;
     } else {
         $focus->text_only = 0;
     }
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $preProcessedImages = array();
     $emailTemplateBodyHtml = from_html($focus->body_html);
     if (strpos($emailTemplateBodyHtml, '"cache/images/')) {
         $matches = array();
         preg_match_all('#<img[^>]*[\\s]+src[^=]*=[\\s]*["\']cache/images/(.+?)["\']#si', $emailTemplateBodyHtml, $matches);
         foreach ($matches[1] as $match) {
             $filename = urldecode($match);
             $file_location = sugar_cached("images/{$filename}");
             $mime_type = pathinfo($filename, PATHINFO_EXTENSION);
             if (file_exists($file_location)) {
                 $id = create_guid();
                 $newFileLocation = "upload://{$id}";
                 if (!copy($file_location, $newFileLocation)) {
                     $GLOBALS['log']->debug("EMAIL Template could not copy attachment to {$newFileLocation}");
                 } else {
                     $secureLink = "index.php?entryPoint=download&type=Notes&id={$id}";
                     $emailTemplateBodyHtml = str_replace("cache/images/{$match}", $secureLink, $emailTemplateBodyHtml);
                     unlink($file_location);
                     $preProcessedImages[$filename] = $id;
                 }
             }
             // if
         }
         // foreach
     }
     // if
     if (isset($GLOBALS['check_notify'])) {
         $check_notify = $GLOBALS['check_notify'];
     } else {
         $check_notify = FALSE;
     }
     $focus->body_html = $emailTemplateBodyHtml;
     $return_id = $focus->save($check_notify);
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         //Images are presaved above so we need to prevent duplicate files from being created.
         if (isset($preProcessedImages[$file['name']])) {
             $oldId = $preProcessedImages[$file['name']];
             $note->id = $oldId;
             $note->new_with_id = TRUE;
             $GLOBALS['log']->debug("Image {$file['name']} has already been processed.");
         }
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id) && $note->new_with_id === FALSE) {
             if (empty($_REQUEST['old_id'])) {
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 $newNoteId = $newNote->save();
                 UploadFile::duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         if ($note->new_with_id === FALSE) {
             $note->file->final_move($note->id);
         } else {
             $GLOBALS['log']->debug("Not performing final move for note id {$note->id} as it has already been processed");
         }
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             UploadFile::duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     clear_register_value('select_array', $focus->object_name);
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/
//updates the link between contract and document with latest revision of
//the document and sends the control back to calling page.
require_once 'modules/Documents/Document.php';
require_once 'include/formbase.php';
if (!empty($_REQUEST['record'])) {
    $document = new Document();
    $document->retrieve($_REQUEST['record']);
    if (!empty($document->document_revision_id) && !empty($_REQUEST['get_latest_for_id'])) {
        $query = "update linked_documents set document_revision_id='{$document->document_revision_id}', date_modified='" . gmdate("Y-m-d H:i:s") . "' where id ='{$_REQUEST['get_latest_for_id']}' ";
        $document->db->query($query);
    }
}
handleRedirect();
Example #11
0
 ********************************************************************************/
global $mod_strings;
if (!isset($_REQUEST['record'])) {
    sugar_die($mod_strings['ERR_DELETE_RECORD']);
}
$focus = new Document();
$focus->retrieve($_REQUEST['record']);
if (!$focus->ACLAccess('Delete')) {
    ACLController::displayNoAccess(true);
    sugar_cleanup(true);
}
if (isset($_REQUEST['object']) && ($_REQUEST['object'] = "documentrevision")) {
    //delete document revision.
    $focus = new DocumentRevision();
    UploadFile::unlink_file($_REQUEST['revision_id'], $_REQUEST['filename']);
} else {
    //delete document and its revisions.
    $focus = new Document();
    $focus->retrieve($_REQUEST['record']);
    $focus->load_relationships('revisions');
    $revisions = $focus->get_linked_beans('revisions', 'DocumentRevision');
    if (!empty($revisions) && is_array($revisions)) {
        foreach ($revisions as $key => $thisversion) {
            UploadFile::unlink_file($thisversion->id, $thisversion->filename);
            //mark the version deleted.
            $thisversion->mark_deleted($thisversion->id);
        }
    }
}
$focus->mark_deleted($_REQUEST['record']);
header("Location: index.php?module=" . $_REQUEST['return_module'] . "&action=" . $_REQUEST['return_action'] . "&record=" . $_REQUEST['return_id']);
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'modules/EmailTemplates/EmailTemplate.php';
     require_once 'modules/Documents/Document.php';
     require_once 'modules/DocumentRevisions/DocumentRevision.php';
     require_once 'modules/Notes/Note.php';
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize, $upload_dir;
     global $mod_strings;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $return_id = $focus->save();
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = 10;
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     for ($i = 0; $i < $max_files_upload; $i++) {
         $note = new Note();
         $upload_file = new UploadFile('email_attachment' . $i);
         if ($upload_file == -1) {
             continue;
         }
         if (isset($_FILES['email_attachment' . $i]) && $upload_file->confirm_upload()) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id)) {
             if (empty($_REQUEST['old_id'])) {
                 // to support duplication of email templates
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNoteId = $newNote->save();
                 $dupeFile = new UploadFile('duplicate');
                 $dupeFile->duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     for ($i = 0; $i < 10; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
 private function getProductCatalogVariables($productCatalog)
 {
     $rootCategoriesSmarty = $this->getSmartyCategories($productCatalog->getAllCategories());
     $this->insertProducts($rootCategoriesSmarty);
     $description = htmlToLatex(from_html($productCatalog->description));
     //1.7.6 TODO create error handling here
     if ($description == null) {
         $GLOBALS['log']->error('OQC: Product catalog description is null!');
         //return null;
     }
     global $timedate;
     $validfrom = $timedate->to_display_date($productCatalog->validfrom);
     $validto = $timedate->to_display_date($productCatalog->validto);
     $frontpage = null;
     $attachment = null;
     if ($productCatalog->frontpage_id != null || $productCatalog->attachment_id != null) {
         $doc = new Document();
         if ($doc->retrieve($productCatalog->frontpage_id)) {
             $frontpage = str_replace("\\", '/', TMP_DIR . DIRECTORY_SEPARATOR . $doc->document_revision_id . '.pdf');
             copy(getcwd() . DIRECTORY_SEPARATOR . getDocumentFilename($doc->document_revision_id), $frontpage);
         }
         if ($doc->retrieve($productCatalog->attachment_id)) {
             $attachment = str_replace("\\", '/', TMP_DIR . DIRECTORY_SEPARATOR . $doc->document_revision_id . '.pdf');
             copy(getcwd() . DIRECTORY_SEPARATOR . getDocumentFilename($doc->document_revision_id), $attachment);
         }
     }
     //ProductCatalog currency setup
     $currencyArray = array();
     $currency = new Currency();
     $currency_id = $currency->retrieve_id_by_name($productCatalog->currency_id);
     //$GLOBALS['log']->error('Contract variables: currency: '. var_export($currency_id,true));
     if ($currency_id) {
         $currency->retrieve($currency_id);
         $currencyArray['currency_id'] = $currency->iso4217;
         $currencyArray['currency_symbol'] = $currency->symbol;
         $currencyArray['currency_ratio'] = $currency->conversion_rate;
     } else {
         $currencyArray['currency_id'] = $currency->getDefaultISO4217();
         $currencyArray['currency_symbol'] = $currency->getDefaultCurrencySymbol();
         $currencyArray['currency_ratio'] = 1.0;
     }
     $currencyArray['currency_symbol'] = str_replace("€", '\\euro{}', $currencyArray['currency_symbol']);
     $currencyArray['currency_symbol'] = str_replace('$', '\\$', $currencyArray['currency_symbol']);
     $currencyArray['currency_symbol'] = str_replace("£", '{\\pounds}', $currencyArray['currency_symbol']);
     $currencyArray['currency_symbol'] = str_replace("¥", '{Y\\hspace*{-1.4ex}--}', $currencyArray['currency_symbol']);
     $productCatalogVariables = array('name' => $productCatalog->name, 'validfrom' => $validfrom, 'validto' => $validto, 'graphicsDir' => LATEX_GRAPHICS_DIR, 'categoriesAndProducts' => $rootCategoriesSmarty, 'description' => $description, 'frontpage' => $frontpage, 'attachment' => $attachment, 'year' => date('Y'), 'currency' => $currencyArray, 'discount' => 1.0 - $productCatalog->oqc_catalog_discount / 100);
     //$GLOBALS['log']->error('Product Catalog variables: '. var_export($productCatalogVariables,true));
     return $productCatalogVariables;
 }
 private function saveAttachedDocuments()
 {
     //	$documents = 'documents';
     //	$this->bean->load_relationship($documents);
     $sequence = array();
     if (isset($_POST["document_status"]) && !empty($_POST["document_status"])) {
         for ($i = 0; $i < count($_POST["document_status"]); $i++) {
             $document_id = $_POST['document_ids'][$i];
             if ($_POST["document_status"][$i] == 'delete') {
                 $revision = new DocumentRevision();
                 if ($revision->retrieve($_POST['document_ids'][$i])) {
                     $document_id = $revision->document_id;
                 }
                 $document = new Document();
                 $document->retrieve($document_id);
                 $changes = array('field_name' => $document->document_name, 'data_type' => 'varchar', 'before' => $document->filename, 'after' => '<deleted>');
                 global $sugar_version;
                 if (floatval(substr($sugar_version, 0, 3)) > 6.3) {
                     $this->bean->db->save_audit_records($this->bean, $changes);
                 } else {
                     $this->bean->dbManager->helper->save_audit_records($this->bean, $changes);
                 }
             } else {
                 $revision = new DocumentRevision();
                 if ($revision->retrieve($_POST['document_ids'][$i])) {
                     $document_id = $revision->document_id;
                 }
                 //		$this->bean->$documents->add($document_id); //2.1 We do not add documents here; only pdf files should be added
                 $document = new Document();
                 $document->retrieve($document_id);
                 if ($_POST["document_status"][$i] == 'new') {
                     $changes = array('field_name' => $document->document_name, 'data_type' => 'varchar', 'before' => '<n/a>', 'after' => $document->filename);
                     global $sugar_version;
                     if (floatval(substr($sugar_version, 0, 3)) > 6.3) {
                         $this->bean->db->save_audit_records($this->bean, $changes);
                     } else {
                         $this->bean->dbManager->helper->save_audit_records($this->bean, $changes);
                     }
                 }
                 $sequence[] = $_POST['document_ids'][$i];
             }
         }
     }
     $this->bean->attachmentsequence = implode(' ', $sequence);
 }
Example #15
0
 /**
  * handles attachments of various kinds when sending email
  */
 function handleAttachments()
 {
     global $mod_strings;
     ///////////////////////////////////////////////////////////////////////////
     ////    ATTACHMENTS FROM DRAFTS
     if (($this->type == 'out' || $this->type == 'draft') && $this->status == 'draft' && isset($_REQUEST['record'])) {
         $this->getNotes($_REQUEST['record']);
         // cn: get notes from OLD email for use in new email
     }
     ////    END ATTACHMENTS FROM DRAFTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////    ATTACHMENTS FROM FORWARDS
     // Bug 8034 Jenny - Need the check for type 'draft' here to handle cases where we want to save
     // forwarded messages as drafts.  We still need to save the original message's attachments.
     if (($this->type == 'out' || $this->type == 'draft') && isset($_REQUEST['origType']) && $_REQUEST['origType'] == 'forward' && isset($_REQUEST['return_id']) && !empty($_REQUEST['return_id'])) {
         $this->getNotes($_REQUEST['return_id'], true);
     }
     // cn: bug 8034 - attachments from forward/replies lost when saving in draft
     if (isset($_REQUEST['prior_attachments']) && !empty($_REQUEST['prior_attachments']) && $this->new_with_id == true) {
         $exIds = explode(",", $_REQUEST['prior_attachments']);
         if (!isset($_REQUEST['template_attachment'])) {
             $_REQUEST['template_attachment'] = array();
         }
         $_REQUEST['template_attachment'] = array_merge($_REQUEST['template_attachment'], $exIds);
     }
     ////    END ATTACHMENTS FROM FORWARDS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM TEMPLATES
     // to preserve individual email integrity, we must dupe Notes and associated files
     // for each outbound email - good for integrity, bad for filespace
     if (isset($_REQUEST['template_attachment']) && !empty($_REQUEST['template_attachment'])) {
         $removeArr = array();
         $noteArray = array();
         if (isset($_REQUEST['temp_remove_attachment']) && !empty($_REQUEST['temp_remove_attachment'])) {
             $removeArr = $_REQUEST['temp_remove_attachment'];
         }
         foreach ($_REQUEST['template_attachment'] as $noteId) {
             if (in_array($noteId, $removeArr)) {
                 continue;
             }
             $noteTemplate = new Note();
             $noteTemplate->retrieve($noteId);
             $noteTemplate->id = create_guid();
             $noteTemplate->new_with_id = true;
             // duplicating the note with files
             $noteTemplate->parent_id = $this->id;
             $noteTemplate->parent_type = $this->module_dir;
             $noteTemplate->date_entered = '';
             $noteTemplate->save();
             $noteFile = new UploadFile('none');
             $noteFile->duplicate_file($noteId, $noteTemplate->id, $noteTemplate->filename);
             $noteArray[] = $noteTemplate;
         }
         $this->attachments = array_merge($this->attachments, $noteArray);
     }
     ////	END ATTACHMENTS FROM TEMPLATES
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = 10;
     // Jenny - Bug 8211 Since attachments for drafts have already been processed,
     // we don't need to re-process them.
     if ($this->status != "draft") {
         $notes_list = array();
         if (!empty($this->id) && !$this->new_with_id) {
             $note = new Note();
             $where = "notes.parent_id='{$this->id}'";
             $notes_list = $note->get_full_list("", $where, true);
         }
         $this->attachments = array_merge($this->attachments, $notes_list);
     }
     // cn: Bug 5995 - rudimentary error checking
     $filesError = array(0 => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.', 1 => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.', 2 => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.', 3 => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.', 4 => 'UPLOAD_ERR_NO_FILE - No file was uploaded.', 5 => 'UNKNOWN ERROR', 6 => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.', 7 => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk. Introduced in PHP 5.1.0.');
     for ($i = 0; $i < $max_files_upload; $i++) {
         // cn: Bug 5995 - rudimentary error checking
         if (!isset($_FILES["email_attachment{$i}"])) {
             $GLOBALS['log']->debug("Email Attachment {$i} does not exist.");
             continue;
         }
         if ($_FILES['email_attachment' . $i]['error'] != 0 && $_FILES['email_attachment' . $i]['error'] != 4) {
             $GLOBALS['log']->debug('Email Attachment could not be attach due to error: ' . $filesError[$_FILES['email_attachment' . $i]['error']]);
             continue;
         }
         $note = new Note();
         $note->parent_id = $this->id;
         $note->parent_type = $this->module_dir;
         $upload_file = new UploadFile('email_attachment' . $i);
         if (empty($upload_file)) {
             continue;
         }
         if (isset($_FILES['email_attachment' . $i]) && $upload_file->confirm_upload()) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             $this->attachments[] = $note;
         }
     }
     $this->saved_attachments = array();
     foreach ($this->attachments as $note) {
         if (!empty($note->id)) {
             array_push($this->saved_attachments, $note);
             continue;
         }
         $note->parent_id = $this->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         $this->saved_attachments[] = $note;
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     for ($i = 0; $i < 10; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             $this->saved_attachments[] = $docRev;
             // cn: bug 9723 - Emails with documents send GUID instead of Doc name
             $docNote->name = $docRev->getDocumentRevisionNameForDisplay();
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $this->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $this->db->query($q);
         }
     }
     //this will remove attachments that have been selected to be removed from drafts.
     if (isset($_REQUEST['removeAttachment']) && !empty($_REQUEST['removeAttachment'])) {
         $exRemoved = explode('::', $_REQUEST['removeAttachment']);
         foreach ($exRemoved as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $this->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
 }
Example #16
0
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/
require_once 'modules/Documents/Document.php';
require_once 'modules/DocumentRevisions/DocumentRevision.php';
require_once 'include/formbase.php';
require_once 'include/upload_file.php';
global $mod_strings;
$mod_strings = return_module_language($current_language, 'DocumentRevisions');
$prefix = '';
$do_final_move = 0;
$Revision = new DocumentRevision();
$Document = new Document();
if (isset($_REQUEST['record'])) {
    $Document->retrieve($_REQUEST['record']);
}
if (!$Document->ACLAccess('Save')) {
    ACLController::displayNoAccess(true);
    sugar_cleanup(true);
}
if (isset($_REQUEST['SaveRevision'])) {
    //fetch the document record.
    $Document->retrieve($_REQUEST['return_id']);
    if ($useRequired && !checkRequired($prefix, array_keys($Revision->required_fields))) {
        return null;
    }
    $Revision = populateFromPost($prefix, $Revision);
    $upload_file = new UploadFile('uploadfile');
    if (isset($_FILES['uploadfile']) && $upload_file->confirm_upload()) {
        $Revision->filename = $upload_file->get_stored_file_name();
    curl_close($ch);
    fclose($fp);
    if ($error) {
        echo "<br>Error sending file.<br>error = " . $error;
        throw new Exception('Error posting create viewing session request to ACS proxy.');
    }
    if ($code != 200) {
        echo "<br>Error sending file.<br>Return Code = " . $code;
        throw new Exception('Error posting create viewing session request to ACS proxy.');
    }
    return $response;
}
echo "<br>One moment please while your document is being prepared...";
$file_id = $_GET["id"];
$doc = new Document();
$doc->retrieve($file_id);
$upload_location = "upload://{$doc->document_revision_id}";
if (strlen($upload_location) < 36) {
    $upload_location .= $file_id;
}
$file_contents = file_get_contents($upload_location);
$file_size = mb_strlen($file_contents, 'latin1');
$resp = json_decode(createViewingSession());
$viewing_session = $resp->viewingSessionId;
putDocument($viewing_session, $file_size, $upload_location);
echo '<script type="text/javascript" language="javascript">
		window.location.href = "' . VIEWER_URL . '/?key=' . ACS_API_KEY . '&viewingSessionId=' . $viewing_session . '&logoimage=&viewertype=html5&viewerwidth=' . VIEWER_WIDTH . '&viewerheight=' . VIEWER_HEIGHT . '&upperToolbarColor=' . UPPER_TOOLBAR_COLOR . '&lowerToolbarColor=' . LOWER_TOOLBAR_COLOR . '&bottomToolbarColor=' . BOTTOM_TOOLBAR_COLOR . '&backgroundColor=' . BACKGROUND_COLOR . '&fontColor=' . FONT_COLOR . '&buttonColor=' . BUTTON_COLOR . '";
	</script>';
?>

<?php

if (!defined('sugarEntry') || !sugarEntry) {
    die("Not A Valid Entry Point");
}
$id = $_REQUEST['record'];
$document = new Document();
$document->retrieve($id);
$filename = $document->document_revision_id;
$filepath = "upload/{$filename}";
$document_name = $document->get_document_name($id);
// File típusának ellenőrzése
$image_formats = array('JPEG', 'GIF', 'PNG');
$finfo = new finfo();
$fileinfo = $finfo->file($filepath);
$fileinfo_array = explode(" ", $fileinfo);
if ($fileinfo_array[0] == 'PDF') {
    $im = new imagick($filepath . "[0]");
    $im->setImageFormat('png');
    $im->thumbnailImage(300, 0);
    header('Content-Type:image/png');
    ob_clean();
    flush();
    echo $im;
} elseif (!in_array($fileinfo_array[0], $image_formats)) {
    header('Content-Type:image/png');
    ob_clean();
    flush();
    readfile('custom/themes/default/images/unknown.png');
} else {
    //Kép Átméretezése
 public function handleAttachments($focus, $redirect, $return_id)
 {
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     global $mod_strings;
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . htmlspecialchars($_REQUEST['old_id'], ENT_QUOTES) . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         //Images are presaved above so we need to prevent duplicate files from being created.
         if (isset($preProcessedImages[$file['name']])) {
             $oldId = $preProcessedImages[$file['name']];
             $note->id = $oldId;
             $note->new_with_id = TRUE;
             $GLOBALS['log']->debug("Image {$file['name']} has already been processed.");
         }
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id) && $note->new_with_id === FALSE) {
             if (empty($_REQUEST['old_id'])) {
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 /* BEGIN - SECURITY GROUPS */
                 //Need to do this so that attachments show under an EmailTemplate correctly for a normal user
                 global $current_user;
                 $newNote->assigned_user_id = $current_user->id;
                 /* END - SECURITY GROUPS */
                 $newNoteId = $newNote->save();
                 UploadFile::duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         /* BEGIN - SECURITY GROUPS */
         //Need to do this so that attachments show under an EmailTemplate correctly for a normal user
         global $current_user;
         $note->assigned_user_id = $current_user->id;
         /* END - SECURITY GROUPS */
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         if ($note->new_with_id === FALSE) {
             $note->file->final_move($note->id);
         } else {
             $GLOBALS['log']->debug("Not performing final move for note id {$note->id} as it has already been processed");
         }
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             UploadFile::duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     clear_register_value('select_array', $focus->object_name);
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }
 function getTechnicalDescriptions()
 {
     $attachmentIds = explode(' ', trim($this->attachmentsequence));
     $attachments = array();
     foreach ($attachmentIds as $id) {
         $attachment_data = array();
         $revision = new DocumentRevision();
         if (!$revision->retrieve($id)) {
             $attachment = new Document();
             if ($attachment->retrieve($id)) {
                 if ($attachment->subcategory_id == 'Technical') {
                     //$attachment_data = array();
                     $attachment_data["id"] = $attachment->id;
                     $attachment_data["document_name"] = $attachment->document_name;
                     $attachment_data["document_revision_id"] = $attachment->document_revision_id;
                     //				$attachment_data["doc_status"] = 'new';
                     $attachments[] = $attachment_data;
                 }
             }
         } else {
             $attachment = new Document();
             if ($attachment->retrieve($revision->document_id)) {
                 if ($attachment->subcategory_id == 'Technical') {
                     //$attachment_data = array();
                     $attachment_data["id"] = $attachment->id;
                     $attachment_data["document_name"] = $attachment->document_name . '_rev.' . $revision->revision;
                     $attachment_data["document_revision_id"] = $revision->id;
                     //				$attachment_data["doc_status"] = 'new';
                     $attachments[] = $attachment_data;
                 }
             }
         }
     }
     return $attachments;
 }
 function fill_in_relationship_fields()
 {
     /*
      * work around a SugarCRM bug. Document relate fields dont work,
      * because Documents have no name attribute.
      */
     parent::fill_in_relationship_fields();
     if (!empty($this->frontpage_id)) {
         $document = new Document();
         if ($document->retrieve($this->frontpage_id)) {
             $this->frontpage = $document->document_name;
         }
     }
     if (!empty($this->attachment_id)) {
         $document = new Document();
         if ($document->retrieve($this->attachment_id)) {
             $this->attachment = $document->document_name;
         }
     }
 }
function createAttachedDocumentsPdf($product)
{
    $attachedDocuments = $product->get_all_linked_attachments();
    //	trigger_error("Started to convert products to PDF!", E_USER_NOTICE);
    if (empty($attachedDocuments)) {
        return null;
    }
    $docHandler = null;
    $catArgs = array();
    $filenameArgs = array();
    $filenames = array();
    $attachArgs = array();
    $ids = range('A', chr(ord('A') + count($attachedDocuments) - 1));
    foreach ($attachedDocuments as $attachment_id) {
        $revision_id = $attachment_id;
        $revision_check = new DocumentRevision();
        if (!$revision_check->retrieve($attachment_id)) {
            $document = new Document();
            if ($document->retrieve($attachment_id)) {
                $revision_id = $document->document_revision_id;
                $purpose = $document->document_purpose_c;
            }
        } else {
            $document = new Document();
            if ($document->retrieve($revision_check->document_id)) {
                $purpose = $document->document_purpose_c;
            }
        }
        if ($purpose == 'Catalog') {
            //1.7.6 include only documents marked For Product Catalog
            $revision = new DocumentRevision();
            if ($revision->retrieve($revision_id)) {
                if ($revision->file_ext != 'pdf') {
                    //SugarCE determines file type unreliably, so only extension is used
                    if (!$docHandler) {
                        $docHandler = new DocumentHandler();
                    }
                    $filename = getDocumentFilename($revision_id);
                    // skuria failo varda su nuoroda
                    // we need a descriptive filename for word macros and pdf attachments
                    $realFilenameWithExtension = getRealFilename($revision);
                    copy($filename, $realFilenameWithExtension);
                    $filenames[] = $realFilenameWithExtension;
                    $attachmentFilename = $docHandler->convertToPdf($realFilenameWithExtension);
                    if ($attachmentFilename) {
                        $catArgs[] = current($ids);
                        $filenameArgs[] = current($ids) . '=' . $attachmentFilename;
                        $filenames[] = $attachmentFilename;
                        next($ids);
                    } else {
                        // file was not possible to convert
                        $attachArgs[] = $realFilenameWithExtension;
                        $GLOBALS['log']->fatal('OQC DocumentHandler: file ' . $realFilenameWithExtension . ' is not possible to convert to pdf!');
                        continue;
                    }
                } else {
                    $attachmentFilename = getDocumentFilename($revision_id);
                    $catArgs[] = current($ids);
                    $filenameArgs[] = current($ids) . '=' . $attachmentFilename;
                    next($ids);
                }
            }
        }
    }
    $testPdfFiles = implode('', $catArgs);
    //test if there are any pdf file available for pdftk
    //$GLOBALS['log']->error('OQC pdf testfiles'.$testPdfFiles);
    $testAttachFiles = implode('', $attachArgs);
    //test if there are attachement files
    if (empty($testPdfFiles)) {
        foreach ($filenames as $attachfile) {
            unlink($attachfile);
        }
        return null;
    }
    $outputFilename = tempnam(TMP_DIR, '');
    $finalFilename = tempnam(TMP_DIR, '');
    $contractFilename = tempnam(TMP_DIR, '');
    if (!empty($testPdfFiles)) {
        // merge files
        $pdfTkArgs = implode(' ', $filenameArgs) . ' cat ' . implode(' ', $catArgs) . " output {$outputFilename} keep_first_id";
        if (execute(PDFTK, $pdfTkArgs) == 0) {
            copy($outputFilename, $contractFilename);
            //owerwrite source file
        } else {
            $GLOBALS['log']->error('Failed to merge PDF files!');
            //cleanup of temporary files
            unlink($finalFilename);
            unlink($outputFilename);
            unlink($contractFilename);
            foreach ($filenames as $attachfile) {
                unlink($attachfile);
            }
            return null;
        }
    }
    if (!empty($testAttachFiles) && !empty($testPdfFiles)) {
        $pdfTkArgs = "{$contractFilename} attach_files " . implode(' ', $attachArgs) . " output {$finalFilename}";
        if (execute(PDFTK, $pdfTkArgs) == 0) {
            copy($finalFilename, $contractFilename);
        } else {
            $GLOBALS['log']->error('Failed to attach documents to final PDF!');
        }
    }
    //cleanup of temporary files
    unlink($finalFilename);
    unlink($outputFilename);
    foreach ($filenames as $attachfile) {
        unlink($attachfile);
    }
    $contractFilenamePdf = str_replace("\\", "/", dirname($contractFilename) . DIRECTORY_SEPARATOR . basename($contractFilename, '.tmp') . '.pdf');
    rename($contractFilename, $contractFilenamePdf);
    //$GLOBALS['log']->error('OQC: Attachment filename is '.$contractFilenamePdf);
    //return str_replace("\\","/",$contractFilename.'.pdf');
    return $contractFilenamePdf;
}
Example #23
0
 /**
  * Returns a filename based off of the logical (Sugar-side) Document name and combined with the revision. Tailor
  * this to needs created by email RFCs, filesystem name conventions, charset conventions etc.
  * @param string revId Revision ID if not latest
  * @return string formatted name
  */
 function getDocumentRevisionNameForDisplay($revId = '')
 {
     global $sugar_config;
     global $current_language;
     $localLabels = return_module_language($current_language, 'DocumentRevisions');
     // prep - get source Document
     $document = new Document();
     // use passed revision ID
     if (!empty($revId)) {
         $tempDoc = new DocumentRevision();
         $tempDoc->retrieve($revId);
     } else {
         $tempDoc = $this;
     }
     // get logical name
     $document->retrieve($tempDoc->document_id);
     $logicalName = $document->document_name;
     // get revision string
     $revString = '';
     if (!empty($tempDoc->revision)) {
         $revString = "-{$localLabels['LBL_REVISION']}_{$tempDoc->revision}";
     }
     // get extension
     $realFilename = $tempDoc->filename;
     $fileExtension_beg = strrpos($realFilename, ".");
     $fileExtension = "";
     if ($fileExtension_beg > 0) {
         $fileExtension = substr($realFilename, $fileExtension_beg + 1);
     }
     //check to see if this is a file with extension located in "badext"
     foreach ($sugar_config['upload_badext'] as $badExt) {
         if (strtolower($fileExtension) == strtolower($badExt)) {
             //if found, then append with .txt to filename and break out of lookup
             //this will make sure that the file goes out with right extension, but is stored
             //as a text in db.
             $fileExtension .= ".txt";
             break;
             // no need to look for more
         }
     }
     $fileExtension = "." . $fileExtension;
     $return = $logicalName . $revString . $fileExtension;
     // apply RFC limitations here
     if (mb_strlen($return) > 1024) {
         // do something if we find a real RFC issue
     }
     return $return;
 }
 function oqc_cleanup_document_revision($id)
 {
     $contract = new $this->object_name();
     if ($contract->retrieve($id)) {
         if (!empty($contract->document_id)) {
             $document = new Document();
             if ($document->retrieve($contract->document_id)) {
                 if (!empty($document->document_revision_id)) {
                     $revision = new DocumentRevision();
                     if ($revision->retrieve($document->document_revision_id)) {
                         if ($revision->revision == $contract->version) {
                             $revision->mark_deleted($revision->id);
                         }
                     }
                     $document->document_revision_id = '';
                     //$document->document_revision_id = null;
                     $document->save();
                 }
             }
         }
     }
 }
Example #25
0
if (!isset($_SESSION['MAILMERGE_MODULE'])) {
    if (isset($_POST['mailmerge_module'])) {
        $_SESSION['MAILMERGE_MODULE'] = $_POST['mailmerge_module'];
    }
}
if (isset($_POST['contains_contact_info'])) {
    $_SESSION['MAILMERGE_CONTAINS_CONTACT_INFO'] = $_POST['contains_contact_info'];
}
if (!isset($_SESSION["MAILMERGE_DOCUMENT_ID"])) {
    if (!empty($_POST['document_id'])) {
        $_SESSION['MAILMERGE_DOCUMENT_ID'] = $_POST['document_id'];
    }
}
$document_id = $_SESSION["MAILMERGE_DOCUMENT_ID"];
$document = new Document();
$document->retrieve($document_id);
$_SESSION["MAILMERGE_TEMPLATE"] = $document->document_name;
if (!empty($_POST['selected_objects'])) {
    $selObjs = urldecode($_POST['selected_objects']);
    $_SESSION['SELECTED_OBJECTS_DEF'] = $selObjs;
} else {
    $selObjs = $_SESSION['SELECTED_OBJECTS_DEF'];
}
$sel_obj = array();
parse_str(html_entity_decode($selObjs, ENT_QUOTES), $sel_obj);
$step_num = 3;
$xtpl->assign("PREV_STEP", '2');
$xtpl->assign("STEP_NUM", "Step 3:");
$popup_request_data = array('call_back_function' => 'set_return', 'form_name' => 'EditView', 'field_to_name_array' => array('id' => 'rel_id', 'name' => 'rel_name'));
$json = getJSONobj();
// must urlencode to put into the filter request string
Example #26
0
 /**
  * Sends Email for Email 2.0
  */
 function email2Send($request)
 {
     global $current_user;
     global $timedate;
     $saveAsDraft = !empty($request['saveDraft']);
     if (!$saveAsDraft && !empty($request["MAIL_RECORD_STATUS"]) && $request["MAIL_RECORD_STATUS"] == 'archived') {
         $archived = true;
         $this->type = 'archived';
     } else {
         $archived = false;
         if (!empty($request['MAIL_RECORD_STATUS']) && $request['MAIL_RECORD_STATUS'] === 'ready') {
             $this->type = 'out';
         }
     }
     /**********************************************************************
      * Sugar Email PREP
      */
     /* preset GUID */
     $orignialId = "";
     if (!empty($this->id)) {
         $orignialId = $this->id;
     }
     // if
     if (empty($this->id)) {
         $this->id = create_guid();
         $this->new_with_id = true;
     }
     /* satisfy basic HTML email requirements */
     $this->name = $request['sendSubject'];
     if (isset($_REQUEST['setEditor']) && $_REQUEST['setEditor'] == 1) {
         $_REQUEST['description_html'] = $_REQUEST['sendDescription'];
         $this->description_html = $_REQUEST['description_html'];
     } else {
         $this->description_html = '';
         $this->description = $_REQUEST['sendDescription'];
     }
     if ($this->isDraftEmail($request)) {
         if ($this->type != 'draft' && $this->status != 'draft') {
             $this->id = create_guid();
             $this->new_with_id = true;
             $this->date_entered = "";
         }
         // if
         $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'";
         $this->db->query($q1);
     }
     // if
     if ($saveAsDraft) {
         $this->type = 'draft';
         $this->status = 'draft';
     } else {
         if ($archived) {
             $this->type = 'archived';
             $this->status = 'archived';
         }
         /* Apply Email Templates */
         // do not parse email templates if the email is being saved as draft....
         $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']);
         $sea = BeanFactory::getBean('EmailAddresses');
         $object_arr = array();
         if (!empty($_REQUEST['parent_type']) && !empty($_REQUEST['parent_id']) && ($_REQUEST['parent_type'] == 'Accounts' || $_REQUEST['parent_type'] == 'Contacts' || $_REQUEST['parent_type'] == 'Leads' || $_REQUEST['parent_type'] == 'Users' || $_REQUEST['parent_type'] == 'Prospects')) {
             $bean = BeanFactory::getBean($_REQUEST['parent_type'], $_REQUEST['parent_id']);
             if (!empty($bean->id)) {
                 $object_arr[$bean->module_dir] = $bean->id;
             }
         }
         foreach ($toAddresses as $addrMeta) {
             $addr = $addrMeta['email'];
             $beans = $sea->getBeansByEmailAddress($addr);
             foreach ($beans as $bean) {
                 if (!isset($object_arr[$bean->module_dir])) {
                     $object_arr[$bean->module_dir] = $bean->id;
                 }
             }
         }
         /* template parsing */
         if (empty($object_arr)) {
             $object_arr = array('Contacts' => '123');
         }
         $object_arr['Users'] = $current_user->id;
         $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr);
         $this->name = EmailTemplate::parse_template($this->name, $object_arr);
         $this->description = EmailTemplate::parse_template($this->description, $object_arr);
         $this->description = html_entity_decode($this->description, ENT_COMPAT, 'UTF-8');
         if ($this->type != 'draft' && $this->status != 'draft' && $this->type != 'archived' && $this->status != 'archived') {
             $this->id = create_guid();
             $this->date_entered = "";
             $this->new_with_id = true;
             $this->type = 'out';
             $this->status = 'sent';
         }
     }
     if (isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id'])) {
         $this->parent_id = "";
         $this->parent_type = "";
     }
     // if
     $forceSave = false;
     $subject = $this->name;
     $textBody = from_html($this->description);
     $htmlBody = from_html($this->description_html);
     //------------------- HANDLEBODY() ---------------------------------------------
     if (isset($_REQUEST['setEditor']) && $_REQUEST['setEditor'] == 1 && trim($_REQUEST['description_html']) != '' || trim($this->description_html) != '' && $current_user->getPreference('email_editor_option', 'global') !== 'plain') {
         $textBody = strip_tags(br2nl($htmlBody));
     } else {
         // plain-text only
         $textBody = str_replace("&nbsp;", " ", $textBody);
         $textBody = str_replace("</p>", "</p><br />", $textBody);
         $textBody = strip_tags(br2nl($textBody));
         $textBody = html_entity_decode($textBody, ENT_QUOTES, 'UTF-8');
         $this->description_html = "";
         // make sure it's blank to avoid any mishaps
         $htmlBody = $this->description_html;
     }
     $textBody = $this->decodeDuringSend($textBody);
     $htmlBody = $this->decodeDuringSend($htmlBody);
     $this->description = $textBody;
     $this->description_html = $htmlBody;
     $mailConfig = null;
     try {
         if (isset($request["fromAccount"]) && !empty($request["fromAccount"])) {
             $mailConfig = OutboundEmailConfigurationPeer::getMailConfigurationFromId($current_user, $request["fromAccount"]);
         } else {
             $mailConfig = OutboundEmailConfigurationPeer::getSystemMailConfiguration($current_user);
         }
     } catch (Exception $e) {
         if (!$saveAsDraft && !$archived) {
             throw $e;
         }
     }
     if (!$saveAsDraft && !$archived && is_null($mailConfig)) {
         throw new MailerException("No Valid Mail Configurations Found", MailerException::InvalidConfiguration);
     }
     try {
         $mailer = null;
         if (!$saveAsDraft && !$archived) {
             $mailerFactoryClass = $this->MockMailerFactoryClass;
             $mailer = $mailerFactoryClass::getMailer($mailConfig);
             $mailer->setSubject($subject);
             $mailer->setHtmlBody($htmlBody);
             $mailer->setTextBody($textBody);
             $replyTo = $mailConfig->getReplyTo();
             if (!empty($replyTo)) {
                 $replyToEmail = $replyTo->getEmail();
                 if (!empty($replyToEmail)) {
                     $mailer->setHeader(EmailHeaders::ReplyTo, new EmailIdentity($replyToEmail, $replyTo->getName()));
                 }
             }
         }
         if (!is_null($mailer)) {
             // Any individual Email Address that is not valid will be logged and skipped
             // If all email addresses in the request are skipped, an error "No Recipients" is reported for the request
             foreach ($this->email2ParseAddresses($request['sendTo']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsTo(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
             foreach ($this->email2ParseAddresses($request['sendCc']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsCc(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
             foreach ($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) {
                 try {
                     $mailer->addRecipientsBcc(new EmailIdentity($addr_arr['email'], $addr_arr['display']));
                 } catch (MailerException $me) {
                     // Invalid Email Address - Log it and Skip
                     $GLOBALS["log"]->warning($me->getLogMessage());
                 }
             }
         }
         /* handle attachments */
         if (!empty($request['attachments'])) {
             $exAttachments = explode("::", $request['attachments']);
             foreach ($exAttachments as $file) {
                 $file = trim(from_html($file));
                 $file = str_replace("\\", "", $file);
                 if (!empty($file)) {
                     $fileGUID = preg_replace('/[^a-z0-9\\-]/', "", substr($file, 0, 36));
                     $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                     $filename = substr($file, 36, strlen($file));
                     // strip GUID	for PHPMailer class to name outbound file
                     // only save attachments if we're archiving or drafting
                     if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                         $note = new Note();
                         $note->id = create_guid();
                         $note->new_with_id = true;
                         // duplicating the note with files
                         $note->parent_id = $this->id;
                         $note->parent_type = $this->module_dir;
                         $note->name = $filename;
                         $note->filename = $filename;
                         $note->file_mime_type = $this->email2GetMime($fileLocation);
                         $note->team_id = isset($_REQUEST['primaryteam']) ? $_REQUEST['primaryteam'] : $current_user->getPrivateTeamID();
                         $noteTeamSet = new TeamSet();
                         $noteteamIdsArray = isset($_REQUEST['teamIds']) ? explode(",", $_REQUEST['teamIds']) : array($current_user->getPrivateTeamID());
                         $note->team_set_id = $noteTeamSet->addTeams($noteteamIdsArray);
                         $dest = "upload://{$note->id}";
                         if (!file_exists($fileLocation) || !copy($fileLocation, $dest)) {
                             $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to {$fileLocation} => {$dest}");
                         } else {
                             $note->save();
                             $validNote = true;
                         }
                     } else {
                         $note = new Note();
                         $validNote = (bool) $note->retrieve($fileGUID);
                     }
                     if (isset($validNote) && $validNote === true) {
                         $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                         if (!is_null($mailer)) {
                             $mailer->addAttachment($attachment);
                         }
                     }
                 }
             }
         }
         /* handle sugar documents */
         if (!empty($request['documents'])) {
             $exDocs = explode("::", $request['documents']);
             foreach ($exDocs as $docId) {
                 $docId = trim($docId);
                 if (!empty($docId)) {
                     $doc = new Document();
                     $doc->retrieve($docId);
                     if (empty($doc->id) || $doc->id != $docId) {
                         throw new Exception("Document Not Found: Id='" . $request['documents'] . "'");
                     }
                     $documentRevision = new DocumentRevision();
                     $documentRevision->retrieve($doc->document_revision_id);
                     //$documentRevision->x_file_name   = $documentRevision->filename;
                     //$documentRevision->x_file_path   = "upload/{$documentRevision->id}";
                     //$documentRevision->x_file_exists = (bool) file_exists($documentRevision->x_file_path);
                     //$documentRevision->x_mime_type   = $documentRevision->file_mime_type;
                     $filename = $documentRevision->filename;
                     $docGUID = preg_replace('/[^a-z0-9\\-]/', "", $documentRevision->id);
                     $fileLocation = "upload://{$docGUID}";
                     if (empty($documentRevision->id) || !file_exists($fileLocation)) {
                         throw new Exception("Document Revision Id Not Found");
                     }
                     // only save attachments if we're archiving or drafting
                     if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                         $note = new Note();
                         $note->id = create_guid();
                         $note->new_with_id = true;
                         // duplicating the note with files
                         $note->parent_id = $this->id;
                         $note->parent_type = $this->module_dir;
                         $note->name = $filename;
                         $note->filename = $filename;
                         $note->file_mime_type = $documentRevision->file_mime_type;
                         $note->team_id = $this->team_id;
                         $note->team_set_id = $this->team_set_id;
                         $dest = "upload://{$note->id}";
                         if (!file_exists($fileLocation) || !copy($fileLocation, $dest)) {
                             $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file {$fileLocation} => {$dest}");
                         }
                         $note->save();
                     }
                     $attachment = AttachmentPeer::attachmentFromSugarBean($documentRevision);
                     //print_r($attachment);
                     if (!is_null($mailer)) {
                         $mailer->addAttachment($attachment);
                     }
                 }
             }
         }
         /* handle template attachments */
         if (!empty($request['templateAttachments'])) {
             $exNotes = explode("::", $request['templateAttachments']);
             foreach ($exNotes as $noteId) {
                 $noteId = trim($noteId);
                 if (!empty($noteId)) {
                     $note = new Note();
                     $note->retrieve($noteId);
                     if (!empty($note->id)) {
                         $filename = $note->filename;
                         $noteGUID = preg_replace('/[^a-z0-9\\-]/', "", $note->id);
                         $fileLocation = "upload://{$noteGUID}";
                         $mime_type = $note->file_mime_type;
                         if (!$note->embed_flag) {
                             $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                             //print_r($attachment);
                             if (!is_null($mailer)) {
                                 $mailer->addAttachment($attachment);
                             }
                             // only save attachments if we're archiving or drafting
                             if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
                                 if ($note->parent_id != $this->id) {
                                     $this->saveTempNoteAttachments($filename, $fileLocation, $mime_type);
                                 }
                             }
                             // if
                         }
                         // if
                     } else {
                         $fileGUID = preg_replace('/[^a-z0-9\\-]/', "", substr($noteId, 0, 36));
                         $fileLocation = $this->et->userCacheDir . "/{$fileGUID}";
                         $filename = substr($noteId, 36, strlen($noteId));
                         // strip GUID	for PHPMailer class to name outbound file
                         $mimeType = $this->email2GetMime($fileLocation);
                         $note = $this->saveTempNoteAttachments($filename, $fileLocation, $mimeType);
                         $attachment = AttachmentPeer::attachmentFromSugarBean($note);
                         //print_r($attachment);
                         if (!is_null($mailer)) {
                             $mailer->addAttachment($attachment);
                         }
                     }
                 }
             }
         }
         /**********************************************************************
          * Final Touches
          */
         if ($this->type == 'draft' && !$saveAsDraft) {
             // sending a draft email
             $this->type = 'out';
             $this->status = 'sent';
             $forceSave = true;
         } elseif ($saveAsDraft) {
             $this->type = 'draft';
             $this->status = 'draft';
             $forceSave = true;
         }
         if (!is_null($mailer)) {
             $mailer->send();
         }
     } catch (MailerException $me) {
         $GLOBALS["log"]->error($me->getLogMessage());
         throw $me;
     } catch (Exception $e) {
         // eat the phpmailerException but use it's message to provide context for the failure
         $me = new MailerException("Email2Send Failed: " . $e->getMessage(), MailerException::FailedToSend);
         $GLOBALS["log"]->error($me->getLogMessage());
         $GLOBALS["log"]->info($me->getTraceMessage());
         if (!empty($mailConfig)) {
             $GLOBALS["log"]->info($mailConfig->toArray(), true);
         }
         throw $me;
     }
     if (!(empty($orignialId) || $saveAsDraft || $this->type == 'draft' && $this->status == 'draft') && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyAll' || $_REQUEST['composeType'] == 'replyCase') && $orignialId != $this->id) {
         $originalEmail = BeanFactory::getBean('Emails', $orignialId);
         $originalEmail->reply_to_status = 1;
         $originalEmail->save();
         $this->reply_to_status = 0;
     }
     // if
     if (isset($_REQUEST['composeType']) && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase')) {
         if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) {
             $emailFromIe = BeanFactory::getBean('InboundEmail', $_REQUEST['ieId'], array('disable_row_level_security' => true));
             $emailFromIe->mailbox = $_REQUEST['mbox'];
             if (isset($emailFromIe->id) && $emailFromIe->is_personal) {
                 if ($emailFromIe->isPop3Protocol()) {
                     $emailFromIe->mark_answered($this->uid, 'pop3');
                 } elseif ($emailFromIe->connectMailserver() == 'true') {
                     $emailFromIe->markEmails($this->uid, 'answered');
                     $emailFromIe->mark_answered($this->uid);
                 }
             }
         }
     }
     if ($forceSave || $this->type == 'draft' || $this->type == 'archived' || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) {
         // Set Up From Name and Address Information
         if ($this->type == 'archived') {
             $this->from_addr = empty($request['archive_from_address']) ? '' : $request['archive_from_address'];
         } elseif (!empty($mailConfig)) {
             $sender = $mailConfig->getFrom();
             $decodedFromName = mb_decode_mimeheader($sender->getName());
             $this->from_addr = "{$decodedFromName} <" . $sender->getEmail() . ">";
         } else {
             $ret = $current_user->getUsersNameAndEmail();
             if (empty($ret['email'])) {
                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
                 $ret['email'] = $systemReturn['email'];
                 $ret['name'] = $systemReturn['name'];
             }
             $decodedFromName = mb_decode_mimeheader($ret['name']);
             $this->from_addr = "{$decodedFromName} <" . $ret['email'] . ">";
         }
         $this->from_addr_name = $this->from_addr;
         $this->to_addrs = $_REQUEST['sendTo'];
         $this->to_addrs_names = $_REQUEST['sendTo'];
         $this->cc_addrs = $_REQUEST['sendCc'];
         $this->cc_addrs_names = $_REQUEST['sendCc'];
         $this->bcc_addrs = $_REQUEST['sendBcc'];
         $this->bcc_addrs_names = $_REQUEST['sendBcc'];
         $this->team_id = isset($_REQUEST['primaryteam']) ? $_REQUEST['primaryteam'] : $current_user->getPrivateTeamID();
         $teamSet = BeanFactory::getBean('TeamSets');
         $teamIdsArray = isset($_REQUEST['teamIds']) ? explode(",", $_REQUEST['teamIds']) : array($current_user->getPrivateTeamID());
         $this->team_set_id = $teamSet->addTeams($teamIdsArray);
         $this->assigned_user_id = $current_user->id;
         $this->date_sent = $timedate->now();
         ///////////////////////////////////////////////////////////////////
         ////	LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
         if (!empty($_REQUEST['parent_type']) && !empty($_REQUEST['parent_id'])) {
             $this->parent_id = $this->db->quote($_REQUEST['parent_id']);
             $this->parent_type = $this->db->quote($_REQUEST['parent_type']);
             $a = $this->db->fetchOne("SELECT count(*) c FROM emails_beans WHERE  email_id = '{$this->id}' AND bean_id = '{$this->parent_id}' AND bean_module = '{$this->parent_type}'");
             if ($a['c'] == 0) {
                 $bean = BeanFactory::getBean($_REQUEST['parent_type'], $_REQUEST['parent_id']);
                 if (!empty($bean)) {
                     if (!empty($bean->field_defs['emails']['type']) && $bean->field_defs['emails']['type'] == 'link') {
                         $email_link = "emails";
                     } else {
                         $email_link = $this->findEmailsLink($bean);
                     }
                     if ($email_link && $bean->load_relationship($email_link)) {
                         $bean->{$email_link}->add($this);
                     }
                 }
             }
             // if
         } else {
             $c = BeanFactory::getBean('Cases');
             if ($caseId = InboundEmail::getCaseIdFromCaseNumber($subject, $c)) {
                 $c->retrieve($caseId);
                 $c->load_relationship('emails');
                 $c->emails->add($this->id);
                 $this->parent_type = "Cases";
                 $this->parent_id = $caseId;
             }
             // if
         }
         // else
         ////	LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY
         ///////////////////////////////////////////////////////////////////
         $this->save();
     }
     /**** --------------------------------- ?????????
     		if(!empty($request['fromAccount'])) {
                 $ie = new InboundEmail();
                 $ie->retrieve($request['fromAccount']);
     			if (isset($ie->id) && !$ie->isPop3Protocol() && $mail->oe->mail_smtptype != 'gmail') {
     				$sentFolder = $ie->get_stored_options("sentFolder");
     				if (!empty($sentFolder)) {
     					$data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n";
     					$ie->mailbox = $sentFolder;
     					if ($ie->connectMailserver() == 'true') {
     						$connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox);
     						$returnData = imap_append($ie->conn,$connectString, $data, "\\Seen");
     						if (!$returnData) {
     							$GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}");
     						} // if
     					} else {
     						$GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}");
     					} // else
     				} else {
     					$GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty");
     				} // else
     			} // if
     		} // if
             ------------------------------------- ****/
     return true;
 }
 function fill_in_relationship_fields()
 {
     /*
      * work around a SugarCRM bug. Document relate fields dont work,
      * because Documents have no name attribute.
      */
     parent::fill_in_relationship_fields();
     // TODO this has been fixed in 5.2.0k (?) has it??
     if (array_key_exists('action', $_REQUEST) && $_REQUEST['action'] == 'DetailView') {
         // Do this only in detailview
         $document_id_names = array('contract_id', 'quote_id', 'service_description_id', 'specialproperties_id', 'installation_hw_agreement_id', 'installation_sw_agreement_id', 'phone_support_id', 'assistance_id');
         foreach ($document_id_names as $document_id_name) {
             if (!empty($this->{$document_id_name})) {
                 $document = new Document();
                 if ($document->retrieve($this->{$document_id_name})) {
                     $document_name = substr($document_id_name, 0, -3);
                     $this->{$document_name} = $document->document_name;
                 }
             }
         }
     }
 }
 function handleSave($prefix, $redirect = true, $useRequired = false)
 {
     require_once 'include/formbase.php';
     require_once 'include/upload_file.php';
     global $upload_maxsize, $upload_dir;
     global $mod_strings;
     global $sugar_config;
     $focus = new EmailTemplate();
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $focus = populateFromPost($prefix, $focus);
     //process the text only flag
     if (isset($_POST['text_only']) && $_POST['text_only'] == '1') {
         $focus->text_only = 1;
     } else {
         $focus->text_only = 0;
     }
     if (!$focus->ACLAccess('Save')) {
         ACLController::displayNoAccess(true);
         sugar_cleanup(true);
     }
     if (!isset($_REQUEST['published'])) {
         $focus->published = 'off';
     }
     $emailTemplateBodyHtml = from_html($focus->body_html);
     $fileBasePath = "{$sugar_config['cache_dir']}images/";
     $filePatternSearch = "{$sugar_config['cache_dir']}";
     $filePatternSearch = str_replace("/", "\\/", $filePatternSearch);
     $filePatternSearch = $filePatternSearch . "images\\/";
     $fileBasePath1 = "\"" . $fileBasePath;
     if (strpos($emailTemplateBodyHtml, "\"{$fileBasePath}")) {
         $matches = array();
         preg_match_all("/{$filePatternSearch}.+?\"/i", $emailTemplateBodyHtml, $matches);
         foreach ($matches[0] as $match) {
             $filenameUndecoded = str_replace($fileBasePath, '', $match);
             $filename = urldecode(substr($filenameUndecoded, 0, -1));
             $filenameUndecoded = str_replace("\"", '', $filenameUndecoded);
             $cid = $filename;
             $file_location = clean_path(getcwd() . "/{$sugar_config['cache_dir']}images/{$filename}");
             $mime_type = strtolower(substr($filename, strrpos($filename, ".") + 1, strlen($filename)));
             if (file_exists($file_location)) {
                 $id = create_guid();
                 $newFileLocation = "{$sugar_config['upload_dir']}{$id}.{$mime_type}";
                 if (!copy($file_location, $newFileLocation)) {
                     $GLOBALS['log']->debug("EMAIL Template could not copy attachment to {$sugar_config['upload_dir']} [ {$newFileLocation} ]");
                 } else {
                     $emailTemplateBodyHtml = str_replace("{$sugar_config['cache_dir']}images/{$filenameUndecoded}", $newFileLocation, $emailTemplateBodyHtml);
                     unlink($file_location);
                 }
             }
             // if
         }
         // foreach
     }
     // if
     $focus->body_html = $emailTemplateBodyHtml;
     $return_id = $focus->save();
     ///////////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////
     ////	ADDING NEW ATTACHMENTS
     $max_files_upload = count($_FILES);
     if (!empty($focus->id)) {
         $note = new Note();
         $where = "notes.parent_id='{$focus->id}'";
         if (!empty($_REQUEST['old_id'])) {
             // to support duplication of email templates
             $where .= " OR notes.parent_id='" . $_REQUEST['old_id'] . "'";
         }
         $notes_list = $note->get_full_list("", $where, true);
     }
     if (!isset($notes_list)) {
         $notes_list = array();
     }
     if (!is_array($focus->attachments)) {
         // PHP5 does not auto-create arrays(). Need to initialize it here.
         $focus->attachments = array();
     }
     $focus->attachments = array_merge($focus->attachments, $notes_list);
     //for($i = 0; $i < $max_files_upload; $i++) {
     foreach ($_FILES as $key => $file) {
         $note = new Note();
         $i = preg_replace("/email_attachment(.+)/", '$1', $key);
         $upload_file = new UploadFile($key);
         if ($upload_file == -1) {
             continue;
         }
         if (isset($_FILES[$key]) && $upload_file->confirm_upload() && preg_match("/^email_attachment/", $key)) {
             $note->filename = $upload_file->get_stored_file_name();
             $note->file = $upload_file;
             $note->name = $mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ' . $note->file->original_file_name;
             if (isset($_REQUEST['embedded' . $i]) && !empty($_REQUEST['embedded' . $i])) {
                 if ($_REQUEST['embedded' . $i] == 'true') {
                     $note->embed_flag = true;
                 } else {
                     $note->embed_flag = false;
                 }
             }
             array_push($focus->attachments, $note);
         }
     }
     $focus->saved_attachments = array();
     foreach ($focus->attachments as $note) {
         if (!empty($note->id)) {
             if (empty($_REQUEST['old_id'])) {
                 // to support duplication of email templates
                 array_push($focus->saved_attachments, $note);
             } else {
                 // we're duplicating a template with attachments
                 // dupe the file, create a new note, assign the note to the new template
                 $newNote = new Note();
                 $newNote->retrieve($note->id);
                 $newNote->id = create_guid();
                 $newNote->parent_id = $focus->id;
                 $newNote->new_with_id = true;
                 $newNote->date_modified = '';
                 $newNote->date_entered = '';
                 $newNoteId = $newNote->save();
                 $dupeFile = new UploadFile('duplicate');
                 $dupeFile->duplicate_file($note->id, $newNoteId, $note->filename);
             }
             continue;
         }
         $note->parent_id = $focus->id;
         $note->parent_type = 'Emails';
         $note->file_mime_type = $note->file->mime_type;
         $note_id = $note->save();
         array_push($focus->saved_attachments, $note);
         $note->id = $note_id;
         $note->file->final_move($note->id);
     }
     ////	END NEW ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS FROM DOCUMENTS
     $count = '';
     //_pp($_REQUEST);
     //_ppd(count($_REQUEST['document']));
     if (!empty($_REQUEST['document'])) {
         $count = count($_REQUEST['document']);
     } else {
         $count = 10;
     }
     for ($i = 0; $i < $count; $i++) {
         if (isset($_REQUEST['documentId' . $i]) && !empty($_REQUEST['documentId' . $i])) {
             $doc = new Document();
             $docRev = new DocumentRevision();
             $docNote = new Note();
             $noteFile = new UploadFile('none');
             $doc->retrieve($_REQUEST['documentId' . $i]);
             $docRev->retrieve($doc->document_revision_id);
             array_push($focus->saved_attachments, $docRev);
             $docNote->name = $doc->document_name;
             $docNote->filename = $docRev->filename;
             $docNote->description = $doc->description;
             $docNote->parent_id = $focus->id;
             $docNote->parent_type = 'Emails';
             $docNote->file_mime_type = $docRev->file_mime_type;
             $docId = $docNote = $docNote->save();
             $noteFile->duplicate_file($docRev->id, $docId, $docRev->filename);
         }
     }
     ////	END ATTACHMENTS FROM DOCUMENTS
     ///////////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////////
     ////	REMOVE ATTACHMENTS
     if (isset($_REQUEST['remove_attachment']) && !empty($_REQUEST['remove_attachment'])) {
         foreach ($_REQUEST['remove_attachment'] as $noteId) {
             $q = 'UPDATE notes SET deleted = 1 WHERE id = \'' . $noteId . '\'';
             $focus->db->query($q);
         }
     }
     ////	END REMOVE ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////////
     ////	END ATTACHMENT HANDLING
     ///////////////////////////////////////////////////////////////////////////////
     if ($redirect) {
         $GLOBALS['log']->debug("Saved record with id of " . $return_id);
         handleRedirect($return_id, "EmailTemplates");
     } else {
         return $focus;
     }
 }