function set_fromhost() { global $proxyIPs; global $fullfromhost; global $fromhost; @($fullfromhost = $_SERVER["HTTP_X_FORWARDED_FOR"]); if ($fullfromhost == "") { @($fullfromhost = $_SERVER["REMOTE_ADDR"]); $fromhost = $fullfromhost; } else { $ips = explode(",", $fullfromhost); $c = count($ips); if ($c > 1) { $fromhost = trim($ips[$c - 1]); if (isset($proxyIPs) && in_array($fromhost, $proxyIPs)) { $fromhost = $ips[$c - 2]; } } else { $fromhost = $fullfromhost; } } if ($fromhost == "") { $fromhost = "127.0.0.1"; $fullfromhost = "127.0.0.1"; } if (defined("IPV6_LEGACY_IPV4_DISPLAY")) { if (strchr($fromhost, '.') && ($p = strrchr($fromhost, ':'))) { $fromhost = substr($p, 1); } } //sometimes,fromhost has strang space bbs_setfromhost(trim($fromhost), trim($fullfromhost)); }
public function onMove($typeProgress, $module, $name, $copy = FALSE) { $imgs = $this->getConfig('img'); foreach ($imgs as $img) { $oldPath = $img['name']; $imagePath = substr(strstr($oldPath, '/files/'), 7); $newPath = $module . '/files/' . $imagePath; if ($oldPath !== $newPath) { if (stream_resolve_include_path($newPath) !== FALSE) { /* check if an image with this path already exists in profile */ $fileInfo = pathinfo($imagePath); $extension = strtolower($fileInfo['extension']); $filename = $fileInfo['filename']; /* allow to not overload filename with name_0_3_2_0 ... */ $generatedPart = strrchr($filename, '_'); if ($generatedPart !== FALSE && is_numeric(substr($generatedPart, 1))) { $filename = substr($fileInfo['filename'], 0, -strlen($generatedPart)); } $nbn = 0; while (stream_resolve_include_path($newPath)) { $imagePath = $filename . '_' . $nbn . '.' . $extension; $newPath = $module . '/files/' . $imagePath; $nbn++; } } $this->setConfig('imgPath', $newPath); \tools::file_put_contents(PROFILE_PATH . $newPath, file_get_contents($oldPath, FILE_USE_INCLUDE_PATH)); } } }
/** * Modify the output of the field on the fronted profile. * * @since 1.2.0 * @param string $value the value of the field. * @param object $field field details. * @return string the formatted field value. */ public static function output_html($value, $field) { $files = $value; $output = ''; // Display files if they're images. if (wpaam_is_multi_array($files)) { foreach ($files as $key => $file) { $extension = !empty($extension) ? $extension : substr(strrchr($file['url'], '.'), 1); if (3 !== strlen($extension) || in_array($extension, array('jpg', 'gif', 'png', 'jpeg', 'jpe'))) { $output .= '<span class="wpaam-uploaded-file-preview"><img src="' . esc_url($file['url']) . '" /></span>'; } else { $output .= ' <span class="wpaam-uploaded-file-name"><code>' . esc_html(basename($file['url'])) . '</code></span>'; } } // We have a single file. } else { $extension = !empty($extension) ? $extension : substr(strrchr($files['url'], '.'), 1); if (3 !== strlen($extension) || in_array($extension, array('jpg', 'gif', 'png', 'jpeg', 'jpe'))) { $output .= '<span class="wpaam-uploaded-file-preview"><img src="' . esc_url($files['url']) . '" /></span>'; } else { $output .= ' <span class="wpaam-uploaded-file-name"><code>' . esc_html(basename($files['url'])) . '</code></span>'; } } return $output; }
/** * import images * * @access public * @param $product, $image, $sku * @return void * */ private function importImages($product, $image, $sku) { $image_url = $image['img']; $image_url = str_replace("https://", "http://", $image_url); $image_type = substr(strrchr($image_url, "."), 1); $split = explode("?", $image_type); $image_type = $split[0]; $imgName = basename($image_url); $imgName = str_replace('.' . $image_type, "", $imgName); $filename = md5($imgName . $sku) . '.' . $image_type; $dirPath = Mage::getBaseDir('media') . DS . 'import'; if (!file_exists($dirPath)) { mkdir($dirPath, 0777, true); } $filepath = $dirPath . DS . $filename; $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $image_url); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Cirkel'); $query = curl_exec($curl_handle); curl_close($curl_handle); file_put_contents($filepath, $query); if (file_exists($filepath)) { $attrIMG = array(); if (array_key_exists('main', $image)) { if ($image['main'] == true) { $attrIMG = array('image', 'thumbnail', 'small_image'); } } $productMG = Mage::getModel('catalog/product')->loadByAttribute('sku', $product->getSku()); $productMG->addImageToMediaGallery($filepath, $attrIMG, false, false); $productMG->save(); } }
public function send($data, $name, $local) { if (!empty($data)) { //echo 'component: <pre>'; print_r ($data); echo '</pre>'; //echo '<br>'.count($data); //exit; /*if ( count( $data ) > $this->max_files ) { throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1); }*/ $file = $data; //foreach ($data as $file) { //echo 'component file: <pre>'; print_r ($file); echo '</pre>'; //echo '<br>'.count($data); //exit; $filename = $file['name']; $file_tmp_name = $file['tmp_name']; $dir = WWW_ROOT . 'uploads' . DS . $local; $allowed = array('png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'txt', 'css', 'html'); if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) { throw new InternalErrorException("Error Processing Request.", 1); } elseif (is_uploaded_file($file_tmp_name)) { //move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid().'-'.$filename); move_uploaded_file($file_tmp_name, $dir . DS . $name); } //} //exit; } }
/** * {@inheritdoc} */ public function extract($command) { $className = substr(strrchr(get_class($command), '\\'), 1); return preg_replace_callback('/(^|[a-z])([A-Z])/', function ($s) { return strtolower(strlen($s[1]) ? "{$s['1']}_{$s['2']}" : "{$s['2']}"); }, $className); }
/** * CDN图片域名 * * @param string $img 图片地址 * @param string $path 附加路径 * @return string 完整URL图片地址 */ function cdn_img_url($img, $path = '/') { if (empty($img) || strpos($img, '://') !== false) { return $img; } if ($img[0] == '/') { $path = ''; } /** * 当使用本机时,就不用CDN处理了 */ if (isset($_GET['local'])) { return "{$path}{$img}"; } if (USE_ISLOCAL_JS2CSS || USE_ISLOCAL_IMG) { $file_ext = strtolower(strrchr($img, '.')); if (USE_ISLOCAL_JS2CSS && ($file_ext == '.js' || $file_ext == '.css')) { return "{$path}{$img}"; } if (USE_ISLOCAL_IMG && ($file_ext == '.jpg' || $file_ext == '.jpeg' || $file_ext == '.gif' || $file_ext == '.swf' || $file_ext == '.png')) { return "{$path}{$img}"; } } /** * 分服务器加载 */ static $img_hosts = null; static $img_count = null; if (is_null($img_hosts)) { $img_hosts = json_decode(IMG_URLS, true); $img_count = count($img_hosts); } $key = abs(crc32($img)) % $img_count; return "{$img_hosts[$key]}{$path}{$img}"; }
private function _getParentContentData() { $data = $this->getData(); $ids = array(); while ($data && !$data->inherits) { $ids[] = strrchr($data->componentId, '-'); $data = $data->parent; } while ($data) { if ($data->inherits) { $d = $data; foreach (array_reverse($ids) as $id) { $d = $d->getChildComponent($id); } if (!$d) { break; } if ($d->componentClass != $this->getData()->componentClass) { return $d; } } $data = $data->parent; } return null; }
function upload_originales($fichier, $destination, $ext) { $sortie = array(); // récupération du nom d'origine $nom_origine = $fichier['name']; // récupération de l'extension du fichier mise en minuscule et sans le . $extension_origine = substr(strtolower(strrchr($nom_origine, '.')), 1); // si l'extension ne se trouve pas (!) dans le tableau contenant les extensions autorisées if (!in_array($extension_origine, $ext)) { // envoi d'une erreur et arrêt de la fonction return "Erreur : Extension non autorisée"; } // si l'extension est valide mais de type jpeg if ($extension_origine === "jpeg") { $extension_origine = "jpg"; } // création du nom final (appel de la fonction chaine_hasard, pour la chaine de caractère aléatoire) $nom_final = chaine_hasard(25); // on a besoin du nom final dans le tableau $sortie si la fonction réussit $sortie['poids'] = filesize($fichier['tmp_name']); $sortie['largeur'] = getimagesize($fichier['tmp_name'])[0]; $sortie['hauteur'] = getimagesize($fichier['tmp_name'])[1]; $sortie['nom'] = $nom_final; $sortie['extension'] = $extension_origine; // on déplace l'image du dossier temporaire vers le dossier 'originales' avec le nom de fichier complet if (@move_uploaded_file($fichier['tmp_name'], $destination . $nom_final . "." . $extension_origine)) { return $sortie; // si erreur } else { return "Erreur lors de l'upload d'image"; } }
function wpui_slide_shortcode($atts, $content = null) { extract(shortcode_atts(array('image' => false, 'image_title' => false), $atts)); if ($image_title) { $imagea = wpui_get_media_item($image_title); } $image = $imagea['image']; if (!$image || !function_exists('getimagesize')) { return false; } if (is_array($imagea)) { $img_title = $imagea['title']; } else { $filename = substr(strrchr($image, '/'), 1); $filename = str_ireplace(strrchr($filename, '.'), '', $filename); $img_title = $filename; } $samp = getimagesize($image); if (!is_array($samp)) { return "Not a valid image."; } $output = ''; $output .= '<h3 class="wp-tab-title">' . $imagea['title'] . '</h3>'; $output .= '<div class="wpui-slide wp-tab-content">'; $output .= '<img src="' . $image . '" />'; $output .= '<div class="wpui_image_description">' . $content . '</div>'; $output .= '</div><!-- end .wpui-slide -->'; return $output; }
function attach($message,$name,$ctype = '') { // type de contenu non defini if(empty($ctype)){ // on essaie de reconnaitre l'extension switch(strrchr(basename($name), ".")){ case ".gz": $ctype = "application/x-gzip"; break; case ".tgz": $ctype = "application/x-gzip"; break; case ".zip": $ctype = "application/zip"; break; case ".pdf": $ctype = "application/pdf"; break; case ".png": $ctype = "image/png"; break; case ".gif": $ctype = "image/gif"; break; case ".jpg": $ctype = "image/jpeg"; break; case ".txt": $ctype = "text/plain"; break; case ".htm": $ctype = "text/html"; break; case ".html": $ctype = "text/html"; break; default: $ctype = "application/octet-stream"; break; } } $this->parts[] = array ( "ctype" => $ctype, "message" => $message, "encode" => "", "name" => $name ); // fin de fonction }
/** * Convert the token * * @param Zend_Markup_Token $token * @param string $text * * @return string */ public function convert(Zend_Markup_Token $token, $text) { $uri = $text; if (!preg_match('/^([a-z][a-z+\\-.]*):/i', $uri)) { $uri = 'http://' . $uri; } // check if the URL is valid if (!Zend_Markup_Renderer_Html::isValidUri($uri)) { return $text; } if ($token->hasAttribute('alt')) { $alt = $token->getAttribute('alt'); } else { // try to get the alternative from the URL $alt = rtrim($text, '/'); $alt = strrchr($alt, '/'); if (false !== strpos($alt, '.')) { $alt = substr($alt, 1, strpos($alt, '.') - 1); } } // run the URI and alt through htmlentities $uri = htmlentities($uri, ENT_QUOTES, Zend_Markup_Renderer_Html::getEncoding()); $alt = htmlentities($alt, ENT_QUOTES, Zend_Markup_Renderer_Html::getEncoding()); return "<img src=\"{$uri}\" alt=\"{$alt}\"" . Zend_Markup_Renderer_Html::renderAttributes($token) . " />"; }
public function Download($link) { if (!preg_match('@://(?:[^/]+\\.)?tune\\.pk/video/(\\d+)@i', $link, $vid)) { html_error('Video ID not found. Check url.'); } $page = $this->GetPage('http://tune.pk/video/' . $vid[1] . '/'); is_present($page, 'Video does not exist'); is_present($page, '404 Page not found'); if (!preg_match('@var \\s*video_title\\s*=\\s*\'([^\']+)\';@i', $page, $title)) { html_error('Video title not found.'); } $title = str_replace(str_split('<>:"/\\|?*\'@#+~{}[]^'), '_', html_entity_decode(trim($title[1]), ENT_QUOTES)); if (stripos($page, 'watch_video_hd_button') !== false && preg_match('@var \\s*hq_video_file\\s*=\\s*\'(http://[^\']+)\'@i', $page, $dl)) { $title .= '_HQ'; } elseif (!preg_match('@var \\s*normal_video_file\\s*=\\s*\'(http://[^\']+)\'@i', $page, $dl)) { html_error('Download link not found.'); } $dllink = $dl[1]; $ext = strrchr($dllink, '.'); if (empty($ext)) { $ext = '.flv'; } $fname = $title . $ext; $this->RedirectDownload($dllink, $fname); }
/** * Return an CT file for download */ function churchcore__filedownload() { global $files_dir; include_once CHURCHCORE . "/churchcore_db.php"; $mime_types = getMimeTypes(); $file = db_query("select * from {cc_file} f where f.id=:id and filename=:filename", array(":id" => $_GET["id"], ":filename" => $_GET["filename"]))->fetch(); $filename = "{$files_dir}/files/{$file->domain_type}/{$file->domain_id}/{$file->filename}"; $handle = fopen($filename, "rb"); if ($handle == false) { echo "Die Datei konnte nicht gefunden werden!"; } else { $contents = fread($handle, filesize($filename)); fclose($handle); if (isset($mime_types[substr(strrchr($filename, '.'), 1)])) { drupal_add_http_header('Content-Type', $mime_types[substr(strrchr($filename, '.'), 1)], false); } else { drupal_add_http_header('Content-Type', 'application/unknown', false); } if (isset($_GET["type"]) && $_GET["type"] == "download") { drupal_add_http_header('Content-Disposition', 'attachment;filename="' . $file->bezeichnung . '"', false); } else { drupal_add_http_header('Content-Disposition', 'inline;filename="' . $file->bezeichnung . '"', false); } drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', false); drupal_add_http_header('Cache-Control', 'private', true); $content = drupal_get_header(); echo $contents; } }
/** * Reads and returns a chunk of data. * @param int $len Number of bytes to read. Default is to read configured buffer size number of bytes. * @return mixed buffer or -1 if EOF. */ function read($len = null) { // if $len is specified, we'll use that; otherwise, use the configured buffer size. if ($len === null) { $len = $this->bufferSize; } if (($data = $this->in->read($len)) !== -1) { // not all files end with a newline character, so we also need to check EOF if (!$this->in->eof()) { $notValidPart = strrchr($data, "\n"); $notValidPartSize = strlen($notValidPart); if ($notValidPartSize > 1) { // Block doesn't finish on a EOL // Find the last EOL and forget all following stuff $dataSize = strlen($data); $validSize = $dataSize - $notValidPartSize + 1; $data = substr($data, 0, $validSize); // Rewind to the begining of the forgotten stuff. $this->in->skip(-$notValidPartSize + 1); } } // if !EOF } return $data; }
public static function parseNonPhtml(Response $response, $file) { if (!file_exists($file = file_exists($file = self::getPath() . $file) ? $file : (file_exists($file . '.html') ? $file . '.html' : (file_exists($file . '.xhtml') ? $file . '.xhtml' : (file_exists($file . '.php') ? $file . '.php' : $file))))) { if ($response->getStatusCode() == 200) { $response->setStatusCode(404); } $response->setContent($file = (string) new Phtml('/errors/' . $response->getStatusCode(), FALSE, 'default')); } else { if (strpos($file = realpath($file), realpath(Skin::getPath())) !== 0) { throw new \Exception('Unknown skin path: "' . $file . '".'); } $file = str_replace('sitemap.xml.php', 'sitemap.xml', $file); $repository = new PhpRepository(); $response->headers->set('Content-Type', $repository->findType(strtolower(substr(strrchr($file, '.'), 1)) ?: $file) ?: 'text/plain'); if (basename($file) == 'sitemap.xml') { $phtml = new Phtml(NULL); $file = $phtml->parsePhtml($file . '.php'); } else { $file = file_get_contents($file); } $response->setContent($file); } $response->headers->set('Cache-Control', 'max-age=604800'); $response->headers->set('Content-Length', strlen($file)); return $response; }
public function parseValue($value) { preg_match_all('/%([^$]+)\\$/', $this->format_string, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); $i = count($matches[1]); $values = []; foreach (array_reverse($matches[1]) as $match) { $fragmentType = strtolower(ltrim(strrchr(get_class($this->fragment), '\\'), '\\')); // era or unit $fragmentName = $this->fragment->internal_name; $partBegin = stripos($match[0], '{'); if ($partBegin >= 0) { $partEnd = stripos($match[0], '}', $partBegin); $fragmentPart = trim(substr($match[0], $partBegin, $partEnd), '{}'); } else { $fragmentPart = 'unknown'; } $type = "{$fragmentType}.{$fragmentName}.{$fragmentPart}"; if (with($txtObj = $this->texts()->where('fragment_text', $value))->count() > 0) { $value = $txtObj->first()->fragment_value; } $invert = preg_replace('/##(\\d+|\\{[^}]+\\})/', '*${1}+{epoch}%%${1}', str_replace(['\\*', '-%', '\\', '+', '-', ':', '/', '*', ':', '%%', '%', '__', '$$'], ['__', '$$', '##', ':', '+', '-', ':', '/', '*', '+{epoch}\\*', '+{epoch}-%', '+{epoch}%%', '+{epoch}%'], $match[0])); $output = BC::parse($invert, ['epoch' => $this->fragment->getEpochValue(), $fragmentPart => $value], 0); $values[$i] = [$type, $output]; $i--; } return $values; }
/** * valida email * @param string $email */ public function validaEmail($email) { $mail_correcto = 0; //verifico umas coisas if (strlen($email) >= 6 && substr_count($email, "@") == 1 && substr($email, 0, 1) != "@" && substr($email, strlen($email) - 1, 1) != "@") { if (!strstr($email, "'") && !strstr($email, "\"") && !strstr($email, "\\") && !strstr($email, "\$") && !strstr($email, " ")) { //vejo se tem caracter . if (substr_count($email, ".") >= 1) { //obtenho a terminação do dominio $term_dom = substr(strrchr($email, '.'), 1); //verifico que a terminação do dominio seja correcta if (strlen($term_dom) > 1 && strlen($term_dom) < 5 && !strstr($term_dom, "@")) { //verifico que o de antes do dominio seja correcto $antes_dom = substr($email, 0, strlen($email) - strlen($term_dom) - 1); $caracter_ult = substr($antes_dom, strlen($antes_dom) - 1, 1); if ($caracter_ult != "@" && $caracter_ult != ".") { $mail_correcto = 1; } } } } } if ($mail_correcto) { return $email; } else { return false; } }
/** * 名称 * @return string */ function getName() { if (is_null($this->name)) { $this->name = strrchr(get_class($this), '\\'); } return $this->name; }
/** * init() * * @return Zend_Tool_Project_Context_Zf_TestLibraryFile */ public function init() { $this->_forClassName = $this->_resource->getAttribute('forClassName'); $this->_filesystemName = ucfirst(ltrim(strrchr($this->_forClassName, '_'), '_')) . 'Test.php'; parent::init(); return $this; }
/** Scan files/ directory for new files * @cron period: 1h */ function cronjob_files_discover() { $ret = array('new' => 0, 'updated' => 0, 'removed' => 0); # Search for new files or updates if (file_exists($files_dir = 'files/')) { foreach (scandir($files_dir) as $file) { if ($file[0] != '.' && strtolower(strrchr($file, '.')) == '.exe') { $q_data = array('file' => $file, 'hash' => md5_file("{$files_dir}/{$file}"), 'time' => time()); # try to add a new file (rely on the PK) mysql_query(mkquery('INSERT INTO `exe_updates` SET `file`={s:file}, `hash`={s:hash}, `ctime`={i:time}, `mtime`={i:time};', $q_data)); if (mysql_affected_rows() > 0) { $ret['new']++; } # try to update mtime & hash of an existing file mysql_query(mkquery('UPDATE `exe_updates` SET `mtime`={i:time}, `hash`={s:hash}, `scan_date`=0, `scan_threat`=0, `scan_count`=0 WHERE `file`={s:file} AND `hash`<>{s:hash};', $q_data)); if (mysql_affected_rows() > 0) { $ret['updated']++; } } } } # Remove missing files $res = mysql_q(mkquery('SELECT `id`, `file`, `mtime` FROM `exe_updates` WHERE `scan_date` < {i:date};', array('date' => time() - 60 * 60 * 20))); while ($res && !is_bool($exe = mysql_fetch_assoc($res))) { if (!file_exists('files/' . $exe['file'])) { if (time() - $exe['mtime'] > 60 * 60 * 24) { mysql_q(mkquery('DELETE FROM `exe_updates` WHERE `id`={i:id}', $exe)); $ret['removed']++; } continue; } } return $ret; }
public static function save($path, UploadedFile $file) { $ext = substr(strrchr($file->getClientOriginalName(), '.'), 1); $new_name = md5(time() . rand()) . '.' . $ext; $file->move($path, $new_name); return $new_name; }
/** * Implements hook_preprocess_page(). */ function carbon_preprocess_page(&$variables) { $is_front = $variables['is_front']; // Adjust the html element that wraps the site name. h1 on front page, p on other pages $variables['wrapper_site_name_prefix'] = ($is_front ? '<h1' : '<p'); $variables['wrapper_site_name_prefix'] .= ' id="site-name"'; $variables['wrapper_site_name_prefix'] .= ' class="site-name'.($is_front ? ' site-name-front' : '').'"'; $variables['wrapper_site_name_prefix'] .= '>'; $variables['wrapper_site_name_suffix'] = ($is_front ? '</h1>' : '</p>'); // If the theme's info file contains the custom theme setting // default_logo_path, set the $logo variable to that path. $default_logo_path = theme_get_setting('default_logo_path'); if (!empty($default_logo_path) && theme_get_setting('default_logo')) { $variables['logo'] = file_create_url(path_to_theme() . '/' . $default_logo_path); } else { $variables['logo'] = null; } //Arrange the elements of the main content area (content and sidebars) based on the layout class $layoutClass = _carbon_get_layout(); $layout = substr(strrchr($layoutClass, '-'), 1); //Get the last bit of the layout class, the 'abc' string $contentPos = strpos($layout, 'c'); $sidebarsLeft = substr($layout,0,$contentPos); $sidebarsRight = strrev(substr($layout,($contentPos+1))); // Reverse the string so that the floats are correct. $sidebarsHidden = ''; // Create a string of sidebars that are hidden to render and then display:none if(stripos($layout, 'a') === false) { $sidebarsHidden .= 'a'; } if(stripos($layout, 'b') === false) { $sidebarsHidden .= 'b'; } $variables['sidebars']['left'] = str_split($sidebarsLeft); $variables['sidebars']['right'] = str_split($sidebarsRight); $variables['sidebars']['hidden'] = str_split($sidebarsHidden); }
/** * Get callee of the current script. */ static function getCallee($level = 2) { $backtrace = debug_backtrace(); if (count($backtrace) <= $level) { $level = count($backtrace) - 1; } /* Added by Vicary @ 23 Dec, 2012 This script should: 1. try its best to search until there is a file, and 2. stop before framework scripts are reached. */ if (!@$backtrace[$level]['file']) { for ($level = count($backtrace); $level-- && !@$backtrace[$level]['file'];) { } } // Framework scripts are: // - resolvers // to be added ... while (strrchr(dirname(@$backtrace[$level]['file']), '/') == '/resolvers') { $level--; } if ($level < 0) { $level = 0; } return @$backtrace[$level]; }
public function format($source) { $this->tkns = token_get_all($source); $this->code = ''; while (list($index, $token) = each($this->tkns)) { list($id, $text) = $this->getToken($token); $this->ptr = $index; switch ($id) { case T_TRAIT: case T_CLASS: if ($this->leftUsefulTokenIs(T_DOUBLE_COLON)) { $this->appendCode($text); break; } $this->appendCode($text); $this->printUntil(ST_CURLY_OPEN); list(, $text) = $this->printAndStopAt(T_WHITESPACE); if ($this->hasLn($text)) { $text = substr(strrchr($text, 10), 0); } $this->appendCode($text); break; default: $this->appendCode($text); break; } } return $this->code; }
protected function output_expensive_queries(array $expensive) { $dp = strlen(substr(strrchr(QM_DB_EXPENSIVE, '.'), 1)); echo '<div class="qm qm-queries" id="qm-query-expensive">'; echo '<table cellspacing="0">'; echo '<thead>'; echo '<tr>'; echo '<th colspan="5" class="qm-expensive">' . sprintf(__('Slow Database Queries (above %ss)', 'query-monitor'), '<span class="qm-expensive">' . number_format_i18n(QM_DB_EXPENSIVE, $dp) . '</span>') . '</th>'; echo '</tr>'; echo '<tr>'; echo '<th scope="col">' . __('Query', 'query-monitor') . '</th>'; echo '<th scope="col">' . __('Caller', 'query-monitor') . '</th>'; if (isset($expensive[0]['component'])) { echo '<th scope="col">' . __('Component', 'query-monitor') . '</th>'; } if (isset($expensive[0]['result'])) { echo '<th scope="col" class="qm-num">' . __('Affected Rows', 'query-monitor') . '</th>'; } echo '<th class="qm-num">' . __('Time', 'query-monitor') . '</th>'; echo '</tr>'; echo '</thead>'; echo '<tbody>'; foreach ($expensive as $row) { $this->output_query_row($row, array('sql', 'caller', 'component', 'result', 'time')); } echo '</tbody>'; echo '</table>'; echo '</div>'; }
/** * Add a file * @param string * @param string * @param string */ public function add($strFile, $strVersion = null, $strMedia = 'screen') { $strType = strrchr($strFile, '.'); // Check the file type if ($strType != self::CSS && $strType != self::JS) { throw new Exception("Invalid file {$strFile}"); } // Set the operation mode if (!$this->strMode) { $this->strMode = $strType; } elseif ($this->strMode != $strType) { throw new Exception('You cannot mix different file types. Create another Combiner object instead.'); } // Prevent duplicates if (isset($this->arrFiles[$strFile])) { return; } // Check the source file if (!file_exists(TL_ROOT . '/' . $strFile)) { $this->import('StyleSheets'); $this->StyleSheets->updateStyleSheets(); // Retry if (!file_exists(TL_ROOT . '/' . $strFile)) { throw new Exception("File {$strFile} does not exist"); } } // Default version if ($strVersion === null) { $strVersion = VERSION . '.' . BUILD; } // Store the file $arrFile = array('name' => $strFile, 'version' => $strVersion, 'media' => $strMedia); $this->arrFiles[$strFile] = $arrFile; $this->strKey .= '-f' . $strFile . '-v' . $strVersion . '-m' . $strMedia; }
/** * Creates and caches the image thumbnail and returns full path from thumbnail file. * * @param string $filename * @param integer $width * @param integer $height * @param string $mode * @return string * @throws FileNotFoundException */ public static function thumbnailFile($filename, $width, $height, $mode = self::THUMBNAIL_OUTBOUND) { $filename = FileHelper::normalizePath(Yii::getAlias($filename)); if (!is_file($filename)) { throw new FileNotFoundException("File {$filename} doesn't exist"); } $cachePath = Yii::getAlias('@webroot/' . self::$cacheAlias); $thumbnailFileExt = strrchr($filename, '.'); $thumbnailFileName = md5($filename . $width . $height . $mode . filemtime($filename)); $thumbnailFilePath = $cachePath . DIRECTORY_SEPARATOR . substr($thumbnailFileName, 0, 2); $thumbnailFile = $thumbnailFilePath . DIRECTORY_SEPARATOR . $thumbnailFileName . $thumbnailFileExt; if (file_exists($thumbnailFile)) { if (self::$cacheExpire !== 0 && time() - filemtime($thumbnailFile) > self::$cacheExpire) { unlink($thumbnailFile); } else { return $thumbnailFile; } } if (!is_dir($thumbnailFilePath)) { mkdir($thumbnailFilePath, 0755, true); } $box = new Box($width, $height); $image = Image::getImagine()->open($filename); $image = $image->thumbnail($box, $mode); $image->save($thumbnailFile); return $thumbnailFile; }
function save_images($image_url, $post_id, $i) { //set_time_limit(180); //每个图片最长允许下载时间,秒 $file = file_get_contents($image_url); $fileext = substr(strrchr($image_url, '.'), 1); $fileext = strtolower($fileext); if ($fileext == "" || strlen($fileext) > 4) { $fileext = "jpg"; } $savefiletype = array('jpg', 'gif', 'png', 'bmp'); if (!in_array($fileext, $savefiletype)) { $fileext = "jpg"; } $im_name = date('YmdHis', time()) . $i . mt_rand(10, 20) . '.' . $fileext; $res = wp_upload_bits($im_name, '', $file); if (isset($res['file'])) { $attach_id = insert_attachment($res['file'], $post_id); } else { return; } if (ot_get_option('auto_save_image_thumb') == 'on' && $i == 1) { set_post_thumbnail($post_id, $attach_id); } return $res; }
public function saveFile($data) { $post = (object) $data; self::setMapping(); // recupera variáveis $fileData = $_FILES["filedata"]; $fileName = $fileData["name"]; $fileType = $fileData["type"]; $tempName = $fileData["tmp_name"]; $dataType = self::$mapping[$fileType]; if (!is_uploaded_file($tempName)) { self::$response->success = false; self::$response->text = "O arquivo não foi enviado com sucesso. Erro de sistema: {$fileData['error']}."; return json_encode(self::$response); } if (!array_key_exists($fileType, self::$mapping)) { return '{"success":false,"records":0,"error":2,"root":[],"text":"Tipo de arquivo não mapeado para esta operação!"}'; } // comprime arquivo temporário if ($dataType === true) { self::sizeFile(); self::workSize($tempName); } $tempData = base64_encode(file_get_contents($tempName)); // recupera extensão do arquivo $fileExtension = strtoupper(strrchr($fileName, ".")); $fileExtension = str_replace(".", "", $fileExtension); $fileInfo = array("fileType" => $fileType, "fileExtension" => $fileExtension, "dataType" => $dataType, "fileName" => $fileName); $fileInfo = stripslashes(json_encode($fileInfo)); $affectedRows = $this->exec("update {$post->tableName} set filedata = '{$tempData}', fileinfo = '{$fileInfo}' where id = {$post->id}"); unlink($tempName); return $affectedRows; }