/** * @see parent::send() */ public function send() { $Resume = $this->getObject(); if ($Resume->IsFile) { $this->attach(File::path($Resume), $Resume->Filename); } return parent::send(); }
/** * ========================================================== * GET SHIELD PATH BY ITS NAME * ========================================================== * * -- CODE: ------------------------------------------------- * * echo Shield::path('article'); * * ---------------------------------------------------------- * */ public static function path($name) { $name = File::path($name) . '.' . File::E($name, 'php'); if ($path = File::exist(SHIELD . DS . Config::get('shield') . DS . ltrim($name, DS))) { return $path; } else { if ($path = File::exist(ROOT . DS . ltrim($name, DS))) { return $path; } } return $name; }
public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media = null) { // If we are on a private node, we won't do any remote calls (just as a precaution until // we can configure this from config.php for the private nodes) if (common_config('site', 'private')) { return true; } if ($media !== 'image') { return true; } // If there is a local filename, it is either a local file already or has already been downloaded. if (!empty($file->filename)) { return true; } $this->checkWhitelist($file->getUrl()); // First we download the file to memory and test whether it's actually an image file $imgData = HTTPClient::quickGet($file->getUrl()); common_debug(sprintf('Downloading remote file id==%u with URL: %s', $file->id, $file->getUrl())); $info = @getimagesizefromstring($imgData); if ($info === false) { throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $file->getUrl()); } elseif (!$info[0] || !$info[1]) { throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)')); } $filehash = hash(File::FILEHASH_ALG, $imgData); try { // Exception will be thrown before $file is set to anything, so old $file value will be kept $file = File::getByHash($filehash); //FIXME: Add some code so we don't have to store duplicate File rows for same hash files. } catch (NoResultException $e) { $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']); $fullpath = File::path($filename); // Write the file to disk if it doesn't exist yet. Throw Exception on failure. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) { throw new ServerException(_('Could not write downloaded file to disk.')); } // Updated our database for the file record $orig = clone $file; $file->filehash = $filehash; $file->filename = $filename; $file->width = $info[0]; // array indexes documented on php.net: $file->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php // Throws exception on failure. $file->updateWithKeys($orig, 'id'); } // Get rid of the file from memory unset($imgData); $imgPath = $file->getPath(); return false; }
/** * Create a ZIP archive encoded in CP850 so that Windows will understand * foreign characters * * @param File $archiveFile * @param Folder $workingFolder * @param Base[] $sources * @param boolean $utf8 Set to true to use UTF8 encoding. This is not supported by Windows explorer. * @throws Exception */ public static function create(File $archiveFile, Folder $workingFolder, $sources, $utf8 = false) { if (class_exists("\\ZipArchive") && !$utf8) { \GO::debug("Using PHP ZipArchive"); $zip = new \ZipArchive(); $zip->open($archiveFile->path(), \ZipArchive::CREATE); for ($i = 0; $i < count($sources); $i++) { if ($sources[$i]->isFolder()) { self::_zipDir($sources[$i], $zip, str_replace($workingFolder->path() . '/', '', $sources[$i]->path()) . '/'); } else { $name = str_replace($workingFolder->path() . '/', '', $sources[$i]->path()); $name = @iconv('UTF-8', 'CP850//TRANSLIT', $name); \GO::debug("Add file: " . $sources[$i]->path()); $zip->addFile($sources[$i]->path(), $name); } } if (!$zip->close() || !$archiveFile->exists()) { throw new \Exception($zip->getStatusString()); } else { return true; } } else { \GO::debug("Using zip exec"); if (!\GO\Base\Util\Common::isWindows()) { putenv('LANG=en_US.UTF-8'); } chdir($workingFolder->path()); $cmdSources = array(); for ($i = 0; $i < count($sources); $i++) { $cmdSources[$i] = escapeshellarg(str_replace($workingFolder->path() . '/', '', $sources[$i]->path())); } $cmd = \GO::config()->cmd_zip . ' -r ' . escapeshellarg($archiveFile->path()) . ' ' . implode(' ', $cmdSources); exec($cmd, $output, $ret); if ($ret != 0 || !$archiveFile->exists()) { throw new \Exception('Command failed: ' . $cmd . "<br /><br />" . implode("<br />", $output)); } return true; } }
function makeBackupFile($user) { // XXX: this is pretty lose-y; try another way $tmpdir = sys_get_temp_dir() . '/offline-backup/' . $user->nickname . '/' . common_date_iso8601(common_sql_now()); common_log(LOG_INFO, 'Writing backup data to ' . $tmpdir . ' for ' . $user->nickname); mkdir($tmpdir, 0700, true); $this->dumpNotices($user, $tmpdir); $this->dumpFaves($user, $tmpdir); $this->dumpSubscriptions($user, $tmpdir); $this->dumpSubscribers($user, $tmpdir); $this->dumpGroups($user, $tmpdir); $fileName = File::filename($user->getProfile(), "backup", "application/atom+xml"); $fullPath = File::path($fileName); $this->makeActivityFeed($user, $tmpdir, $fullPath); $this->delTree($tmpdir); return $fileName; }
/** * Get file name * * @param array $args $_REQUEST array * * @return success flag */ function prepare($args) { parent::prepare($args); $filename = $this->trimmed('filename'); $path = null; if ($filename && File::validFilename($filename)) { $path = File::path($filename); } if (empty($path) or !file_exists($path)) { $this->clientError(_('No such file.'), 404); return false; } if (!is_readable($path)) { $this->clientError(_('Cannot read file.'), 403); return false; } $this->path = $path; return true; }
/** * Get file name * * @param array $args $_REQUEST array * * @return success flag */ protected function prepare(array $args = array()) { parent::prepare($args); $filename = $this->trimmed('filename'); $path = null; if ($filename && File::validFilename($filename)) { $path = File::path($filename); } if (empty($path) or !file_exists($path)) { // TRANS: Client error displayed when requesting a non-existent file. $this->clientError(_('No such file.'), 404); } if (!is_readable($path)) { // TRANS: Client error displayed when requesting a file without having read access to it. $this->clientError(_('Cannot read file.'), 403); } $this->path = $path; return true; }
protected final function __new__($level, $value, $file = null, $line = null, $time = null) { if ($file === null) { $debugs = debug_backtrace(false); if (sizeof($debugs) > 4) { list($dumy, $dumy, $dumy, $debug, $op) = $debugs; } else { list($dumy, $debug) = $debugs; } $file = File::path(isset($debug['file']) ? $debug['file'] : $dumy['file']); $line = isset($debug['line']) ? $debug['line'] : $dumy['line']; $class = isset($op['class']) ? $op['class'] : $dumy['class']; } $this->level = $level; $this->file = $file; $this->line = intval($line); $this->time = $time === null ? time() : $time; $this->class = $class; $this->value = is_object($value) ? $value instanceof Exception ? array_merge(array($value->getMessage()), self::$exception_trace ? $value->getTrace() : array($value->getTraceAsString())) : clone $value : $value; }
/** * 既存のDBからモデルファイルを自動生成する **/ public static function __setup_generate_model__(Request $request, $value) { if (!$request->is_vars('tables')) { throw new RuntimeException('tables required'); } $model_path = $request->is_vars('model_path') ? $request->in_vars('model_path') : path('libs/model'); $tables = $request->in_vars('tables'); $tables = strpos(',', $tables) === false ? array($tables) : explode(',', $tables); foreach ($tables as $table) { $dao = Dao::instant($table, $value); $props = $dao->get_columns(); $properties = array(); foreach ($props as $prop_name) { $property = new ModelProperty(); $property->name($prop_name); foreach (self::$anons as $a) { $anon = $dao->a($prop_name, $a); if (isset(self::$defaults[$prop_name]) && self::$defaults[$prop_name] == $anon) { continue; } if (!is_null($anon)) { $property->annotation($a, $anon); } } $properties[] = $property; } $class_name = preg_replace('/_(.)/e', 'ucfirst("\\1")', ucfirst(strtolower($table))); $template = new Template(); $template->vars('properties', $properties); $template->vars('class_name', $class_name); $filename = File::path($model_path, $class_name . '.php'); $src = "<?php\n" . $template->read(module_templates('model.php')); File::write($filename, $src); // unset $dao = $template = $properties = $property = null; unset($dao); unset($template); unset($properties); unset($property); } }
function copy_files() { $files = $this->get_files(); $paths = $this->project->file_paths(); foreach ($files as $file_parameters) { $file_to_copy = new File($file_parameters); $file_to_copy_url = $file_to_copy->path(); //create the file record $file = new File(); $file->import_parameters_exactly($file_parameters); //we want to create a new file so we need to reset the id. If we don't the app will just save our changes on //the old file (bad idea) $file->set('id', null); $file->set('created_date', time()); $file->set('project_id', $this->project->id); $file->save(); //copy the actual file if (file_exists($file_to_copy_url)) { copy($file_to_copy_url, $paths['upload_path'] . $file->name); } } }
function action() { $FileManager =& $this->_Parent->ExtensionManager->create('filemanager'); $file = new File(DOCROOT . $FileManager->getStartLocation() . $_GET['file']); if (isset($_POST['action']['save'])) { $fields = $_POST['fields']; $file->setName($fields['name']); if (isset($fields['contents'])) { $file->setContents($fields['contents']); } $file->setPermissions($fields['permissions']); $relpath = str_replace(DOCROOT . $FileManager->getStartLocation(), NULL, dirname($_GET['file'])); if ($file->isWritable()) { redirect($FileManager->baseURL() . 'properties/?file=' . rtrim(dirname($_GET['file']), '/') . '/' . $file->name() . '&result=saved'); } else { redirect($FileManager->baseURL() . 'browse/' . $relpath); } } elseif (isset($_POST['action']['delete'])) { General::deleteFile($file->path() . '/' . $file->name()); $relpath = str_replace(DOCROOT . $FileManager->getStartLocation(), NULL, dirname($_GET['file'])); redirect($FileManager->baseURL() . 'browse/' . $relpath); } }
function handle($args) { common_debug("in oembed api action"); $url = $args['url']; if (substr(strtolower($url), 0, strlen(common_root_url())) == strtolower(common_root_url())) { $path = substr($url, strlen(common_root_url())); $r = Router::get(); $proxy_args = $r->map($path); if (!$proxy_args) { // TRANS: Server error displayed in oEmbed action when path not found. // TRANS: %s is a path. $this->serverError(sprintf(_('"%s" not found.'), $path), 404); } $oembed = array(); $oembed['version'] = '1.0'; $oembed['provider_name'] = common_config('site', 'name'); $oembed['provider_url'] = common_root_url(); switch ($proxy_args['action']) { case 'shownotice': $oembed['type'] = 'link'; $id = $proxy_args['notice']; $notice = Notice::staticGet($id); if (empty($notice)) { // TRANS: Server error displayed in oEmbed action when notice not found. // TRANS: %s is a notice. $this->serverError(sprintf(_("Notice %s not found."), $id), 404); } $profile = $notice->getProfile(); if (empty($profile)) { // TRANS: Server error displayed in oEmbed action when notice has not profile. $this->serverError(_('Notice has no profile.'), 500); } $authorname = $profile->getFancyName(); // TRANS: oEmbed title. %1$s is the author name, %2$s is the creation date. $oembed['title'] = sprintf(_('%1$s\'s status on %2$s'), $authorname, common_exact_date($notice->created)); $oembed['author_name'] = $authorname; $oembed['author_url'] = $profile->profileurl; $oembed['url'] = $notice->url ? $notice->url : $notice->uri; $oembed['html'] = $notice->rendered; break; case 'attachment': $id = $proxy_args['attachment']; $attachment = File::staticGet($id); if (empty($attachment)) { // TRANS: Server error displayed in oEmbed action when attachment not found. // TRANS: %d is an attachment ID. $this->serverError(sprintf(_('Attachment %s not found.'), $id), 404); } if (empty($attachment->filename) && ($file_oembed = File_oembed::staticGet('file_id', $attachment->id))) { // Proxy the existing oembed information $oembed['type'] = $file_oembed->type; $oembed['provider'] = $file_oembed->provider; $oembed['provider_url'] = $file_oembed->provider_url; $oembed['width'] = $file_oembed->width; $oembed['height'] = $file_oembed->height; $oembed['html'] = $file_oembed->html; $oembed['title'] = $file_oembed->title; $oembed['author_name'] = $file_oembed->author_name; $oembed['author_url'] = $file_oembed->author_url; $oembed['url'] = $file_oembed->url; } else { if (substr($attachment->mimetype, 0, strlen('image/')) == 'image/') { $oembed['type'] = 'photo'; if ($attachment->filename) { $filepath = File::path($attachment->filename); $gis = @getimagesize($filepath); if ($gis) { $oembed['width'] = $gis[0]; $oembed['height'] = $gis[1]; } else { // TODO Either throw an error or find a fallback? } } $oembed['url'] = $attachment->url; $thumb = $attachment->getThumbnail(); if ($thumb) { $oembed['thumbnail_url'] = $thumb->url; $oembed['thumbnail_width'] = $thumb->width; $oembed['thumbnail_height'] = $thumb->height; } } else { $oembed['type'] = 'link'; $oembed['url'] = common_local_url('attachment', array('attachment' => $attachment->id)); } } if ($attachment->title) { $oembed['title'] = $attachment->title; } break; default: // TRANS: Server error displayed in oEmbed request when a path is not supported. // TRANS: %s is a path. $this->serverError(sprintf(_('"%s" not supported for oembed requests.'), $path), 501); } switch ($args['format']) { case 'xml': $this->init_document('xml'); $this->elementStart('oembed'); $this->element('version', null, $oembed['version']); $this->element('type', null, $oembed['type']); if ($oembed['provider_name']) { $this->element('provider_name', null, $oembed['provider_name']); } if ($oembed['provider_url']) { $this->element('provider_url', null, $oembed['provider_url']); } if ($oembed['title']) { $this->element('title', null, $oembed['title']); } if ($oembed['author_name']) { $this->element('author_name', null, $oembed['author_name']); } if ($oembed['author_url']) { $this->element('author_url', null, $oembed['author_url']); } if ($oembed['url']) { $this->element('url', null, $oembed['url']); } if ($oembed['html']) { $this->element('html', null, $oembed['html']); } if ($oembed['width']) { $this->element('width', null, $oembed['width']); } if ($oembed['height']) { $this->element('height', null, $oembed['height']); } if ($oembed['cache_age']) { $this->element('cache_age', null, $oembed['cache_age']); } if ($oembed['thumbnail_url']) { $this->element('thumbnail_url', null, $oembed['thumbnail_url']); } if ($oembed['thumbnail_width']) { $this->element('thumbnail_width', null, $oembed['thumbnail_width']); } if ($oembed['thumbnail_height']) { $this->element('thumbnail_height', null, $oembed['thumbnail_height']); } $this->elementEnd('oembed'); $this->end_document('xml'); break; case 'json': case '': $this->init_document('json'); print json_encode($oembed); $this->end_document('json'); break; default: // TRANS: Error message displaying attachments. %s is a raw MIME type (eg 'image/png') $this->serverError(sprintf(_('Content type %s not supported.'), $apidata['content-type']), 501); } } else { // TRANS: Error message displaying attachments. %s is the site's base URL. $this->serverError(sprintf(_('Only %s URLs over plain HTTP please.'), common_root_url()), 404); } }
public static function merge($path, $name = null, $addon = "", $call = null) { $path = is_string($path) && strpos($path, ';') !== false ? explode(';', $path) : (array) $path; $the_path = ASSET . DS . File::path($name); $the_path_log = SYSTEM . DS . 'log' . DS . 'asset.' . str_replace(array(ASSET . DS, DS), array("", '__'), $the_path) . '.log'; $is_valid = true; if (!file_exists($the_path_log)) { $is_valid = false; } else { $the_path_time = explode("\n", file_get_contents($the_path_log)); if (count($the_path_time) !== count($path)) { $is_valid = false; } else { foreach ($the_path_time as $i => $time) { $p = self::path($path[$i]); if (!file_exists($p) || (int) filemtime($p) !== (int) $time) { $is_valid = false; break; } } } } $time = ""; $content = ""; $e = File::E($name); if (!file_exists($the_path) || !$is_valid) { if (Text::check($e)->in(array('gif', 'jpeg', 'jpg', 'png'))) { foreach ($path as $p) { if (!self::ignored($p)) { $p = self::path($p); if (file_exists($p)) { $time .= filemtime($p) . "\n"; } } } File::write(trim($time))->saveTo($the_path_log); Image::take($path)->merge()->saveTo($the_path); } else { foreach ($path as $p) { if (!self::ignored($p)) { $p = self::path($p); if (file_exists($p)) { $time .= filemtime($p) . "\n"; $c = file_get_contents($p); if (strpos(File::B($p), '.min.') === false) { if (strpos(File::B($the_path), '.min.css') !== false) { $content .= Converter::detractShell($c) . "\n"; } else { if (strpos(File::B($the_path), '.min.js') !== false) { $content .= Converter::detractSword($c) . "\n"; } else { $content .= $c . "\n\n"; } } } else { $content .= $c . "\n\n"; } } } } File::write(trim($time))->saveTo($the_path_log); File::write(trim($content))->saveTo($the_path); } } if (is_null($call)) { $call = Mecha::alter($e, array('css' => 'stylesheet', 'js' => 'javascript', 'gif' => 'image', 'jpeg' => 'image', 'jpg' => 'image', 'png' => 'image')); } return call_user_func_array('self::' . $call, array($the_path, $addon)); }
/** * @return mixed false on failure, HTML fragment string on success */ protected function scrubHtmlFile(File $attachment) { $path = File::path($attachment->filename); if (!file_exists($path) || !is_readable($path)) { common_log(LOG_ERR, "Missing local HTML attachment {$path}"); return false; } $raw = file_get_contents($path); // Normalize... $dom = new DOMDocument(); if (!$dom->loadHTML($raw)) { common_log(LOG_ERR, "Bad HTML in local HTML attachment {$path}"); return false; } // Remove <script>s or htmlawed will dump their contents into output! // Note: removing child nodes while iterating seems to mess things up, // hence the double loop. $scripts = array(); foreach ($dom->getElementsByTagName('script') as $script) { $scripts[] = $script; } foreach ($scripts as $script) { common_log(LOG_DEBUG, $script->textContent); $script->parentNode->removeChild($script); } // Trim out everything outside the body... $body = $dom->saveHTML(); $body = preg_replace('/^.*<body[^>]*>/is', '', $body); $body = preg_replace('/<\\/body[^>]*>.*$/is', '', $body); require_once INSTALLDIR . '/extlib/htmLawed/htmLawed.php'; $config = array('safe' => 1, 'deny_attribute' => 'id,style,on*', 'comment' => 1); // remove comments $scrubbed = htmLawed($body, $config); return $scrubbed; }
if ($request = Request::post()) { Guardian::checkToken($request['token']); $info_path = array(); $is_folder_or_file = count($deletes) === 1 && is_dir(ASSET . DS . $deletes[0]) ? 'folder' : 'file'; foreach ($deletes as $file_to_delete) { $_path = ASSET . DS . $file_to_delete; $info_path[] = $_path; File::open($_path)->delete(); } $P = array('data' => array('files' => $info_path)); Notify::success(Config::speak('notify_' . $is_folder_or_file . '_deleted', '<code>' . implode('</code>, <code>', $deletes) . '</code>')); Weapon::fire('on_asset_update', array($P, $P)); Weapon::fire('on_asset_destruct', array($P, $P)); Guardian::kick($config->manager->slug . '/asset/1' . $p); } else { Notify::warning(count($deletes) === 1 ? Config::speak('notify_confirm_delete_', '<code>' . File::path($name) . '</code>') : $speak->notify_confirm_delete); } Shield::lot('segment', 'asset')->attach('manager', false); }); /** * Multiple Asset Killer * --------------------- */ Route::accept($config->manager->slug . '/asset/kill', function ($path = "") use($config, $speak) { if ($request = Request::post()) { Guardian::checkToken($request['token']); if (!isset($request['selected'])) { Notify::error($speak->notify_error_no_files_selected); Guardian::kick($config->manager->slug . '/asset/1'); } $files = array();
/** * Rewrite and resize a placeholder image element to match the uploaded * file. If the holder is smaller than the file, the file is scaled to fit * with correct aspect ratio (but will be loaded at full resolution). * * @param DOMElement $img * @param MediaFile $media */ private function insertImage($img, $media) { $img->setAttribute('src', $media->fileRecord->url); $holderWidth = intval($img->getAttribute('width')); $holderHeight = intval($img->getAttribute('height')); $path = File::path($media->filename); $imgInfo = getimagesize($path); if ($imgInfo) { $origWidth = $imgInfo[0]; $origHeight = $imgInfo[1]; list($width, $height) = $this->sizeBox($origWidth, $origHeight, $holderWidth, $holderHeight); $img->setAttribute('width', $width); $img->setAttribute('height', $height); } }
$Admin->Password = Admin::pwd($argv[3]); $Admin->IsSuper = 1; if ($Admin->save()) { echo " - OK\n"; } else { echo " - FAILED\n"; } } else { echo "Login is not set\n"; } break; case 'images': $Product = new Product(); foreach ($Product->findList() as $Product) { $f1 = File::path($Product, 1); $f2 = File::path($Product, 2); File::restore($f2); copy($f1, $f2); File::upload($Product, $f2); } break; case 'add': // the function adds controller + view + model if it does not exist if (!$argv[2]) { Console::writeln("Define controller"); break; } if (!$argv[3]) { Console::writeln("Define model"); break; }
Weapon::fire(array('on_shield_update', 'on_shield_repair'), array($G, $P)); Guardian::kick($config->manager->slug . '/shield/' . $folder . ($file !== false ? '/repair/file:' . File::url($name) : "")); } } Shield::lot(array('segment' => 'shield', 'folder' => $folder, 'path' => $path, 'content' => $content))->attach('manager'); }); /** * Shield Killer * ------------- */ Route::accept(array($config->manager->slug . '/shield/kill/id:(:any)', $config->manager->slug . '/shield/(:any)/kill/file:(:all)'), function ($folder = false, $file = false) use($config, $speak) { if (!Guardian::happy(1) || $folder === "") { Shield::abort(); } $info = Shield::info($folder); $path = $file !== false ? File::path($file) : false; if ($file !== false) { if (!($_file = File::exist(SHIELD . DS . $folder . DS . $path))) { Shield::abort(); // File not found! } } else { if (!($_file = File::exist(SHIELD . DS . $folder))) { Shield::abort(); // Folder not found! } } Config::set(array('page_title' => $speak->deleting . ': ' . ($file !== false ? File::B($file) : $info->title) . $config->title_separator . $config->manager->title, 'page' => $info, 'cargo' => 'kill.shield.php')); if ($request = Request::post()) { Guardian::checkToken($request['token']); $P = array('data' => array('path' => $_file));
/** * ========================================================== * RENDER A SHIELD CHUNK * ========================================================== * * -- CODE: ------------------------------------------------- * * Shield::chunk('header'); * * ---------------------------------------------------------- * * Shield::chunk('header', array('title' => 'Yo!')); * * ---------------------------------------------------------- * */ public static function chunk($name, $fallback = false, $buffer = true) { $path__ = File::path($name); $G = array('data' => array('name' => $name)); if (is_array($fallback)) { self::$lot = array_merge(self::$lot, $fallback); $fallback = false; } $path__ = Filter::apply('chunk:path', self::path($path__, $fallback)); $G['data']['lot'] = self::$lot; $G['data']['path'] = $path__; $out = ""; if ($path__) { // Begin chunk Weapon::fire('chunk_lot_before', array($G, $G)); extract(Filter::apply('chunk:lot', self::$lot)); Weapon::fire('chunk_lot_after', array($G, $G)); Weapon::fire('chunk_before', array($G, $G)); if ($buffer) { ob_start(function ($content) use($path__, &$out) { $content = Filter::apply('chunk:input', $content, $path__); $out = Filter::apply('chunk:output', $content, $path__); return $out; }); require $path__; ob_end_flush(); } else { require $path__; } $G['data']['content'] = $out; // End chunk Weapon::fire('chunk_after', array($G, $G)); } }
/** * Store the full-length scrubbed HTML of a remote notice to an attachment * file on our server. We'll link to this at the end of the cropped version. * * @param string $title plaintext for HTML page's title * @param string $rendered HTML fragment for HTML page's body * @return File */ function saveHTMLFile($title, $rendered) { $final = sprintf("<!DOCTYPE html>\n" . '<html><head>' . '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . '<title>%s</title>' . '</head>' . '<body>%s</body></html>', htmlspecialchars($title), $rendered); $filename = File::filename($this->localProfile(), 'ostatus', 'text/html'); $filepath = File::path($filename); $fileurl = File::url($filename); file_put_contents($filepath, $final); $file = new File(); $file->filename = $filename; $file->urlhash = File::hashurl($fileurl); $file->url = $fileurl; $file->size = filesize($filepath); $file->date = time(); $file->mimetype = 'text/html'; $file_id = $file->insert(); if ($file_id === false) { common_log_db_error($file, "INSERT", __FILE__); // TRANS: Server exception. throw new ServerException(_m('Could not store HTML content of long post as file.')); } return $file; }
<?php $hooks = array($files, $segment); echo $messages; if ($files) { ?> <ul> <?php foreach ($files as $file) { ?> <li><?php echo ASSET . DS . File::path(Text::parse($file, '->decoded_url')); ?> </li> <?php } ?> </ul> <?php } ?> <form class="form-kill form-asset" id="form-kill" action="<?php echo $config->url_current . str_replace('&', '&', $config->url_query); ?> " method="post"> <?php Weapon::fire('action_before', $hooks); ?> <?php echo Jot::button('action', $speak->yes); ?>
/** * Handle the request * * @return void */ protected function handle() { parent::handle(); $profile = $this->user->getProfile(); $base64img = $this->img; if (stristr($base64img, 'image/jpeg')) { $base64img_mime = 'image/jpeg'; } elseif (stristr($base64img, 'image/png')) { // should convert to jpg here!! $base64img_mime = 'image/png'; } $base64img = str_replace('data:image/jpeg;base64,', '', $base64img); $base64img = str_replace('data:image/png;base64,', '', $base64img); $base64img = str_replace(' ', '+', $base64img); $base64img_hash = md5($base64img); $base64img = base64_decode($base64img); $base64img_basename = basename('bg'); $base64img_filename = File::filename($profile, $base64img_basename, $base64img_mime); $base64img_path = File::path($base64img_filename); $base64img_success = file_put_contents($base64img_path, $base64img); $base64img_mimetype = MediaFile::getUploadedMimeType($base64img_path, $base64img_filename); $mediafile = new MediaFile($profile, $base64img_filename, $base64img_mimetype); $imagefile = new ImageFile($mediafile->fileRecord->id, File::path($mediafile->filename)); $imagefile->resizeTo(File::path($mediafile->filename), array('width' => 1280, 'height' => 1280, 'x' => $this->cropX, 'y' => $this->cropY, 'w' => $this->cropW, 'h' => $this->cropH)); $result['url'] = File::url($mediafile->filename); Profile_prefs::setData($profile, 'qvitter', 'background_image', $result['url']); $this->initDocument('json'); $this->showJsonObjects($result); $this->endDocument('json'); }
static function fromFilehandle($fh, $user) { $stream = stream_get_meta_data($fh); if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) { // Should never actually get here // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota. throw new ClientException(_('File exceeds user\'s quota.')); return; } $mimetype = MediaFile::getUploadedFileType($fh); $filename = null; if (isset($mimetype)) { $filename = File::filename($user->getProfile(), "email", $mimetype); $filepath = File::path($filename); $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664); if (!$result) { // TRANS: Client exception thrown when a file upload operation fails because the file could // TRANS: not be moved from the temporary folder to the permanent file location. throw new ClientException(_('File could not be moved to destination directory.' . $stream['uri'] . ' ' . $filepath)); } } else { // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME // TRANS: type of the uploaded file could not be determined. throw new ClientException(_('Could not determine file\'s MIME type.')); return; } return new MediaFile($user, $filename, $mimetype); }
/** * 格納されたログを出力する */ public static final function flush() { if (self::isPublishLevel() >= 4) { self::$LOG[] = new self(4, "use memory: " . number_format(memory_get_usage()) . "byte / " . number_format(memory_get_peak_usage()) . "byte"); self::$LOG[] = new self(4, sprintf("------- end logger ( %f sec ) ------- ", microtime(true) - (double) self::$START)); } if (!empty(self::$LOG)) { $level = array("none", "error", "warning", "info", "debug"); foreach (self::$LOG as $log) { $value = $log->value(); if (Rhaco::def("core.Log@expression") === true) { ob_start(); var_dump($value); $value = substr(ob_get_clean(), 0, -1); } $value = "[" . $level[$log->level()] . " " . $log->time() . "]:[" . $log->file() . ":" . $log->line() . "] " . $value . "\n"; if (self::$DISP_LEVEL >= $log->level() && self::$DISP) { print $value; } if (self::$FILE_LEVEL >= $log->level()) { if (empty(self::$PATH)) { throw new Exception("not found path"); } File::append(sprintf("%s/%s.log", File::path(self::$PATH), date("Ymd")), $value); } self::call_filter($level[$log->level()], $log); } self::call_filter("flush", self::$LOG); } self::$LOG = array(); }
$length = Request::get('length', 7); $font = Request::get('font', 'special-elite-regular.ttf', false); $text = substr(str_shuffle($str), 0, $length); Session::set(Guardian::$captcha, $text); if ($bg !== 'false' && ($bg = Converter::HEX2RGB($bg))) { $bg = array($bg['r'], $bg['g'], $bg['b'], $bg['a']); } else { $bg = $bg !== 'false' ? array(51, 51, 51, 1) : array(0, 0, 0, 0); } if ($color = Converter::HEX2RGB($color)) { $color = array($color['r'], $color['g'], $color['b'], $color['a']); } else { $color = array(255, 255, 170, 1); } $image = imagecreatetruecolor($width, $height); $font = strpos($font, '/') === false ? ASSET . DS . '__captcha' . DS . $font : ROOT . DS . File::path($font); imagefill($image, 0, 0, 0x7fff0000); imagealphablending($image, true); imagesavealpha($image, true); $bg = imagecolorallocatealpha($image, $bg[0], $bg[1], $bg[2], 127 - $bg[3] * 127); $color = imagecolorallocatealpha($image, $color[0], $color[1], $color[2], 127 - $color[3] * 127); imagefilledrectangle($image, 0, 0, $width, $height, $bg); // center the image text ... $xi = imagesx($image); $yi = imagesy($image); $box = imagettfbbox($size, 0, $font, $text); $xr = abs(max($box[2], $box[4])); $yr = abs(max($box[5], $box[7])); $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
/** * Handle the request * * @return void */ protected function handle() { parent::handle(); $profile = $this->user->getProfile(); $base64img = $this->img; if (stristr($base64img, 'image/jpeg')) { $base64img_mime = 'image/jpeg'; } elseif (stristr($base64img, 'image/png')) { // should convert to jpg here!! $base64img_mime = 'image/png'; } $base64img = str_replace('data:image/jpeg;base64,', '', $base64img); $base64img = str_replace('data:image/png;base64,', '', $base64img); $base64img = str_replace(' ', '+', $base64img); $base64img_hash = md5($base64img); $base64img = base64_decode($base64img); $base64img_basename = basename('avatar'); $base64img_filename = File::filename($profile, $base64img_basename, $base64img_mime); $base64img_path = File::path($base64img_filename); $base64img_success = file_put_contents($base64img_path, $base64img); $base64img_mimetype = MediaFile::getUploadedMimeType($base64img_path, $base64img_filename); $mediafile = new MediaFile($profile, $base64img_filename, $base64img_mimetype); $imagefile = new ImageFile($mediafile->fileRecord->id, File::path($mediafile->filename)); $imagefile->resizeTo(File::path($mediafile->filename), array('width' => $this->cropW, 'height' => $this->cropH, 'x' => $this->cropX, 'y' => $this->cropY, 'w' => $this->cropW, 'h' => $this->cropH)); $type = $imagefile->preferredType(); $filename = Avatar::filename($profile->id, image_type_to_extension($type), null, common_timestamp()); $filepath = Avatar::path($filename); $imagefile->copyTo($filepath); $profile = $this->user->getProfile(); $profile->setOriginal($filename); $mediafile->delete(); $twitter_user = $this->twitterUserArray($profile, true); $this->initDocument('json'); $this->showJsonObjects($twitter_user); $this->endDocument('json'); }
} Config::set(array('page_title' => $speak->deleting . ': ' . ($path ? File::B($file) : $info['title']) . $config->title_separator . $config->manager->title, 'files' => Get::files(SHIELD . DS . $folder, '*'), 'cargo' => DECK . DS . 'workers' . DS . 'kill.shield.php')); if ($request = Request::post()) { Guardian::checkToken($request['token']); $P = array('data' => array('path' => $file)); File::open($file)->delete(); if ($path) { Notify::success(Config::speak('notify_file_deleted', '<code>' . File::B($path) . '</code>')); } else { Notify::success(Config::speak('notify_success_deleted', $speak->shield)); } Weapon::fire('on_shield_update', array($P, $P)); Weapon::fire('on_shield_destruct', array($P, $P)); Guardian::kick($config->manager->slug . '/shield' . ($path ? '/' . $folder : "")); } else { Notify::warning(Config::speak('notify_confirm_delete_', $path ? '<code>' . File::path($path) . '</code>' : '<strong>' . $info['title'] . '</strong>')); } Shield::lot(array('segment' => 'shield', 'the_shield' => $folder, 'the_name' => $path, 'the_info' => $info))->attach('manager', false); }); /** * Shield Attacher * --------------- */ Route::accept($config->manager->slug . '/shield/(attach|eject)/id:(:any)', function ($path = "", $slug = "") use($config, $speak) { $new_config = Get::state_config(); $new_config['shield'] = $path === 'attach' ? $slug : 'normal'; File::serialize($new_config)->saveTo(STATE . DS . 'config.txt', 0600); $G = array('data' => array('id' => $slug, 'action' => $path)); $mode = $path === 'eject' ? 'eject' : 'mount'; Notify::success(Config::speak('notify_success_updated', $speak->shield)); Weapon::fire('on_shield_update', array($G, $G));
/** * ========================================================================== * GET ADJACENT FILE(S) * ========================================================================== * * -- CODE: ----------------------------------------------------------------- * * $files = Get::adjacentFiles( * 'some/path', * 'txt', * 'ASC', * 'update' * ); * * -------------------------------------------------------------------------- * */ public static function adjacentFiles($folder = ASSET, $extensions = '*', $order = 'DESC', $sorter = 'path', $filter = "", $inclusive = false) { if (!file_exists($folder)) { return false; } $results = array(); $results_inclusive = array(); $extension = str_replace(' ', "", $extensions); $folder = rtrim(File::path($folder), DS); $files = strpos($extension, ',') !== false ? glob($folder . DS . '*.{' . $extension . '}', GLOB_NOSORT | GLOB_BRACE) : glob($folder . DS . '*.' . $extension, GLOB_NOSORT); if ($inclusive) { $files = array_merge($files, glob($folder . DS . '.*', GLOB_NOSORT)); } foreach ($files as $file) { if (is_file($file)) { if (!$filter) { $results_inclusive[] = File::inspect($file); } else { if (strpos(File::B($file), $filter) !== false) { $results_inclusive[] = File::inspect($file); } } $_file = str_replace($folder . DS, "", $file); if (strpos($_file, '__') !== 0 && strpos($_file, '.') !== 0) { if (!$filter) { $results[] = File::inspect($file); } else { if (strpos(File::B($file), $filter) !== false) { $results[] = File::inspect($file); } } } } } if ($inclusive) { unset($results); return !empty($results_inclusive) ? Mecha::eat($results_inclusive)->order($order, $sorter)->vomit() : false; } else { unset($results_inclusive); return !empty($results) ? Mecha::eat($results)->order($order, $sorter)->vomit() : false; } }
/** * * @param array $uploadedFileArray * @param Folder $destinationFolder * @param boolean $overwrite If false this function will append a number. eg. Filename (1).jpg * @return File[] */ public static function moveUploadedFiles($uploadedFileArray, $destinationFolder, $overwrite = false) { if (!is_array($uploadedFileArray['tmp_name'])) { $uploadedFileArray['tmp_name'] = array($uploadedFileArray['tmp_name']); $uploadedFileArray['name'] = array($uploadedFileArray['name']); } $files = array(); for ($i = 0; $i < count($uploadedFileArray['tmp_name']); $i++) { if (is_uploaded_file($uploadedFileArray['tmp_name'][$i])) { $destinationFile = new File($destinationFolder->path() . '/' . $uploadedFileArray['name'][$i]); if (!$overwrite) { $destinationFile->appendNumberToNameIfExists(); } if (move_uploaded_file($uploadedFileArray['tmp_name'][$i], $destinationFile->path())) { $destinationFile->setDefaultPermissions(); $files[] = $destinationFile; } } } return $files; }
}); Route::post($config->manager->slug . '/snippet/ignite', function () use($config, $speak) { $request = Request::post(); $id = time(); Guardian::checkToken($request['token']); if (trim($request['name']) === "") { $request['name'] = $id . '.txt'; // empty file name } $_path = Text::parse(sprintf($request['name'], $id), '->safe_path_name'); $e = File::E($_path, false); if ($e !== 'txt' && $e !== 'php') { $e = 'txt'; $_path .= '.txt'; } $_path_ = File::path($_path); $file = ASSET . DS . '__snippet' . DS . $e . DS . $_path; if (File::exist($file)) { // file already exists Notify::error(Config::speak('notify_file_exist', '<code>' . $_path_ . '</code>')); } if (trim($request['content']) === "") { // empty file content Notify::error($speak->notify_error_content_empty); } if (!Notify::errors()) { $recent = array_slice(File::open(CACHE . DS . 'plugin.snippet.cache')->unserialize(), 0, $config->per_page); File::serialize(array_merge(array($_path), $recent))->saveTo(CACHE . DS . 'plugin.snippet.cache', 0600); $url = $config->manager->slug . '/asset/repair/file:__snippet/' . $e . '/' . File::url($_path) . '?path=' . urlencode(rtrim('__snippet/' . $e . '/' . File::D(File::url($_path)), '/')); File::write($request['content'])->saveTo($file, 0600); Notify::success(Config::speak('notify_file_created', '<code>' . $_path_ . '</code>' . (!isset($request['redirect']) ? ' <a class="pull-right" href="' . $config->url . '/' . $url . '" target="_blank">' . Jot::icon('pencil') . ' ' . $speak->edit . '</a>' : "")));