/** * Обрезает анимированный .gif, оставляя только первый кадр. * Обрезанный гиф сохраняет в той же директории, где и оригинал, под тем же именем, только с префиксом 'na_'. * Если файл с таким именем (с префиксом) уже есть, то ничего не делает. * Возвращает в случае успеха имя обрезанного гифа, в случае ошибки (или это не анимированный гиф) -- имя оригинала. * * @param string $dir путь к оригиналу (от корня, без '/' в начале) * @param string $orig_name имя гифа оригинала. * @param string $alt_dir имя альтернативной директории для поиска файла (отличной от foto) * @return string имя обрезанного гифа */ function get_unanimated_gif($dir, $orig_name, $alt_dir = false) { if (CFile::getext($orig_name) != 'gif') { return $orig_name; } $memBuff = new memBuff(); $res = $memBuff->get($orig_name); if ($res) { return $res; } $orig_file = $alt_dir ? trim($alt_dir, '/') . '/' . $orig_name : "users/" . substr($dir, 0, 2) . "/" . $dir . "/foto/" . $orig_name; $orig_content = @file_get_contents(WDCPREFIX_LOCAL . '/' . $orig_file); $unan_content = unanimate_gif($orig_content); if ($unan_content !== false) { $unan_name = "na_" . $orig_name; $unan_file = dirname($orig_file) . "/" . $unan_name; $unan = new CFile($unan_file); if (!$unan->id) { $unan = new CFile($orig_file); $unan->name = $unan_name; $unan->size = strlen($unan_content); $put = $unan->putContent($unan_file, $unan_content); // Записываем измененный файл if ($put) { $memBuff->set($orig_name, $unan_name, 3600 * 12); return $unan_name; } } else { $memBuff->set($orig_name, $unan_name, 3600 * 12); return $unan_name; } } return $orig_name; // Если не смогли сохранить возвращаем оригинал }
/** * Сохраняем документ на сайте. * * @return \CFile */ public function saveFile() { $login = '******'; $content = $this->getOutput(); $file = new CFile(); $file->path = 'users/' . substr($login, 0, 2) . "/{$login}/upload/"; $file->name = basename($file->secure_tmpname($file->path, '.odt')); $file->size = strlen($content); if ($file->putContent($file->path . $file->name, $content)) { return $file; } }
/** * Traitement des retours en erreur d'xml d'un praticien * * @param int $chir_id praticien de la consultation * * @return void|string */ static function traitementDossier($chir_id) { $files = array(); $fs_source_reception = CExchangeSource::get("reception-tarmed-CMediusers-{$chir_id}", "file_system", true, null, false); if (!$fs_source_reception->_id || !$fs_source_reception->active) { return null; } $count_files = CMbPath::countFiles($fs_source_reception->host); if ($count_files < 100) { try { $files = $fs_source_reception->receive(); } catch (CMbException $e) { return CAppUI::tr($e->getMessage()); } } $delfile_read_reject = CAppUI::conf("dPfacturation Other delfile_read_reject", CGroups::loadCurrent()); foreach ($files as $_file) { $fs = new CSourceFileSystem(); $rejet = new self(); $rejet->praticien_id = $chir_id; $rejet->file_name = basename($_file); if ($msg = $rejet->store()) { return $msg; } $rejet->readXML($fs->getData($_file)); //Sauvegarde du XML en CFile $new_file = new CFile(); $new_file->setObject($rejet); $new_file->file_name = basename($_file); $new_file->file_type = "application/xml"; $new_file->author_id = CAppUI::$user->_id; $new_file->fillFields(); $new_file->updateFormFields(); $new_file->forceDir(); $new_file->putContent(trim($fs->getData($_file))); if ($msg = $new_file->store()) { mbTrace($msg); } //Suppression du fichier selon configuration if ($delfile_read_reject) { $fs->delFile($_file); } } return null; }
/** * OBX Segment with reference pointer to external report * * @param DOMNode $OBX DOM node * @param CMbObject $object object * @param String $name name * * @return bool */ function getReferencePointerToExternalReport(DOMNode $OBX, CMbObject $object, $name) { $exchange_hl7v2 = $this->_ref_exchange_hl7v2; $sender = $exchange_hl7v2->_ref_sender; //Récupération de l'emplacement et du type du fichier (full path) $observation = $this->getObservationValue($OBX); $rp = explode("^", $observation); $pointer = CMbArray::get($rp, 0); $type = CMbArray::get($rp, 2); // Création d'un lien Hypertext sur l'objet if ($type == "HTML") { $hyperlink = new CHyperTextLink(); $hyperlink->setObject($object); $hyperlink->name = $name; $hyperlink->link = $pointer; $hyperlink->loadMatchingObject(); if ($msg = $hyperlink->store()) { $this->codes[] = "E343"; return false; } return true; } // Chargement des objets associés à l'expéditeur /** @var CInteropSender $sender_link */ $object_links = $sender->loadRefsObjectLinks(); if (!$object_links) { $this->codes[] = "E340"; return false; } $sender_link = new CInteropSender(); $files_category = new CFilesCategory(); // On récupère toujours une seule catégorie, et une seule source associée à l'expéditeur foreach ($object_links as $_object_link) { if ($_object_link->_ref_object instanceof CFilesCategory) { $files_category = $_object_link->_ref_object; } if ($_object_link->_ref_object instanceof CInteropSender) { $sender_link = $_object_link->_ref_object; continue 1; } } // Aucun expéditeur permettant de récupérer les fichiers if (!$sender_link->_id) { $this->codes[] = "E340"; return false; } $authorized_sources = array("CSenderFileSystem", "CSenderFTP"); // L'expéditeur n'est pas prise en charge pour la réception de fichiers if (!CMbArray::in($sender_link->_class, $authorized_sources)) { $this->codes[] = "E341"; return false; } $sender_link->loadRefsExchangesSources(); // Aucune source permettant de récupérer les fichiers if (!$sender_link->_id) { $this->codes[] = "E342"; return false; } $source = $sender_link->getFirstExchangesSources(); $path = str_replace("\\", "/", $pointer); $path = basename($path); if ($source instanceof CSourceFileSystem) { $path = $source->getFullPath() . "/{$path}"; } // Exception déclenchée sur la lecture du fichier try { $content = $source->getData("{$path}"); } catch (Exception $e) { $this->codes[] = "E345"; return false; } if (!$type) { $type = CMbPath::getExtension($path); } $file_type = $this->getFileType($type); $file_name = $this->getObservationFilename($OBX); // Gestion du CFile $file = new CFile(); $file->setObject($object); $file->file_name = $file_name ? $file_name : $name; $file->file_type = $file_type; $file->loadMatchingObject(); if ($files_category->_id && $sender->_configs["associate_category_to_a_file"]) { $file->file_category_id = $files_category->_id; } $file->file_date = "now"; $file->doc_size = strlen($content); $file->fillFields(); $file->updateFormFields(); $file->putContent($content); if ($msg = $file->store()) { $this->codes[] = "E343"; } $this->codes[] = "I340"; return true; }
public static function saveThemeCss($theme_name, $stylesheets, $skin = null) { if (!$skin) { $skin = modApiFunc('Configuration', 'getValue', STOREFRONT_ACTIVE_SKIN); } $backup_path = CConf::get('themes_backup_dir') . $skin . '.' . $theme_name . date('.Y-m-d.H-i-s') . '.css'; $file = new CFile($backup_path); $file->putContent($stylesheets); $theme_path = self::getThemePath($theme_name, $skin); $file = new CFile($theme_path); if ($file->putContent($stylesheets)) { return array('result' => self::OK, 'message' => ''); } return array('result' => self::FAIL, 'message' => getXMsg('LF', 'LF_THEME_CANT_WRITE'), 'what_to_do' => strtr(getXMsg('LF', 'LF_THEME_PERMISSIONS'), array('%theme_file%' => $theme_path)), 'path' => $theme_path); }
/** * create the CFiles attached to the mail * * @param CMailAttachments[] $attachList The list of CMailAttachment * @param CPop $popClient the CPop client * * @return void */ function attachFiles($attachList, $popClient) { //size limit $size_required = CAppUI::pref("getAttachmentOnUpdate"); if ($size_required == "") { $size_required = 0; } foreach ($attachList as $_attch) { $_attch->mail_id = $this->_id; $_attch->loadMatchingObject(); if (!$_attch->_id) { $_attch->store(); } //si preference taille ok OU que la piece jointe est incluse au texte => CFile if ($_attch->bytes <= $size_required || $_attch->disposition == "INLINE") { $file = new CFile(); $file->setObject($_attch); $file->author_id = CAppUI::$user->_id; if (!$file->loadMatchingObject()) { $file_pop = $popClient->decodeMail($_attch->encoding, $popClient->openPart($this->uid, $_attch->getpartDL())); $file->file_name = $_attch->name; //apicrypt attachment if (strpos($_attch->name, ".apz") !== false) { $file_pop = CApicrypt::uncryptAttachment($popClient->source->object_id, $file_pop); } //file type detection $first = is_array($file_pop) ? reset($file_pop) : $file_pop; $mime = $this->extensionDetection($first); //file name $infos = pathinfo($_attch->name); $extension = $infos['extension']; $mime_extension = strtolower(end(explode("/", $mime))); if (strtolower($extension) != $mime_extension) { $file->file_name = $infos['filename'] . "." . $mime_extension; } $file->file_type = $mime ? $mime : $_attch->getType($_attch->type, $_attch->subtype); $file->fillFields(); $file->updateFormFields(); $file->putContent($file_pop); $file->store(); } } } }
/** * Создает xml файл webprof * * @return text $filename полный путь к файлу куда webdav должен сохранить получившийся xml */ public function webprofGenerateRss($filename) { global $DB, $GLOBALS; require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/professions.php"; require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/kwords.php"; function getProfessionName($id, $professions) { foreach ($professions as $profession) { if ($profession['id'] == $id) { return "{$profession['groupname']} / {$profession['profname']}"; } } } $spec = array(9, 37, 27, 86, 8, 164, 10); $users = self::getListForWebprof($spec); $professions = professions::GetAllProfessions(); $xml = ''; $host = str_replace(HTTP_PREFIX, '', $GLOBALS['host']); $HTTP_PREFIX = "https://"; $XMLData = ''; $xml .= '<?xml version="1.0" encoding="utf-8"?>' . "\n"; $xml .= '<!DOCTYPE source>' . "\n"; $xml .= '<source creation-time="' . date('Y-m-d H:i:s') . ' GMT+3" host="' . $host . '">' . "\n"; $xml .= ' <users>' . "\n"; if (is_array($users) && count($users)) { $XMLData = ''; foreach ($users as $user) { $frl_name = trim("{$user['uname']} {$user['usurname']}"); $frl_name = iconv('CP1251', 'UTF-8', htmlspecialchars($frl_name, ENT_QUOTES)); $frl_spec_main = iconv('CP1251', 'UTF-8', htmlspecialchars(getProfessionName($user['spec'], $professions), ENT_QUOTES)); switch ($user['status_type']) { case '0': $frl_status = 'free'; break; case '1': $frl_status = 'busy'; break; case '2': $frl_status = 'absent'; break; default: $frl_status = 'no status'; break; } $frl_spec_ext = ''; $spec_ext_ids = professions::GetProfsAddSpec($user['uid']); if ($spec_ext_ids) { foreach ($spec_ext_ids as $spec_id) { $frl_spec_ext .= "<spec>" . iconv('CP1251', 'UTF-8', htmlspecialchars(getProfessionName($spec_id, $professions), ENT_QUOTES)) . "</spec>"; } } $frl_tags = ''; $tags = kwords::getUserKeys($user['uid'], $user['spec']); $bIsModer = kwords::isModerUserKeys($user['uid'], $user['spec']); if ($tags && !$bIsModer) { foreach ($tags as $tag) { $frl_tags .= "<tag>" . iconv('CP1251', 'UTF-8', htmlspecialchars($tag, ENT_QUOTES)) . "</tag>"; } } $frl_cost_hour = ''; $frl_cost_month = ''; if ($user['cost_hour'] != 0) { $frl_cost_hour = (double) $user['cost_hour']; switch ($user['cost_type_hour']) { case '1': $frl_cost_hour .= " Euro"; break; case '2': $frl_cost_hour .= " Руб"; break; case '3': $frl_cost_hour .= " FM"; break; default: $frl_cost_hour .= " USD"; break; } $frl_cost_hour = iconv('CP1251', 'UTF-8', $frl_cost_hour); } if ($user['cost_month'] != 0) { $frl_cost_month = (double) $user['cost_month']; switch ($user['cost_type_month']) { case '1': $frl_cost_month .= " Euro"; break; case '2': $frl_cost_month .= " Руб"; break; case '3': $frl_cost_month .= " FM"; break; default: $frl_cost_month .= " USD"; break; } $frl_cost_month = iconv('CP1251', 'UTF-8', $frl_cost_month); } $XMLData .= "<user>"; $XMLData .= "<name>{$frl_name}</name>"; $XMLData .= "<spec_main>{$frl_spec_main}</spec_main>"; $XMLData .= "<spec_ext>{$frl_spec_ext}</spec_ext>"; $XMLData .= "<status>{$frl_status}</status>"; $XMLData .= "<rating>{$user['rating']}</rating>"; $XMLData .= "<cost_from_hour>{$frl_cost_hour}</cost_from_hour>"; $XMLData .= "<cost_from_month>{$frl_cost_month}</cost_from_month>"; $XMLData .= "<url>" . $HTTP_PREFIX . "{$host}/users/{$user['login']}</url>"; $XMLData .= "<tags>{$frl_tags}</tags>"; $XMLData .= "</user>\n"; } } $xml .= $XMLData . "\n"; $xml .= ' </users>' . "\n"; $xml .= '</source>' . "\n"; $file = new CFile(); return $file->putContent($filename, $xml); }
/** * Создает xml файл для Jooble.ru * * @param $filename string полный путь к файлу куда webdav должен сохранить получившийся xml * @param string $interval Интервал (1 day, 2 days, 1 month) * @return text $filename полный путь к файлу куда webdav должен сохранить получившийся xml */ function joobleGenerateRss($filename, $prjs) { require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php"; $project_exRates = project_exrates::GetAll(); $exch = array(1 => 'FM', 'USD', 'Euro', 'Руб'); $translate_exRates = array(0 => 2, 1 => 3, 2 => 4, 3 => 1); $xml = ''; $host = str_replace(HTTP_PREFIX, '', $GLOBALS['host']); $HTTP_PREFIX = "https://"; $xml = '<?xml version="1.0" encoding="utf-8"?>' . "\n"; $xml .= '<source creation-time="' . date('Y-m-d H:i:s') . ' GMT+3" host="' . $host . '">' . "\n"; $xml .= ' <jobs>' . "\n"; foreach ($prjs as $row) { $city = $row['city_name'] ? $row['city_name'] : ''; $location = $row['country_name'] ? $row['country_name'] : ''; $location .= $location ? ', ' . $city : $city; $location = preg_replace("/, \$/", "", $location); $location = html_entity_decode($location, ENT_QUOTES, 'cp1251'); if (!$location) { $location = 'Россия'; } $row['categories'] = self::getProjectCategories($row['id']); if (!empty($row['categories'])) { $name_case = false; foreach ($row['categories'] as $cat) { if ((int) $cat['subcategory_id'] > 0) { if ($cat['name_case']) { $name_case[] = $cat['name_case']; } } } if ($name_case) { $name_case = implode(". ", $name_case) . ". "; } } $cat = html_entity_decode($row['cat_name'], ENT_QUOTES, 'cp1251'); $name = html_entity_decode($name_case . $row['project_name'], ENT_QUOTES, 'cp1251'); unset($name_case); $descr = html_entity_decode($row['descr'], ENT_QUOTES, 'cp1251'); $contacts = $row['e_login']; $contacts = $row['e_surname'] ? html_entity_decode($row['e_surname'], ENT_QUOTES, 'cp1251') . ', ' . $contacts : $contacts; $contacts = $row['e_name'] ? html_entity_decode($row['e_name'], ENT_QUOTES, 'cp1251') . ' ' . $contacts : $contacts; $currency = ''; switch ($row['currency']) { case 0: $currency = '$'; break; case 1: $currency = ' Euro'; break; case 2: $currency = ' Руб.'; break; case 3: $currency = ' Руб.'; break; } if ($row['cost'] && $row['currency'] == 3) { $row['cost'] = preg_replace("/\\.00\$/", "", sprintf("%.2f", round($row['cost'] * $project_exRates[trim($translate_exRates[$row['currency']]) . '4'], 2))); } $xml .= ' <job id="' . $row['id'] . '"> <link>' . $HTTP_PREFIX . $host . getFriendlyURL('project', $row['id']) . '</link> '; $name .= ' (удаленно)'; $xml .= ' <name>' . xmloutofrangechars(iconv('CP1251', 'UTF-8', htmlspecialchars($name, ENT_QUOTES))) . '</name>'; $xml .= '<description>' . xmloutofrangechars(iconv('CP1251', 'UTF-8', htmlspecialchars($descr, ENT_QUOTES))) . '</description> <region>' . iconv('CP1251', 'UTF-8', htmlspecialchars($location, ENT_QUOTES)) . "</region>\n <salary>" . ($row['cost'] ? iconv('CP1251', 'UTF-8', $row['cost'] . $currency) : '') . "</salary>\n <contacts>" . iconv('CP1251', 'UTF-8', $contacts) . "</contacts>\n <company></company>\n <expire>" . ($row['kind'] == 7 ? dateFormat("d.m.Y", $row['end_date']) : '') . "</expire>\n <updated>" . dateFormat("d.m.Y", $row['create_date']) . "</updated>\n </job>\n"; } $xml .= "</jobs>\n</source>"; $file = new CFile(); return $file->putContent($filename, $xml); }
// 'from_time' => '2010-01-03', // 'to_time' => '2010-06-15' // ), // array( // 'from_time' => '2010-12-02', // 'to_time' => '2010-12-28' // ) // )); $svg = $graph->render(); $cfile = new CFile(); $cfile->name = "{$file_name}.{$file_ext}"; $cfile->path = "/users/" . substr($u_login, 0, 2) . "/{$u_login}/upload/"; $cfile->modified = ''; $cfile->putContent($file, $file_ext == 'html' ? svgToVml($svg) : $svg); $file_ext = $file_ext == 'svg' ? 'html' : 'svg'; $file = "/users/" . substr($u_login, 0, 2) . "/{$u_login}/upload/{$file_name}.{$file_ext}"; $cfile = new CFile(); $cfile->name = "{$file_name}.{$file_ext}"; $cfile->path = "/users/" . substr($u_login, 0, 2) . "/{$u_login}/upload/"; $cfile->modified = ''; $cfile->putContent($file, $file_ext == 'html' ? svgToVml($svg) : $svg); $svg = stristr($_SERVER['HTTP_USER_AGENT'], 'msie ') ? svgToVml($svg) : $svg; if (stristr($_SERVER['HTTP_USER_AGENT'], 'msie ')) { header('Content-type: text/html'); } else { header('Content-type: image/svg+xml'); } echo $svg; } else { header("Location: " . WDCPREFIX . $file); }
function _save_cert_to_file($cert_code) { if ($this->_validate_cert($cert_code, true) !== CERTIFICATE_OK) { $this->certificate = array(); $this->certificate_status = CERTIFICATE_INVALID; return false; } $cert = ";<?php exit();?>\n" . $cert_code; $file = new CFile($this->license_cert_file); if (!$file->putContent($cert)) { $this->certificate = array(); $this->certificate_status = CERTIFICATE_NOT_EXISTS; return false; } $this->license_cert = $this->_read_cert_from_file(); $this->certificate_status = $this->_validate_cert(); return true; }
$svg->file_name = $file->file_name; $svg->file_type = "image/svg+xml"; $svg->author_id = $file->author_id; $svg->loadMatchingObject(); $svg->fillFields(); $svg->setObject($file->_ref_object); $svg->updateFormFields(); if (strpos($svg->file_name, ".") === false) { $svg->file_name = $svg->file_name . ".svg"; } if (strpos($svg->file_name, ".fjs") !== false) { $svg->file_name = str_replace(".fjs", ".svg", $svg->file_name); } // @TODO : replace url by datauri $content = str_replace(array("&a=fileviewer", "&file_id", "&suppressHeaders"), array("&a=fileviewer", "&file_id", "&suppressHeaders"), $content); if ($result = $svg->putContent(stripslashes($content))) { if ($msg = $svg->store()) { CAppUI::stepAjax($msg, UI_MSG_ERROR); } else { CAppUI::stepAjax("Dessin exporté avec succès", UI_MSG_OK); } } if ($remove_draft) { $msg = $file->delete(); CAppUI::stepAjax($msg ? $msg : "CFile-msg-delete", $msg ? UI_MSG_WARNING : UI_MSG_OK); } } else { if ($result = $file->putContent(stripslashes($content))) { // no extensio; if (strpos($file->file_name, ".") === false) { $file->file_name .= ".fjs";
function _save_key_to_file($file, $key) { if ($this->_is_license_key_valid($key)) { $_key = $this->formatKey($key); if ($_key !== false) { $str = ";<?php exit(); ?>\n"; $str .= "key = " . $_key; $fp = new CFile($file); if (!$fp->putContent($str)) { return LICENSE_KEY_NOT_WRITEABLE; } #$this->license_key = $_key; $this->license_key = $this->_read_key_from_file($this->license_key_file, ".php"); if (!$this->_is_license_key_valid($this->license_key)) { $this->license_key = LICENSE_KEY_UNDEFINED; return LICENSE_KEY_FORMAT_INVALID; } else { return LICENSE_KEY_FILE_OK; } } else { return LICENSE_KEY_FORMAT_INVALID; } } else { return LICENSE_KEY_FORMAT_INVALID; } }
/** * Make a PDF document archive of the sejour (based on soins/print_dossier_soins) * * @param string $title File title * @param bool $replace Replace existing file * * @return bool * @throws CMbException */ function makePDFarchive($title = "Dossier complet", $replace = false) { if (!CModule::getActive("soins")) { return false; } $query = array("m" => "soins", "a" => "print_dossier_soins", "sejour_id" => $this->_id, "dialog" => 1, "offline" => 1, "limit" => 10000, "_aio" => 1, "_aio_ignore_scripts" => 1); $base = $_SERVER["SCRIPT_NAME"] . "?" . http_build_query($query, "", "&"); $result = CApp::serverCall("http://127.0.0.1{$base}"); $content = $result["body"]; $file = new CFile(); $file->setObject($this); $file->file_name = "{$title}.pdf"; $file->file_type = "application/pdf"; /*if ($file->loadMatchingObject()) { if ($replace) { $file->delete(); // New file $file = new CFile(); $file->setObject($this); $file->file_name = "$title.pdf"; $file->file_type = "application/pdf"; } }*/ $file->fillFields(); $file->updateFormFields(); $file->forceDir(); $file->author_id = CAppUI::$user->_id; $compte_rendu = new CCompteRendu(); $compte_rendu->_orientation = "portrait"; $format = CCompteRendu::$_page_formats["a4"]; $page_width = round(72 / 2.54 * $format[0], 2); $page_height = round(72 / 2.54 * $format[1], 2); $compte_rendu->_page_format = array(0, 0, $page_width, $page_height); $content = str_replace("<!DOCTYPE html>", "", $content); CHtmlToPDFConverter::init("CWkHtmlToPDFConverter"); //CHtmlToPDFConverter::init("CPrinceXMLConverter"); $pdf = CHtmlToPDFConverter::convert($content, $compte_rendu->_page_format, $compte_rendu->_orientation); $file->putContent($pdf); if ($msg = $file->store()) { throw new CMbException($msg); } return true; }
} else { CAppUI::setMsg("CMailAttachments-msg-attachmentsaved", UI_MSG_OK); } $pop->close(); } } else { //je récupère TOUTES les pièces jointes $mail->loadRefsFwd(); foreach ($mail->_attachments as $_att) { $file = new CFile(); $file->setObject($_att); $file->author_id = $user->_id; $file->loadMatchingObject(); if (!$file->_id) { $pop = new CPop($log_pop); $pop->open(); $file_pop = $pop->decodeMail($_att->encoding, $pop->openPart($mail->uid, $_att->getpartDL())); $file->file_name = $_att->name; $file->file_type = $_att->getType($_att->type, $_att->subtype); $file->fillFields(); $file->putContent($file_pop); if ($str = $file->store()) { CAppUI::setMsg($str, UI_MSG_ERROR); } else { CAppUI::setMsg("CMailAttachments-msg-attachmentsaved", UI_MSG_OK); } $pop->close(); } } } echo CAppUI::getMsg();
/** * Store a CFile linked to $this * * @param string $filename File name * @param string $filedata File contents * * @return bool */ function addFile($filename, $filedata) { $file = new CFile(); $file->setObject($this); $file->file_name = $filename; $file->file_type = "text/plain"; $file->doc_size = strlen($filedata); $file->author_id = CAppUI::$instance->user_id; $file->fillFields(); if (!$file->putContent($filedata)) { return false; } $file->store(); return true; }
/** * НЕ ИСПОЛЬЗОВАТЬ - УСТАРЕЛ СМ generateInvoice2. * * Генерация счета * * @todo: может перенести генерацию в очереди? * @todo: но тогда нужно организовать обратную связь. * * @param type $user_info * * @return bool|\CFile */ public function generateInvoice($user_info) { extract($this->options); $file = new CFile(); $file_path = $this->getFilePath(); $reserve_id = @$this->data['reserve_id']; if (!$file_path || !$reserve_id || empty($this->data)) { return false; } $data = $this->getCheckByReserveId($reserve_id); if (isset($data['payed_date']) && !empty($data['payed_date'])) { return false; } if (isset($data['check_file_id']) && $data['check_file_id'] > 0) { $file->Delete($data['check_file_id']); } if (!$data) { $data = array(); } $this->data = array_merge($data, $this->data, $user_info); $data = $this->data; $bill_num = sprintf($bill_num_format, $data['reserve_id']); $data['bill_num'] = $bill_num; $data['date'] = date_text($data['date'], 'd'); $data['price_txt'] = num2str(intval($data['price'])); $data['price'] = number_format($data['price'], 2, ',', ''); $data['title'] = sprintf($check_title, $bill_num); foreach ($data as $key => $value) { $data['$' . $key] = $value; unset($data[$key]); } $pdf = new odt2pdf($invoice_template); $pdf->setFolder(ABS_PATH . $templates_path); $pdf->convert($data); $content = $pdf->output(null, 'S'); $len = strlen($content); if (!$len) { return false; } $file->path = $file_path; $file->table = $table_files; $file->size = $len; $file->src_id = $src_id; $file->name = basename($file->secure_tmpname($file->path, '.pdf')); $file->original_name = change_q_x(sprintf($check_org_filename, $bill_num)); if (!$file->putContent($file->path . $file->name, $content)) { return false; } $this->data['check_file_id'] = $file->id; return $this->addCheck() ? $file : false; }
while ($zipFile = zip_read($zip)) { $doc_name = zip_entry_name($zipFile); $extension = strtolower(pathinfo($doc_name, PATHINFO_EXTENSION)); $file_name = pathinfo($doc_name, PATHINFO_BASENAME); $doc_size = zip_entry_filesize($zipFile); $dir_name = end(explode("/", dirname($doc_name))); if ((!$dir_name || $dir_name == ".") && $category || $category != "divers") { $dir_name = $category; } $cat = new CDrawingCategory(); $cat->name = $dir_name; $cat->loadMatchingObjectEsc(); if ($msg = $cat->store()) { CAppUI::stepAjax($msg, UI_MSG_WARNING); } $content_file = zip_entry_read($zipFile, $doc_size); if ($content_file) { $file = new CFile(); $file->file_name = $file_name; $file->author_id = CAppUI::$user->_id; $file->file_type = CMbPath::guessMimeType($doc_name); $file->fillFields(); $file->setObject($cat); $file->updateFormFields(); $file->putContent($content_file); if ($msg = $file->store()) { CAppUI::setMsg($msg, UI_MSG_WARNING); } } } zip_close($zip);
$text->load($text_html); $content_type = "text/html"; } else { $text = new CContentAny(); $text->load($text_plain); } $file = new CFile(); $file->setObject($object); $file->author_id = CAppUI::$user->_id; $file->file_name = "sans_titre"; $file->file_category_id = $category_id; if ($mail->subject) { $file->file_name = $mail->subject; } if ($rename_text) { $file->file_name = $rename_text; } $file->file_type = $content_type; $file->fillFields(); $file->putContent($text->content); if ($str = $file->store()) { CAppUI::stepAjax($str, UI_MSG_ERROR); } else { $mail->text_file_id = $file->_id; $mail->store(); CAppUI::stepAjax("CUserMail-content-attached", UI_MSG_OK); } } if (!$text_html && !$text_plain && $attach_list == "") { CAppUI::stepAjax("CMailAttachments-msg-noAttachSelected", UI_MSG_ERROR); }
/** * Создает пакет. * * @param integer $type тип пакета (TYPE_CSS|TYPE_JS|TYPE_PHP_JS|TYPE_JS_UTF8) * @param string $batch_id ид. (хеш) пакета * @param string $batch_version устанавливаемая версия пакета (текущая версия всей статики). * @param string $filename вернется имя файла пакета * @param boolean $light true, если сжимаем по облегченному варианту (сжатие быстрое, но не полное). * @return int код ошибки или 0. */ private function _createBatch($type, $batch_id, $batch_version, &$filename, $light = false) { $log = $this->_log; $err = 0; $cfile = new CFile(); $filename = self::STATIC_WDPATH . '/' . $this->createFileName($batch_id, $batch_version, $this->types[$type]); $lock_key = $this->_createBatchLockKey($batch_id, $batch_version); if (!$light || !$cfile->CheckPath($filename, false)) { // проверка на случай, если pgq переполнится. $log->writeln("creating new batch file {$filename}, compressing content..."); if ($content = $this->_compress($type, $light)) { $cfile->exclude_reserved_wdc = true; if ($cfile->putContent($filename, $content)) { $log->writeln('saving batch info to memcached...'); if (!$this->setBatchVersion($batch_id, $batch_version)) { $err = 3; } } else { $err = 2; } } else { $err = 1; } } if ($err) { $log->writeln("failed ({$err})"); $filename = NULL; } $log->writeln('unset lock...'); $ok = $this->memBuff->delete($lock_key); $log->writeln($ok ? 'ok' : 'failed'); return $err; }
/** * Генерация Exсel таблицы на основе шаблона * * @param type $cellnames - массив ячеек где искать шаблоны подстановки * @return boolean|\CFile */ public function generateExcel($cellnames = array('A1')) { if (empty($cellnames) || empty($this->data)) { return false; } $objReader = PHPExcel_IOFactory::createReader('Excel5'); $objPHPExcel = $objReader->load(ABS_PATH . $this->template_path . $this->template); $data = array(); foreach ($this->data as $key => $value) { $value = iconv("windows-1251", "utf-8", $value); $data['{' . $key . '}'] = $value; } $keys = array_keys($data); $vals = array_values($data); foreach ($cellnames as $cellname) { $content = (string) $objPHPExcel->getActiveSheet()->getCell($cellname); if (!empty($content)) { $content = str_replace($keys, $vals, $content); $objPHPExcel->getActiveSheet()->setCellValue($cellname, $content); } } if (!file_exists($this->tmp_path)) { mkdir($this->tmp_path, 0777); } $tmpFilename = tempnam($this->tmp_path, 'tmp'); //$tmpFilename = $this->tmp_path . substr(md5(microtime()), 0, 6) . '.xls'; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save($tmpFilename); $content = file_get_contents($tmpFilename); unlink($tmpFilename); $file = new CFile(); $file->path = $this->getFilePath(); $file->table = $this->file_table; $file->size = strlen($content); $file->src_id = $this->file_src_id; $file->name = basename($file->secure_tmpname($file->path, '.xls')); $file->original_name = change_q_x($this->file_original_name); if (!$file->putContent($file->path . $file->name, $content)) { return false; } Events::trigger('generate_file', $file); return $file; }
<?php /** * $Id$ * * @category Files * @package Mediboard * @author SARL OpenXtrem <*****@*****.**> * @license GNU General Public License, see http://www.gnu.org/licenses/gpl.html * @version $Revision$ * @link http://www.mediboard.org */ CCanDo::checkEdit(); $object_class = CValue::post("object_class"); $object_id = CValue::post("object_id"); $content = CValue::post("content"); $file_name = CValue::post("file_name"); $file = new CFile(); $file->file_name = $file_name; $file->object_class = $object_class; $file->object_id = $object_id; $file->fillFields(); $file->putContent(base64_decode($content)); $file->file_type = CMbPath::guessMimeType($file_name); if ($msg = $file->store()) { CAppUI::setMsg($msg, UI_MSG_ERROR); } else { CAppUI::setMsg("CFile-msg-moved"); } echo CAppUI::getMsg();
/** * Сохраняет контент документа в файл. * * @param string $content текст файла. * @param string $ext расширение файла. * @return CFile загруженный файл. */ function _saveDocFile($content, $ext = '.pdf') { if (trim($content) == "") { return NULL; } $file = new CFile(); $file->table = 'file_sbr'; $file->path = $this->getUploadDir(); $file->name = basename($file->secure_tmpname($file->path, '.pdf')); $file->size = strlen($content); if ($file->putContent($file->path . $file->name, $content)) { return $file; } return NULL; }
/** * Edition des journaux selon le type * * @param bool $read lecture * @param bool $create_journal Création du journal * * @return void */ function editJournal($read = true, $create_journal = true) { if ($create_journal) { $journal = new CJournalBill(); $journal->type = $this->type_pdf; $journal->nom = "Journal_" . $this->type_pdf . "_" . CMbDT::date(); $journal->_factures = $this->factures; if ($msg = $journal->store()) { mbTrace($msg); } else { $this->journal_id = $journal->_id; } } // Creation du PDF $this->pdf = new CMbPdf('l', 'mm'); $this->pdf->setPrintHeader(false); $this->pdf->setPrintFooter(false); $this->font = "vera"; $this->fontb = $this->font . "b"; $this->pdf->setFont($this->font, '', 8); $this->page = 0; $this->editEntete(); switch ($this->type_pdf) { case "paiement": $this->editPaiements(); break; case "debiteur": $this->editDebiteur(); break; case "rappel": $this->editRappel(); break; case "checklist": $this->editCheckList(); break; } if ($create_journal) { $file = new CFile(); $file->file_name = $journal->nom . ".pdf"; $file->file_type = "application/pdf"; $file->author_id = CMediusers::get()->_id; $file->file_category_id = 1; $file->setObject($journal); $file->fillFields(); $file->putContent($this->pdf->Output('Factures.pdf', "S")); if ($msg = $file->store()) { echo $msg; } if ($this->type_pdf == "checklist") { $user = CMediusers::get(); $printer = new CPrinter(); $printer->function_id = $user->function_id; $printer->label = "justif"; $printer->loadMatchingObject(); if (!$printer->_id) { CAppUI::setMsg("Les imprimantes ne sont pas paramétrées", UI_MSG_ERROR); echo CAppUI::getMsg(); return false; } $file = new CFile(); $pdf = $this->pdf->Output('Factures.pdf', "S"); $file_path = tempnam("tmp", "facture"); $file->_file_path = $file_path; file_put_contents($file_path, $pdf); $printer->loadRefSource()->sendDocument($file); unlink($file_path); } } if ($read) { //Affichage du fichier pdf $this->pdf->Output('Factures.pdf', "I"); } }
function asc_file_put_contents($filepath, $contents) { $f = new CFile($filepath); $f->putContent($contents); }
</table:table-cell> <table:table-cell office:value-type="string"> <text:p>An online map</text:p> </table:table-cell> <table:table-cell office:value-type="string"> <text:p> <text:a xlink:type="simple" xlink:href="http://maps.google.com/" >http://maps.google.com</text:a> </text:p> </table:table-cell> </table:table-row> </table:table> '; */ $descr_tz = ' 111 <text:h text:outline-level="1"> A Table (Heading 1)</text:h> <text:p>222</text:p> <text:a xlink:type="simple" xlink:href="http://www.flickr.com/services/api/">http://www.flickr.com/services/api/</text:a> '; $act_new = array('$sbr_num' => "СБР-109-Б/О-1", '$date_act' => "12.09.2012", '$date_sbr' => "12.09.2012", '$efio' => "Резидент Республики Беларусь", '$ffio' => "Александр Сергеевич Буров", '$sum_frl' => num2strEx($sum_frl, 'рублей Российской Федерации'), '$sum_emp' => num2strEx($sum_emp, 'рублей Российской Федерации'), '$tz_descr' => $descr_tz, '$work_time' => '3 дня на этап', '$work_type' => 'Промежуточной стоимости Работы', '$work_cost' => num2strEx($work_cost, 'рублей Российской Федерации'), '$is_arb_emp' => false, '$is_arb_frl' => false, '$user_arb' => 'Заказчик', '$result_arb' => 'Результат арбитража вынес потому что не работал такой то человек'); $t = new odt2pdf('arb_frl_soglashenie.odt'); $t->convert($act_new); $content = $t->Output(NULL, 'S'); $file = new CFile(); //$file->table = 'file_sbr'; $file->path = 'uploader/'; $file->name = basename($file->secure_tmpname($file->path, '.pdf')); $file->size = strlen($content); $file->putContent($file->path . $file->name, $content); //echo strlen($t->output);
/** * Store the file * * @param String $prefix Prefix for the name of file * @param String $file_name Name of file * @param String $file_type Type file * @param CSejour $sejour Sejour * @param Array &$erreur Error * * @return bool */ function storeFile($prefix, $file_name, $file_type, $sejour, &$erreur) { /** @var CInteropSender $sender */ $sender = $this->_ref_sender; $exchange_hpr = $this->_ref_exchange_hpr; $file = false; $object_links = $sender->loadRefsObjectLinks(); foreach ($object_links as $_object_link) { /** @var CInteropSender $sender_link */ $sender_link = $_object_link->loadRefObject(); $sender_link->loadRefsExchangesSources(); foreach ($sender_link->_ref_exchanges_sources as $_source) { $path = $_source->getFullPath($file_name); /** @var CExchangeSource $_source */ $data = $_source->getData($path); if (!$data) { continue; } $file = new CFile(); $file->file_name = "{$prefix} {$file_name}"; $file->file_type = $file_type; $file->fillFields(); $file->setObject($sejour); $file->putContent($data); if ($msg = $file->store()) { $erreur[] = new CHPrimSanteError($exchange_hpr, "P", "17", array("OBX", $this->loop, $this->identifier_patient), "10.6", CMbString::removeAllHTMLEntities($msg)); continue; } } } if (!$file) { $erreur[] = new CHPrimSanteError($exchange_hpr, "P", "18", array("OBX", $this->loop, $this->identifier_patient), "10.6"); return false; } return true; }