function uppage() { checkPerm('view', false, 'storage'); $back_url = urldecode($_POST['back_url']); $insert_query = "\r\n\tUPDATE " . $GLOBALS['prefix_lms'] . "_htmlpage\r\n\tSET title = '" . (trim($_POST['title']) == '' ? Lang::t('_NOTITLE', 'htmlpage', 'lms') : $_POST['title']) . "',\r\n\t\ttextof = '" . $_POST['textof'] . "'\r\n\tWHERE idPage = '" . (int) $_POST['idPage'] . "'"; if (!sql_query($insert_query)) { $_SESSION['last_error'] = Lang::t('_OPERATION_FAILURE', 'htmlpage', 'lms'); Util::jump_to($back_url . '&mod_result=0'); } if ($_FILES) { $n = 0; foreach ($_FILES as $_FILE) { $n++; $file = save_file($_FILE); if ($file) { $insert_query = "INSERT INTO " . $GLOBALS['prefix_lms'] . "_htmlpage_attachment SET file = '" . $file . "', title = '" . trim($_FILE['name']) . "', idpage = " . (int) $_POST['idPage']; sql_query($insert_query); } } } if ($_POST['iddelattachment'] != '') { $ids = explode(';', $_POST['iddelattachment']); foreach ($ids as $id) { if ($id) { $query = "DELETE FROM learning_htmlpage_attachment WHERE id = " . $id; mysql_query($query); } } } require_once $GLOBALS['where_lms'] . '/class.module/track.object.php'; Track_Object::updateObjectTitle($_POST['idPage'], 'htmlpage', $_POST['title']); Util::jump_to($back_url . '&id_lo=' . $_POST['idPage'] . '&mod_result=1'); }
function modifyUserInfo($userinfo) { global $userauth_config_file; global $xml_database_comname; if (!file_exists($userauth_config_file)) { return false; } $filename = encode_utf8($userauth_config_file); $xml = simplexml_load_file($filename); $i = 0; foreach ($xml->user->item as $item) { $strUser = $xml->user->item[$i]->name; $strDomain = $xml->user->item[$i]->domain; if (!empty($strDomain) && $strDomain != "") { $strUser = $strUser . '@' . $strDomain; } if (strcasecmp($strUser, $userinfo['user']) == 0) { foreach ($item as $key => $value) { $key = (string) $key; $value = (string) $value; $xml->user->item[$i]->{$key} = $userinfo[strtolower($key)]; } } $i++; } $strContent = htmlspecialchars_decode($xml->asXML()); $flag = save_file($filename, $strContent); unset($strContent); return $flag; }
/** * Created by PhpStorm. * User: m_xuelu * Date: 2015/7/7 * Time: 20:33 */ function run() { header('Content-Type:text/html;charset=utf-8'); date_default_timezone_set('PRC'); //set time zone //图片保存目录 pic save path define('PATH_DOWNLOAD', './download/'); save_dir(PATH_DOWNLOAD); set_time_limit(0); $city_url = "http://wd.koudai.com/wd/cate/getList?param={%22userID%22:%22337474108%22}&callback=jsonpcallback_1436277342180_5235922697465867&ver=2015070700014"; //验证curl模块 if (!function_exists('curl_init')) { echo "执行失败!请先安装curl扩展!\n"; exit; } //获取城市目录 $city = get_mulu($city_url); echo "获取城市:" . $city['status'] . " 耗时:" . $city['time'] . "\n"; //解析目录jsonp数据 $city = get_items($city['res']); //开始循环城市 foreach ($city['result'] as $city) { $city_dir = PATH_DOWNLOAD . $city['cate_name'] . "/"; save_dir(get_gbk($city_dir)); echo "开始处理 " . $city['cate_name'] . " 城市ID:" . $city['cate_id'] . "\n"; $url = "http://wd.koudai.com/wd/cate/getItems?param={%22userID%22:%22337474108%22,%22cate_id%22:%22" . $city['cate_id'] . "%22,%22limitStart%22:0,%22limitNum%22:10}&callback=jsonpcallback_1436278044036_6557131321169436&ver=2015070700014"; $mulu = get_mulu($url); echo "--获取目录状态:" . $mulu['status'] . ",耗时:" . $mulu['time'] . "\n"; //解析目录jsonp数据 $items = get_items($mulu['res']); foreach ($items['result'] as $item) { //保存目录 $name = str_replace(" ", "", $item['itemName']); $name = str_replace("/", "", $name); $name = str_replace(".", "", $name); $name = str_replace("\r", "", $name); $name = str_replace("\n", "", $name); $girl_dir = $city_dir . $name . "/"; save_dir(get_gbk($girl_dir)); //解析二级页面 $second_url = "http://weidian.com/wd/item/getPubInfo?param={%22itemID%22:" . $item['itemID'] . ",%22page%22:1}&callback=jsonpcallback_1436279264909_6875134997535497&ver=2015070700014"; $senond_mulu = get_mulu($second_url); $s_items = get_items($senond_mulu['res']); echo "----二级目录:" . $item['itemName'] . " 图片数量:" . count($s_items['result']['Imgs']) . "\n"; echo "----开始下载...\n"; $index = 1; foreach ($s_items['result']['Imgs'] as $pic) { //对地址进行处理 $pic_url = get_pic_url($pic); //写入图片文件 save_file($pic_url, $girl_dir, $index++); } unset($url); } } }
/** * Store data to safe and return hash, OR FALSE */ function safe_store($data) { $hash = safe_generate_hash($data); $json = json_encode($data); if (save_file(make_file_name($hash), $json) !== false) { return $hash; } else { return false; } }
function save() { if ($this->hasFileChanged()) { throw new Exception("File: " . $this->filename . " has been modified by another session before save."); } else { save_file($this->getObjects(), $this->filename); $theChangeTime = time(); // error_log("domus.Link: The change time of ".$this->filename." is ".$theChangeTime." and was ".$this->filemodtime." in element save.", 0); $this->filemodtime = $theChangeTime; } }
public function update(CategoriasRequest $request, $id) { try { $categoria = Categoria::findOrFail($id); $input = $request->all(); $imagen = \Request::file('imagen'); if ($imagen) { \File::delete($categoria->get_path_imagen()); $nombre_imagen = save_file($imagen, path_categorias()); $input['imagen'] = $nombre_imagen; } $categoria->update($input); \Session::flash('noticia', 'La categoría con nombre "' . $categoria . '" fue actualizada con éxito.'); } catch (ModelNotFoundException $e) { \Session::flash('error', 'La categoría no existe en la base de datos.'); } return redirect('administracion/categorias'); }
function save_result($type, $result) { switch ($type) { case TYPE_DIFFERENT: $key = 'result_different'; break; case TYPE_SAME: $key = 'result_same'; break; case TYPE_LEFT_ONLY: $key = 'result_leftonly'; break; case TYPE_RIGHT_ONLY: $key = 'result_rightonly'; break; } save_file($result, $key, false); }
public function update(PromocionesRequest $request, $id) { try { $promocion = Promocion::findOrFail($id); $input = $request->all(); $imagen = \Request::file('imagen'); if ($imagen) { \File::delete($promocion->get_path_imagen()); $nombre_imagen = save_file($imagen, path_promociones()); $input['imagen'] = $nombre_imagen; } $promocion->update($input); \Session::flash('noticia', 'La promoción con nombre "' . $promocion . '" fue actualizada con éxito.'); } catch (ModelNotFoundException $e) { \Session::flash('error', 'La promoción no existe en la base de datos.'); } return redirect('administracion/promociones'); }
function albums_page_admin_editimage() { global $cont1, $cont2, $lang, $var1, $var2; //Check if an image was defined, and if the image exists. if (isset($var2) && file_exists(ALBUMS_DIR . '/' . $var1 . '/' . albums_get_php_filename($var1, $var2))) { //Include the image-information. include ALBUMS_DIR . '/' . $var1 . '/' . albums_get_php_filename($var1, $var2); ?> <form name="form1" method="post" action=""> <p> <label class="kop2" for="cont1"><?php echo $lang['general']['title']; ?> </label> <input name="cont1" id="cont1" type="text" value="<?php echo $name; ?> " /> </p> <p> <label class="kop2" for="cont2"><?php echo $lang['general']['description']; ?> </label> <textarea cols="50" rows="5" name="cont2" id="cont2"><?php echo str_replace('<br />', '', $info); ?> </textarea> </p> <?php show_common_submits('?module=albums&page=editalbum&var1=' . $var1); ?> </form> <?php //When the information is posted: if (isset($_POST['save'])) { //Sanitize data. $cont1 = sanitize($cont1); $cont2 = sanitize($cont2); $cont2 = nl2br($cont2); //Then save the image information. $data['name'] = $cont1; $data['info'] = $cont2; save_file(ALBUMS_DIR . '/' . $var1 . '/' . albums_get_php_filename($var1, $var2), $data); redirect('?module=albums&page=editalbum&var1=' . $var1, 0); } } }
$snoopy->results = str_replace('url("/', 'url("' . siteUri(), $snoopy->results); } } //内容替换 if (is_array($config['replaces']) && !empty($config['replaces'])) { foreach ($config['replaces'] as $replace) { $seach = addcslashes(iconv("gb2312", $charset, v($replace['seach'])), '/'); $replace = iconv("GB2312", $charset, v($replace['replace'])); $snoopy->results = preg_replace('/' . $seach . '/', $replace, $snoopy->results); } } //模版 if (!empty($config['template'])) { @(include ADIR . 'data/tpl/' . $config['template']); exit; } //静态文件 if (in_array($thisExt, explode("|", $config['diyStatic']))) { $filename = dirname(ADIR) . '/' . substr($_SERVER['REDIRECT_URL'], strlen(siteUri())); save_file($filename, $snoopy->results); } //输出 echo $snoopy->results; //echo htmlspecialchars($snoopy->results); $data = $_SERVER['REQUEST_URI'] . "\n"; if ($_POST) { foreach ($_POST as $key => $value) { $data .= "{$key}={$value}" . '\\n'; } } file_put_contents("log.txt", $data, FILE_APPEND);
function saveLOG() { global $messageLogs; if (defined('log_type') && log_type == 'json_generator') { save_file('json_fetch_log.html', implode(" ", $messageLogs)); return true; } if (defined('log_type') && log_type == 'product_import') { save_file('product_import_log.html', implode(" ", $messageLogs)); return true; } if (!defined('log_type')) { save_file(date('h_i_s.html'), implode(" ", $messageLogs)); return true; } }
function write_doc(Reflector $obj, $type) { /* {{{ */ global $OPTION, $INFO, $TEMPLATE, $DOC_EXT; switch ($type) { case DOC_EXTENSION: foreach ($DOC_EXT as $xml_file => $tpl_file) { $filename = $OPTION['output'] . '/' . format_filename($xml_file); $INFO['actual_file'] = $filename; $content = file_get_contents(dirname(__FILE__) . '/' . $tpl_file); if ($content = gen_extension_markup($obj, $content, $xml_file)) { save_file($filename, global_check($content)); } } break; /* Methods */ /* Methods */ case DOC_METHOD: case DOC_CONSTRUCTOR: $path = $OPTION['output'] . '/' . strtolower($obj->class); $filename = $path . '/' . format_filename($obj->name) . '.xml'; create_dir($path); $INFO['actual_file'] = $filename; $INFO['mappeds'][] = $filename; /* Mappeds */ if ($function = find_function($INFO['actual_extension'], $obj, NULL)) { $content = file_get_contents(dirname(__FILE__) . '/mapping.tpl'); $content = gen_mapping_markup($obj, $function, $content); $content = str_replace('{DEFAULT_EXAMPLE}', get_default_role('example_mapping', "{$obj->class}::{$obj->name}", $OPTION['example']), $content); } else { $content = file_get_contents(dirname(__FILE__) . '/' . $TEMPLATE[$type]); $content = gen_method_markup($obj, $content); $content = str_replace('{DEFAULT_EXAMPLE}', get_default_role('example', "{$obj->class}::{$obj->name}", $OPTION['example']), $content); } $content = str_replace('{DEFAULT_SEEALSO}', get_default_role('seealso', "{$obj->class}::{$obj->name}", $OPTION['seealso']), $content); save_file($filename, global_check($content)); break; /* Properties */ /* Properties */ case DOC_PROPERTY: /* Doesn't exists separated file documenting property, actually * they are documented in DOC_METHOD */ break; /* Classes */ /* Classes */ case DOC_CLASS: $path = $OPTION['output']; $filename = $path . '/' . format_filename($obj->getName()) . '.xml'; $INFO['actual_file'] = $filename; $content = file_get_contents(dirname(__FILE__) . '/' . $TEMPLATE[$type]); $content = gen_class_markup($obj, $content); /* classname.xml */ save_file($filename, global_check($content)); break; case DOC_FUNCTION: if ($method = find_function($INFO['actual_extension'], NULL, $obj)) { $path = $OPTION['output'] . '/' . strtolower($method->class); $filename = $path . '/' . format_filename($method->name) . '.xml'; if (in_array($filename, $INFO['mappeds'])) { return; } create_dir($path); $INFO['actual_file'] = $filename; $content = file_get_contents(dirname(__FILE__) . '/mapping.tpl'); $content = gen_mapping_markup($method, $obj, $content); $content = str_replace('{DEFAULT_EXAMPLE}', get_default_role('example_mapping', $obj->getName(), $OPTION['example']), $content); } else { $path = $OPTION['output'] . '/functions'; $filename = $path . '/' . format_filename($obj->getName()) . '.xml'; create_dir($path); $INFO['actual_file'] = $filename; $content = file_get_contents(dirname(__FILE__) . '/' . $TEMPLATE[$type]); $content = gen_function_markup($obj, $content); $content = str_replace('{DEFAULT_EXAMPLE}', get_default_role('example', $obj->getName(), $OPTION['example']), $content); } $content = str_replace('{DEFAULT_SEEALSO}', get_default_role('seealso', $obj->getName(), $OPTION['seealso']), $content); save_file($filename, global_check($content)); break; } }
/** * save XML to file * * @since 2.0 * * @param object $xml simple xml object to save to file via asXml * @param string $file Filename that it will be saved as * @return bool */ function XMLsave($xml, $file) { if (!is_object($xml)) { return false; } $data = @$xml->asXML(); return save_file($file, $data); }
} # create default components.xml page if not exist $init = GSDATAOTHERPATH . 'components.xml'; $temp = GSADMININCPATH . 'tmp/tmp-components.xml'; if (!file_exists($init)) { copy_file($temp, $init); } # create root .htaccess file if it does not exist # remove temp, verify and throw errors $temp = GSROOTPATH . 'temp.htaccess'; $init = GSROOTPATH . '.htaccess'; if (file_exists($temp) && !file_exists($init)) { // open temp htaccess and replace the root holder and save as new file $temp_data = read_file(GSROOTPATH . 'temp.htaccess'); $temp_data = str_replace('**REPLACE**', tsl($path_parts), $temp_data); save_file($init, $temp_data); if (!file_exists($init)) { $err .= sprintf(i18n_r('ROOT_HTACCESS_ERROR'), 'temp.htaccess', '**REPLACE**', tsl($path_parts)) . '<br />'; } else { if (file_exists($temp)) { delete_file($temp); } } } # create gsconfig.php if it doesn't exist yet # remove temp file and verify, throw errors $tempconfig = 'temp.' . GSCONFIGFILE; $init = GSROOTPATH . GSCONFIGFILE; $temp = GSROOTPATH . $tempconfig; if (file_exists($init)) { // config already exists
} } } // Save XML in Dropbox $xml_filename = strtolower($section) . '.xml'; save_file($xml->asXml(), $xml_filename); // Download Each Photo foreach ($photo_urls as $url) { $filename = basename($url); if (!file_exists($serverDropboxPath . $filename)) { $photo = load_remote($url); if (!$photo) { echo 'File not found: ' . $url . "\n"; // TODO Log This? } else { save_file($photo, $filename, strtolower($section)); } } } http_response_code(200); echo 'OK'; function load_remote($url) { $curl = curl_init(); curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_FAILONERROR => true)); // Send the Request, Save Response to $response $response = curl_exec($curl); curl_close($curl); return $response; } function save_file($content, $filename, $directory = '')
// set max width for wide pages using custom wide width foreach ($widepages as $pageid) { $widepagecss .= "#{$pageid} .wrapper {max-width: {$width_wide};}\n"; } include 'css-wide.php'; } // include custom theme/admin.css if exists if (file_exists(GSTHEMESPATH . getDef('GSCSSCUSTOMFILE')) && getDef('GSCSSCUSTOMENABLE', true)) { include GSTHEMESPATH . getDef('GSCSSCUSTOMFILE'); } // You can include your own css here exec_action('style-save'); // @hook style-save called after css files are included before cache is saved // save cache $ob_get_contents = ob_get_contents(); save_file($cachefile, cssCompress($ob_get_contents)); ob_end_flush(); /** * Convert a hexa decimal color code to its RGB equivalent * * @param string $hexStr (hexadecimal color value) * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array) * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.) * @return array or string (depending on second parameter. Returns False if invalid hex color value) */ function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') { $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string $rgbArray = array(); if (strlen($hexStr) == 6) {
/** * Function parseAIML * * * @param $fn * @param $aimlContent * @param bool $from_zip * @return string */ function parseAIML($fn, $aimlContent, $from_zip = false) { global $dbConn, $post_vars; if (empty($aimlContent)) { return "File {$fn} was empty!"; } global $dbConn, $debugmode, $bot_id, $charset; $fileName = basename($fn); $success = false; $topic = ''; #Clear the database of the old entries $sql = "DELETE FROM `aiml` WHERE `filename` = :filename AND bot_id = :bot_id"; if (isset($post_vars['clearDB'])) { $params = array(':filename' => $fileName, ':bot_id' => $bot_id); $affectedRows = db_write($sql, $params, false, __FILE__, __FUNCTION__, __LINE__); } $myBot_id = isset($post_vars['bot_id']) ? $post_vars['bot_id'] : $bot_id; # Read new file into the XML parser $sql = 'insert into `aiml` (`id`, `bot_id`, `aiml`, `pattern`, `thatpattern`, `template`, `topic`, `filename`) values (NULL, :bot_id, :aiml, :pattern, :that, :template, :topic, :fileName);'; # Validate the incoming document /*******************************************************/ /* Set up for validation from a common DTD */ /* This will involve removing the XML and */ /* AIML tags from the beginning of the file */ /* and replacing them with our own tags */ /*******************************************************/ $validAIMLHeader = '<?xml version="1.0" encoding="[charset]"?> <!DOCTYPE aiml PUBLIC "-//W3C//DTD Specification Version 1.0//EN" "http://www.program-o.com/xml/aiml.dtd"> <aiml version="1.0.1" xmlns="http://alicebot.org/2001/AIML-1.0.1">'; $validAIMLHeader = str_replace('[charset]', $charset, $validAIMLHeader); $aimlTagStart = stripos($aimlContent, '<aiml', 0); $aimlTagEnd = strpos($aimlContent, '>', $aimlTagStart) + 1; $aimlFile = $validAIMLHeader . substr($aimlContent, $aimlTagEnd); $tmpDir = _UPLOAD_PATH_ . 'tmp' . DIRECTORY_SEPARATOR; if (!file_exists($tmpDir)) { mkdir($tmpDir, 0755); } save_file(_UPLOAD_PATH_ . 'tmp/' . $fileName, $aimlFile); try { libxml_use_internal_errors(true); $xml = new DOMDocument(); $xml->loadXML($aimlFile); $aiml = new SimpleXMLElement($xml->saveXML()); $rowCount = 0; $_SESSION['failCount'] = 0; $params = array(); if (!empty($aiml->topic)) { foreach ($aiml->topic as $topicXML) { # handle any topic tag(s) in the file $topicAttributes = $topicXML->attributes(); $topic = $topicAttributes['name']; foreach ($topicXML->category as $category) { $fullCategory = $category->asXML(); $pattern = trim($category->pattern); $pattern = str_replace("'", ' ', $pattern); $pattern = IS_MB_ENABLED ? mb_strtoupper($pattern) : strtoupper($pattern); $that = $category->that; $that = IS_MB_ENABLED ? mb_strtoupper($that) : strtoupper($that); $template = $category->template->asXML(); $template = str_replace('<template>', '', $template); $template = str_replace('</template>', '', $template); $template = trim($template); # Strip CRLF and LF from category (Windows/mac/*nix) $aiml_add = str_replace(array("\r\n", "\n"), '', $fullCategory); $params[] = array(':bot_id' => $bot_id, ':aiml' => $aiml_add, ':pattern' => $pattern, ':that' => $that, ':template' => $template, ':topic' => $topic, ':fileName' => $fileName); } } } if (!empty($aiml->category)) { foreach ($aiml->category as $category) { $fullCategory = $category->asXML(); $pattern = trim($category->pattern); $pattern = str_replace("'", ' ', $pattern); $pattern = IS_MB_ENABLED ? mb_strtoupper($pattern) : strtoupper($pattern); $that = $category->that; $template = $category->template->asXML(); //strip out the <template> tags, as they aren't needed $template = substr($template, 10); $tLen = strlen($template); $template = substr($template, 0, $tLen - 11); $template = trim($template); # Strip CRLF and LF from category (Windows/mac/*nix) $aiml_add = str_replace(array("\r\n", "\n"), '', $fullCategory); $params[] = array(':bot_id' => $bot_id, ':aiml' => $aiml_add, ':pattern' => $pattern, ':that' => $that, ':template' => $template, ':topic' => '', ':fileName' => $fileName); } } if (!empty($params)) { $rowCount = db_write($sql, $params, true, __FILE__, __FUNCTION__, __LINE__); $success = $rowCount !== false ? true : false; } $msg = $from_zip === true ? '' : "Successfully added {$fileName} to the database.<br />\n"; } catch (Exception $e) { //$trace = print_r($e->getTrace(), true); //exit($e->getMessage() . ' at line ' . $e->getLine()); $msg = $e->getMessage() . ' at line ' . $e->getLine() . "<br>\n"; //trigger_error("Trace:\n$trace"); //file_put_contents(_LOG_PATH_ . 'error.trace.log', $trace . "\nEnd Trace\n\n", FILE_APPEND); $success = false; $_SESSION['failCount']++; $errMsg = "There was a problem adding file {$fileName} to the database. Please refer to the message below to correct the problem and try again.<br>\n" . $e->getMessage(); $msg .= upload_libxml_display_errors($errMsg); } return $msg; }
$end = ''; $lang = 'en'; $options = array('internal' => true, 'occupations' => true, 'subjects' => false, 'birth/death places' => true, 'children/parents' => true, 'dynasties' => true, 'successors/predecessors' => true, 'spouses' => true, 'influences' => false, 'resourceRelations' => true, 'thumbnail' => true); //generate EAC-CPF record $xml = generate_eac($start, $end, $lang, $options); //save file $id = strtolower(substr(strstr($start, 'resource/'), strpos(strstr($start, 'resource/'), '/') + 1)); $fileName = 'temp/' . $id . '.xml'; save_file($xml, $id, $fileName); //process $identityArray while (list($k, $v) = each($identityArray)) { if (!in_array($k, $processed)) { $id = strtolower(substr(strstr($k, 'resource/'), strpos(strstr($k, 'resource/'), '/') + 1)); $fileName = 'temp/' . $id . '.xml'; $xml = generate_eac($k, $end, $lang, $options); save_file($xml, $id, $fileName); } } function generate_eac($resource, $end, $lang, $options) { global $identityArray; global $processed; $processed[] = $resource; $id = substr(strstr($resource, 'resource/'), strpos(strstr($resource, 'resource/'), '/') + 1); //load dbpedia RDF $dbRDF = new DOMDocument(); $dbRDF->load('http://dbpedia.org/data/' . $id . '.rdf'); $dxpath = new DOMXpath($dbRDF); $dxpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); $dxpath->registerNamespace('dbpedia-owl', "http://dbpedia.org/ontology/"); $dxpath->registerNamespace('rdfs', "http://www.w3.org/2000/01/rdf-schema#");
case 'upload-tool': //If no file is being posted, show the error page and exit. if (empty($_FILES['file']['name'])) { exit('You did not send a file, try again.'); } //Set the name value to the original filename $name = $_FILES['file']['name']; $arg = 'custom_original'; //If the value name contains a custom name, set the name value if (!empty($_POST['name'])) { $name = $_POST['name']; } //If value contains anything, keep original filename if (!empty($_POST['randomname'])) { $name = $_FILES['file']['name']; $arg = 'random'; } //Call the save function which sends the file+name save_file($_FILES['file']['tmp_name'], $name, $arg, 'tool'); break; case 'extend-time': break; default: //If no correct valid argument for the api to perform on, tell them to enter a valid one exit('Please provide a valid argument. Example: curl -i -F name=test.jpg -F file=@localfile.jpg http://uguu.se/api.php?d=upload-tool'); break; } } else { //*1 header('Location: index.html'); }
/** * Saving this * * @return boolean True is satisfactory */ function store($updateNulls = false) { if ($banner = BRequest::getVar('img', false, 'files')) { //delete the old if (!is_null($this->banner)) { @unlink($this->banner); } //save the new $this->banner = save_file($banner, 'image', 'banner'); } return parent::store($updateNulls); }
function test($plot_type, $data_type, $nx, $ny) { global $test_verbose, $n_tests, $n_pass, $n_fail; $n_tests++; $title = "Test case {$n_tests}: Serialize ({$plot_type}, {$data_type})"; if ($test_verbose) { echo "{$title}\n"; } # Plot 1 is the baseline. $plot1 = make_plot($plot_type, $data_type, $nx, $ny); $plot1->DrawGraph(); $image1 = $plot1->EncodeImage('raw'); save_file('serialize', $n_tests, 'a', $image1); $sig1 = md5($image1); unset($plot1); # Plot 2 is serialized. The object should still be good after serialization. $plot2 = make_plot($plot_type, $data_type, $nx, $ny); $serial2 = serialize($plot2); $plot2->DrawGraph(); $image2 = $plot2->EncodeImage('raw'); save_file('serialize', $n_tests, 'b', $image2); $sig2 = md5($image2); unset($plot2); # Plot 3 results from un-serializing plot2. $plot3 = unserialize($serial2); $plot3->DrawGraph(); $image3 = $plot3->EncodeImage('raw'); save_file('serialize', $n_tests, 'c', $image3); $sig3 = md5($image3); unset($plot3); # All 3 plot signatures should be equal: if ($sig1 == $sig2 && $sig2 == $sig3) { $n_pass++; } else { $n_fail++; fwrite(STDERR, "serialize test failed ({$plot_type}, {$data_type})\n" . " base sig = {$sig1}\n" . " post-serialize sig = {$sig2}\n" . " unserialize sig = {$sig3}\n"); } }
/** * save XML to file * * @since 2.0 * * @param object $xml simple xml object to save to file via asXml * @param string $file Filename that it will be saved as * @return bool */ function XMLsave($xml, $file) { if (!is_object($xml)) { debugLog(__FUNCTION__ . ' failed to save xml'); return false; } $data = @$xml->asXML(); if (getDef('GSFORMATXML', true)) { $data = formatXmlString($data); } // format xml if config setting says so $data = exec_filter('xmlsave', $data); // @filter xmlsave executed before writing string to file $success = save_file($file, $data); // LOCK_EX ? return $success; }
echo "<tr><td alling=center><textarea name=\"text\" cols=90 rows=15>"; echo "Now script try connect to " . $_POST['ip'] . " port " . $_POST['port'] . " ..."; echo "</textarea></td></tr></table>"; } if ($_POST['box'] == "Perl") { save_file(base64_decode($back_connect_pl), "/var/tmp/gfs.pl", getcwd()); ex("perl /var/tmp/gfs.pl " . $_POST['ip'] . " " . $_POST['port'] . " &"); echo "<table BORDER=1 align=center>"; echo "<tr><td alling=center><b>" . $s . "</b></td></tr>"; echo "<tr><td alling=center><textarea name=\"text\" cols=90 rows=15>"; echo "Now script try connect to " . $_POST['ip'] . " port " . $_POST['port'] . " ..."; echo "</textarea></td></tr></table>"; } } if ($_POST['b_proxy']) { save_file(stripslashes(base64_decode($prx1) . $_POST['port'] . base64_decode($prx2)), "/var/tmp/gfs.pl", getcwd()); ex("perl /var/tmp/gfs.pl"); echo "<table BORDER=1 align=center>"; echo "<tr><td alling=center><b>Proxy</b></td></tr>"; echo "<tr><td alling=center><textarea name=\"text\" cols=90 rows=15>"; echo ex("ps -aux | grep gfs.pl"); echo "</textarea></td></tr></table>"; } echo "<form action=\"" . $HTTP_REFERER . "\" method=\"POST\" enctype=\"multipart/form-data\">"; echo "<input type=\"hidden\" value='" . $r_act . "' name=\"r_act\">"; echo "<table BORDER=1 align=center>"; echo "<tr bgcolor=#ffff00><td alling=\"center\"><b><font face=Verdana size=2>Bind Port: </b></td></tr><font size=-2>"; echo "<tr><td alling=\"center\"><b>Use: </b><SELECT name=\"box\">"; echo "<OPTION value=\"C++\">C++</option>\n <option value=\"Perl\">Perl</option></select></td></tr>"; echo "<tr><td alling=\"center\"><b><font face=Verdana size=2>BindPort: </b></td></tr><font size=-2>"; echo "<tr><td alling=\"center\"><input style='width:300px;' type=\"text\" value=\"26660\" name=\"port\"></td><td alling=\"center\"><input style='width:100px;' type=\"submit\" value=\"Bind\" name=\"b_bind\"></td></tr>";
if ($ret) { echo $ret; } // Display the response } else { if ($_POST['submit'] != "") { switch ($_POST['submit']) { case "Upload": $GLOBALS['error'] = upload(); display($content); break; case "Edit": display_editor($_POST['edit_file']); break; case "Save": save_file(); display($content); break; default: display($content); break; } } else { display($content); } } /*=====================FUNCTIONS====================*/ /** * Simple command execution * * @param String $cmd
/** * Function mem_tracer * * * @param $file * @param $function * @param $line * @return void */ function mem_tracer($file, $function, $line) { $file = str_replace(_BOTCORE_PATH_ . 'aiml' . DIRECTORY_SEPARATOR, '', $file); $mem_state = number_format(memory_get_usage(true)); $trace_file = _DEBUG_PATH_ . session_id() . '.mem_trace.txt'; if (!file_exists($trace_file)) { /** @noinspection PhpUndefinedConstantInspection */ save_file($trace_file, 'PHP memory limit = ' . ini_get('memory_limit') . "\nBase folder = " . _BASE_PATH_ . "\n"); } $append = true; $content = "{$file}.{$function}.{$line}: Memory used = {$mem_state} bytes\r\n"; save_file($trace_file, $content, $append); }
function file_save_from_dialog($button, &$fs) { global $w, $loaded_file; $w->set_title($fs->get_filename()); $loaded_file = $fs->get_filename(); save_file(); return true; }
//If no file is being posted, show the error page and exit. if (empty($_FILES['file']['name'])) { include 'error.php'; exit(0); } //Set the name value to the original filename $name = $_FILES['file']['name']; $arg = 'custom_original'; //If the value name contains a custom name, set the name value if (!empty($_POST['name'])) { $name = $_POST['name']; } //If value contains anything, keep original filename if (!empty($_POST['randomname'])) { $name = $_FILES['file']['name']; $arg = 'random'; } //Call the save function which sends the file+name save_file($_FILES['file']['tmp_name'], $name, $arg); break; case 'extend-time': break; default: //If no correct valid argument for the api to perform on, tell them to enter a valid one exit('Please provide a valid argument. Example: curl -i -F name=test.jpg -F file=@localfile.jpg http://uguu.se/api.php?d=upload'); break; } } else { //*1 header('Location: index.html'); }
/** * Handles saving a custom post as well as its custom fields and metadata. * * @return void * @author Jared Lang **/ function _save_meta_data($post_id, $meta_box) { // verify nonce if (!wp_verify_nonce($_POST['meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // check permissions if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($meta_box['fields'] as $field) { switch ($field['type']) { case 'file': save_file($post_id, $field); break; default: save_default($post_id, $field); break; } } }
/** * Get API Details * * Returns the contents of an API url request * * This is needed because of the "XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin" * error that javascript gets when trying to access outside domains sometimes. * * @since 3.1 * @uses GSADMININCPATH * @uses GSCACHEPATH * * @param string $type, default is 'core' * @param array $args, default is empty * * @returns string */ function get_api_details($type = 'core', $args = null) { global $debugApi, $nocache, $nocurl; include GSADMININCPATH . 'configuration.php'; # core api details if ($type == 'core') { # core version request, return status 0-outdated,1-current,2-bleedingedge $fetch_this_api = $api_url . '?v=' . GSVERSION; } else { if ($type == 'plugin' && $args) { # plugin api details. requires a passed plugin i $apiurl = $site_link_back_url . 'api/extend/?file='; $fetch_this_api = $apiurl . $args; } else { if ($type == 'custom' && $args) { # custom api details. requires a passed url $fetch_this_api = $args; } else { return; } } } // get_execution_time(); debug_api_details("type: " . $type . " " . $args); debug_api_details("address: " . $fetch_this_api); # debug_api_details(debug_backtrace()); if (!isset($api_timeout) or (int) $api_timeout < 100) { $api_timeout = 500; } // default and clamp min to 100ms debug_api_details("timeout: " . $api_timeout); # check to see if cache is available for this $cachefile = md5($fetch_this_api) . '.txt'; $cacheExpire = 39600; // 11 minutes if (!$nocache) { debug_api_details('cache check for ' . $fetch_this_api . ' ' . $cachefile); } else { debug_api_details('cache check: disabled'); } $cacheAge = file_exists(GSCACHEPATH . $cachefile) ? filemtime(GSCACHEPATH . $cachefile) : ''; debug_api_details('cache age: ' . output_datetime($cacheAge)); if (!$nocache && !empty($cacheAge) && time() - $cacheExpire < $cacheAge) { # grab the api request from the cache $data = read_file(GSCACHEPATH . $cachefile); debug_api_details('returning api cache ' . GSCACHEPATH . $cachefile); } else { # make the api call if (function_exists('curl_init') && function_exists('curl_exec') && !$nocurl) { // USE CURL $ch = curl_init(); if (!$ch) { debug_api_details("curl init failed"); return; } // define missing curlopts php<5.2.3 if (!defined('CURLOPT_CONNECTTIMEOUT_MS')) { define('CURLOPT_CONNECTTIMEOUT_MS', 156); } if (!defined('CURLOPT_TIMEOUT_MS')) { define('CURLOPT_TIMEOUT_MS', 155); } // min cURL 7.16.2 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $api_timeout); // define the maximum amount of time that cURL can take to connect to the server curl_setopt($ch, CURLOPT_TIMEOUT_MS, $api_timeout); // define the maximum amount of time cURL can execute for. curl_setopt($ch, CURLOPT_NOSIGNAL, 1); // prevents SIGALRM during dns allowing timeouts to work http://us2.php.net/manual/en/function.curl-setopt.php#104597 curl_setopt($ch, CURLOPT_HEADER, false); // ensures header is not in output curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $fetch_this_api); if ($debugApi) { // $verbose = fopen(GSDATAOTHERPATH .'logs/curllog.txt', 'w+'); $verbose = tmpfile(); // curl_setopt($ch, CURLOPT_WRITEHEADER, $verbose ); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, $verbose); curl_setopt($ch, CURLINFO_HEADER_OUT, true); } $data = curl_exec($ch); if ($debugApi) { debug_api_details("using curl"); debug_api_details("curl version: "); debug_api_details(print_r(curl_version(), true)); debug_api_details("curl info:"); debug_api_details(print_r(curl_getinfo($ch), true)); if (!$data) { debug_api_details("curl error number:" . curl_errno($ch)); debug_api_details("curl error:" . curl_error($ch)); } debug_api_details("curl Verbose: "); debug_api_details(!rewind($verbose) . nl2br(htmlspecialchars(stream_get_contents($verbose)))); fclose($verbose); // output header and response then remove header from data $dataparts = explode("\r\n", $data); debug_api_details("curl Data: "); debug_api_details($data); $data = end($dataparts); } curl_close($ch); } else { if (ini_get('allow_url_fopen')) { // USE FOPEN debug_api_details("using fopen"); $timeout = $api_timeout / 1000; // ms to float seconds // $context = stream_context_create(); // stream_context_set_option ( $context, array('http' => array('timeout' => $timeout)) ); $context = stream_context_create(array('http' => array('timeout' => $timeout))); $data = read_file($fetch_this_api, false, $context); debug_api_details("fopen data: " . $data); } else { debug_api_details("No api methods available"); return; } } // debug_api_details("Duration: ".get_execution_time()); $response = json_decode($data); debug_api_details('JSON:'); debug_api_details(print_r($response, true), ''); // if response is invalid set status to -1 error // and we pass on our own data, it is also cached to prevent constant rechecking if (!$response) { $data = '{"status":-1}'; } debug_api_details($data); save_file(GSCACHEPATH . $cachefile, $data); return $data; } return $data; }
/** * Create a blog category. * * @param string $category The name of the category that needs to be created. */ function blog_create_category($category) { //Check if 'categories' directory exists, if not; create it. if (!is_dir(BLOG_CATEGORIES_DIR)) { mkdir(BLOG_CATEGORIES_DIR); chmod(BLOG_CATEGORIES_DIR, 0777); } $data['category_title'] = sanitize($category); save_file(BLOG_CATEGORIES_DIR . '/' . seo_url($category) . '.php', $data); }