/** * This function will take any file and make it permanently * available as a CiviCRM File entity. * * @param path where to find the file * @param contact_id which contact to connect to * * @param mimetype the document's MIME type. Autodetect if null * * @return an array containing the created file object, including a generated url */ public static function createPermanentFile($path, $name = null, $contact_id, $mimetype = null, $description = '') { $config = CRM_Core_Config::singleton(); if (!file_exists($path)) { return null; } // TODO: check if a file object already exists? // move file to a permanent folder $newPath = $config->customFileUploadDir . basename($path); copy($path, $newPath); // find mime type if (empty($mimetype)) { $mimetype = mime_content_type($newPath); } // create the file object if (empty($description)) { $description = $name; } $file = civicrm_api('File', 'create', array('version' => 3, 'uri' => basename($newPath), 'mime_type' => $mimetype, 'description' => $description)); if (!empty($file['is_error'])) { CRM_Core_Error::debug_log_message("de.systopia.donrec: couldn't create file object - " . $file['error_message']); return null; } if ($contact_id) { // link the file to a contact (there is no API call for this...) $entityFile = new CRM_Core_DAO_EntityFile(); $entityFile->file_id = $file['id']; $entityFile->entity_id = $contact_id; $entityFile->entity_table = 'civicrm_contact'; $entityFile->save(); } // build reply $reply = $file['values']; $reply['url'] = CRM_Utils_System::url("civicrm/file", "reset=1&id=" . $file['id'] . "&eid={$contact_id}"); $reply['path'] = $newPath; return $reply; }
static function copyEntityFile($oldEntityTable, $oldEntityId, $newEntityTable, $newEntityId) { $oldEntityFile = new CRM_Core_DAO_EntityFile(); $oldEntityFile->entity_id = $oldEntityId; $oldEntityFile->entity_table = $oldEntityTable; $oldEntityFile->find(); while ($oldEntityFile->fetch()) { $newEntityFile = new CRM_Core_DAO_EntityFile(); $newEntityFile->entity_id = $newEntityId; $newEntityFile->entity_table = $newEntityTable; $newEntityFile->file_id = $oldEntityFile->file_id; $newEntityFile->save(); } }
/** * @param array $customParams * * @throws Exception */ public static function create(&$customParams) { if (empty($customParams) || !is_array($customParams)) { return; } foreach ($customParams as $tableName => $tables) { foreach ($tables as $index => $fields) { $sqlOP = NULL; $hookID = NULL; $hookOP = NULL; $entityID = NULL; $isMultiple = FALSE; $set = array(); $params = array(); $count = 1; foreach ($fields as $field) { if (!$sqlOP) { $entityID = $field['entity_id']; $hookID = $field['custom_group_id']; $isMultiple = $field['is_multiple']; if (array_key_exists('id', $field)) { $sqlOP = "UPDATE {$tableName} "; $where = " WHERE id = %{$count}"; $params[$count] = array($field['id'], 'Integer'); $count++; $hookOP = 'edit'; } else { $sqlOP = "INSERT INTO {$tableName} "; $where = NULL; $hookOP = 'create'; } } // fix the value before we store it $value = $field['value']; $type = $field['type']; switch ($type) { case 'StateProvince': $type = 'Integer'; if (is_array($value)) { $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR; $type = 'String'; } elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) { //fix for multi select state, CRM-3437 $mulValues = explode(',', $value); $validStates = array(); foreach ($mulValues as $key => $stateVal) { $states = array(); $states['state_province'] = trim($stateVal); CRM_Utils_Array::lookupValue($states, 'state_province', CRM_Core_PseudoConstant::stateProvince(), TRUE); if (empty($states['state_province_id'])) { CRM_Utils_Array::lookupValue($states, 'state_province', CRM_Core_PseudoConstant::stateProvinceAbbreviation(), TRUE); } $validStates[] = CRM_Utils_Array::value('state_province_id', $states); } $value = implode(CRM_Core_DAO::VALUE_SEPARATOR, $validStates); $type = 'String'; } elseif (!$value) { // CRM-3415 // using type of timestamp allows us to sneak in a null into db // gross but effective hack $value = NULL; $type = 'Timestamp'; } else { $type = 'String'; } break; case 'Country': $type = 'Integer'; $mulValues = explode(',', $value); if (is_array($value)) { $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR; $type = 'String'; } elseif (!is_numeric($value) && !strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) { //fix for multi select country, CRM-3437 $mulValues = explode(',', $value); $validCountries = array(); foreach ($mulValues as $key => $countryVal) { $countries = array(); $countries['country'] = trim($countryVal); CRM_Utils_Array::lookupValue($countries, 'country', CRM_Core_PseudoConstant::country(), TRUE); if (empty($countries['country_id'])) { CRM_Utils_Array::lookupValue($countries, 'country', CRM_Core_PseudoConstant::countryIsoCode(), TRUE); } $validCountries[] = CRM_Utils_Array::value('country_id', $countries); } $value = implode(CRM_Core_DAO::VALUE_SEPARATOR, $validCountries); $type = 'String'; } elseif (!$value) { // CRM-3415 // using type of timestamp allows us to sneak in a null into db // gross but effective hack $value = NULL; $type = 'Timestamp'; } else { $type = 'String'; } break; case 'File': if (!$field['file_id']) { CRM_Core_Error::fatal(); } // need to add/update civicrm_entity_file $entityFileDAO = new CRM_Core_DAO_EntityFile(); $entityFileDAO->file_id = $field['file_id']; $entityFileDAO->find(TRUE); $entityFileDAO->entity_table = $field['table_name']; $entityFileDAO->entity_id = $field['entity_id']; $entityFileDAO->file_id = $field['file_id']; $entityFileDAO->save(); $entityFileDAO->free(); $value = $field['file_id']; $type = 'String'; break; case 'Date': $value = CRM_Utils_Date::isoToMysql($value); break; case 'Int': if (is_numeric($value)) { $type = 'Integer'; } else { $type = 'Timestamp'; } break; case 'ContactReference': if ($value == NULL) { $type = 'Timestamp'; } else { $type = 'Integer'; } break; case 'RichTextEditor': $type = 'String'; break; case 'Boolean': //fix for CRM-3290 $value = CRM_Utils_String::strtoboolstr($value); if ($value === FALSE) { $type = 'Timestamp'; } break; default: break; } if (strtolower($value) === "null") { // when unsetting a value to null, we don't need to validate the type // https://projectllr.atlassian.net/browse/VGQBMP-20 $set[$field['column_name']] = $value; } else { $set[$field['column_name']] = "%{$count}"; $params[$count] = array($value, $type); $count++; } } if (!empty($set)) { $setClause = array(); foreach ($set as $n => $v) { $setClause[] = "{$n} = {$v}"; } $setClause = implode(',', $setClause); if (!$where) { // do this only for insert $set['entity_id'] = "%{$count}"; $params[$count] = array($entityID, 'Integer'); $count++; $fieldNames = implode(',', array_keys($set)); $fieldValues = implode(',', array_values($set)); $query = "{$sqlOP} ( {$fieldNames} ) VALUES ( {$fieldValues} )"; // for multiple values we dont do on duplicate key update if (!$isMultiple) { $query .= " ON DUPLICATE KEY UPDATE {$setClause}"; } } else { $query = "{$sqlOP} SET {$setClause} {$where}"; } $dao = CRM_Core_DAO::executeQuery($query, $params); CRM_Utils_Hook::custom($hookOP, $hookID, $entityID, $fields); } } } }
/** * Create an Attachment. * * @param array $params * * @return array * @throws API_Exception validation errors * @see Civi\API\Subscriber\DynamicFKAuthorization */ function civicrm_api3_attachment_create($params) { if (empty($params['id'])) { // When creating we need either entity_table or field_name civicrm_api3_verify_one_mandatory($params, NULL, array('entity_table', 'field_name')); } $config = CRM_Core_Config::singleton(); list($id, $file, $entityFile, $name, $content, $moveFile, $isTrusted, $returnContent) = _civicrm_api3_attachment_parse_params($params); $fileDao = new CRM_Core_BAO_File(); $entityFileDao = new CRM_Core_DAO_EntityFile(); if ($id) { $fileDao->id = $id; if (!$fileDao->find(TRUE)) { throw new API_Exception("Invalid ID"); } $entityFileDao->file_id = $id; if (!$entityFileDao->find(TRUE)) { throw new API_Exception("Cannot modify orphaned file"); } } if (!$id && !is_string($content) && !is_string($moveFile)) { throw new API_Exception("Mandatory key(s) missing from params array: 'id' or 'content' or 'options.move-file'"); } if (!$isTrusted && $moveFile) { throw new API_Exception("options.move-file is only supported on secure calls"); } if (is_string($content) && is_string($moveFile)) { throw new API_Exception("'content' and 'options.move-file' are mutually exclusive"); } if ($id && !$isTrusted && isset($file['upload_date']) && $file['upload_date'] != CRM_Utils_Date::isoToMysql($fileDao->upload_date)) { throw new API_Exception("Cannot modify upload_date" . var_export(array($file['upload_date'], $fileDao->upload_date, CRM_Utils_Date::isoToMysql($fileDao->upload_date)), TRUE)); } if ($id && $name && $name != CRM_Utils_File::cleanFileName($fileDao->uri)) { throw new API_Exception("Cannot modify name"); } $fileDao->copyValues($file); if (!$id) { $fileDao->uri = CRM_Utils_File::makeFileName($name); } $fileDao->save(); $entityFileDao->copyValues($entityFile); $entityFileDao->file_id = $fileDao->id; $entityFileDao->save(); $path = $config->customFileUploadDir . DIRECTORY_SEPARATOR . $fileDao->uri; if (is_string($content)) { file_put_contents($path, $content); } elseif (is_string($moveFile)) { // CRM-17432 Do not use rename() since it will break file permissions. // Also avoid move_uplaoded_file() because the API can use options.move-file. copy($moveFile, $path); unlink($moveFile); } // Save custom field to entity if (!$id && empty($params['entity_table']) && isset($params['field_name'])) { civicrm_api3('custom_value', 'create', array('entity_id' => $params['entity_id'], $params['field_name'] => $fileDao->id)); } $result = array($fileDao->id => _civicrm_api3_attachment_format_result($fileDao, $entityFileDao, $returnContent, $isTrusted)); return civicrm_api3_create_success($result, $params, 'Attachment', 'create'); }
function saveDocument($contact_id, $filename, $mimetype, $filetype, $date, $date_from, $date_to, $comment) { $docs = get_docs_table(); $file = new CRM_Core_DAO_File(); $file->mime_type = $mimetype; $file->uri = $filename; $file->upload_date = date('Ymd'); $file->save(); $entityFile = new CRM_Core_DAO_EntityFile(); $entityFile->file_id = $file->id; $entityFile->entity_id = $contact_id; $entityFile->entity_table = $docs['table']; $entityFile->save(); $stmt = "INSERT INTO {$docs['table']}\n SET {$docs['field_filetype']} = '{$filetype}'\n , {$docs['field_date']} = '{$date}'\n , {$docs['field_from']} = '{$date_from}'\n , {$docs['field_to']} = '{$date_to}'\n , {$docs['field_comment']} = '{$comment}'\n , {$docs['field_file']} = {$file->id}\n , entity_id = {$contact_id}\n "; $res =& CRM_Core_DAO::executeQuery($stmt); return $file->id; }
function fileUpload() { $config = CRM_Core_Config::singleton(); $postParams = $_POST; if ($postParams['entityID'] == 'undefined') { $result = civicrm_api3('HRJob', 'get', array('options' => array('sort' => "id DESC"))); foreach ($result['values'] as $key => $val) { $id = $val['id']; break; } $postParams['entityID'] = ++$id; } $files = $_FILES; if (is_array($files) && !empty($files)) { foreach ($files as $k => $v) { $fileName = CRM_Utils_File::makeFileName(basename($v['name'])); $maxSize = @filesize($v['tmp_name']); $dest = $config->customFileUploadDir; if ($dest != '' && substr($dest, -1) != '/') { $dest .= '/'; } $fileName = $fileName != '' ? $fileName : basename($v['name']); if (is_uploaded_file($v['tmp_name'])) { if (move_uploaded_file($v['tmp_name'], $dest . $fileName)) { $fileparam['name'] = $fileName; $fileparam['uri'] = $fileName; $file_params = array('version' => 3, 'file_type_id' => null, 'mime_type' => $v['type'], 'name' => $fileName, 'uri' => $fileName, 'upload_date' => date('Y-m-d h:i:s', time())); $file_save = civicrm_api('File', 'Create', $file_params); $newEntityFile = new CRM_Core_DAO_EntityFile(); $newEntityFile->entity_id = $postParams['entityID']; $newEntityFile->entity_table = $postParams['entityTable']; $newEntityFile->file_id = $file_save['id']; $newEntityFile->save(); $fileName = basename($v['name']); } } } } CRM_Utils_System::civiExit(); }
public static function fileUpload() { $config = CRM_Core_Config::singleton(); $postParams = $_POST; $result = 0; $dest = $config->customFileUploadDir; if ($dest != '' && substr($dest, -1) != '/') { $dest .= '/'; } $files = $_FILES; if (is_array($files) && !empty($files)) { foreach ($files as $k => $v) { $fileName = self::makeFileName(basename($v['name']), $dest); $maxSize = @filesize($v['tmp_name']); $fileName = $fileName != '' ? $fileName : basename($v['name']); if (is_uploaded_file($v['tmp_name'])) { if (move_uploaded_file($v['tmp_name'], $dest . $fileName)) { $fileparam['name'] = $fileName; $fileparam['uri'] = $fileName; $file_params = array('version' => 3, 'file_type_id' => null, 'mime_type' => $v['type'], 'name' => $fileName, 'uri' => $fileName, 'upload_date' => date('Y-m-d h:i:s', time())); $file_save = civicrm_api('File', 'Create', $file_params); $newEntityFile = new CRM_Core_DAO_EntityFile(); $newEntityFile->entity_id = $postParams['entityID']; $newEntityFile->entity_table = $postParams['entityTable']; $newEntityFile->file_id = $file_save['id']; $newEntityFile->save(); $fileName = basename($v['name']); $result++; } } } } echo html_entity_decode(stripcslashes(json_encode(array('values' => array(array('result' => $result))), true))); CRM_Utils_System::civiExit(); }
function civicrm_api3_civi_outlook_processattachments($params) { //Get mime type of the attachment $mimeType = CRM_Utils_Type::escape($_REQUEST['mimeType'], 'String'); $params['mime_type'] = $mimeType; $config = CRM_Core_Config::singleton(); $directoryName = $config->customFileUploadDir; CRM_Utils_File::createDir($directoryName); //Process the below only if there is any attachment found if (CRM_Utils_Array::value("name", $_FILES['file'])) { $tmp_name = $_FILES['file']['tmp_name']; $name = str_replace(' ', '_', $_FILES['file']['name']); //Replace any spaces in name with underscore $fileExtension = new SplFileInfo($name); if ($fileExtension->getExtension()) { $explodeName = explode("." . $fileExtension->getExtension(), $name); $name = $explodeName[0] . "_" . md5($name) . "." . $fileExtension->getExtension(); } $_FILES['file']['uri'] = $name; move_uploaded_file($tmp_name, "{$directoryName}{$name}"); foreach ($_FILES['file'] as $key => $value) { $params[$key] = $value; } $result = civicrm_api3('File', 'create', $params); if (CRM_Utils_Array::value('id', $result)) { if (CRM_Utils_Array::value('activityID', $params)) { $lastActivityID = $params['activityID']; } $entityFileDAO = new CRM_Core_DAO_EntityFile(); $entityFileDAO->entity_table = 'civicrm_activity'; $entityFileDAO->entity_id = $lastActivityID; $entityFileDAO->file_id = $result['id']; $entityFileDAO->save(); } } return civicrm_api3_create_success($entityFileDAO, $params); }
/** * Assigns an entity to a file * * @param object $file id of a file * @param object $entity id of a entity * @param string $entity_table * * @return array of newly created entity-file object properties * @access public */ function civicrm_entity_file_create(&$fileID, &$entityID, $entity_table = 'civicrm_contact') { require_once 'CRM/Core/DAO/EntityFile.php'; if (!$fileID || !$entityID) { return civicrm_create_error('Required parameters missing'); } $params = array('entity_id' => $entityID, 'file_id' => $fileID, 'entity_table' => $entity_table); $entityFileDAO = new CRM_Core_DAO_EntityFile(); $entityFileDAO->copyValues($params); $entityFileDAO->save(); $entityFile = array(); _civicrm_object_to_array($entityFileDAO, $entityFile); return $entityFile; }