/** * Copy folder tree and returns a true if all tree is copied and false if there was errors. * if $halt_on_errors is true, function will exit if there is error when copying file. * $errors is array of errors. * * @param string $source_dir Source Directory * @param string $destination_dir Destination Directory * @return boolean */ function backup_module_copy_dir($source_dir, $destination_dir, $halt_on_errors, $errors) { if (!is_dir($source_dir)) { $errors[] = "Source directory ({$source_dir}) does not exists"; return false; } else { if (!is_dir($destination_dir)) { if (!recursive_mkdir($destination_dir, 0777, WORK_PATH)) { $errors[] = "Could not create destination directory: {$source_dir}"; return false; } // if } } // if $result = true; $dh = opendir($source_dir); while ($file = readdir($dh)) { if ($file != "." && $file != "..") { $full_src_path = $source_dir . "/" . $file; $dest_src_path = $destination_dir . "/" . $file; if (!is_dir($full_src_path)) { $tmp_result = copy($full_src_path, $dest_src_path); if (!$tmp_result) { $errors[] = 'Failed to copy file: ' . $full_src_path; if ($halt_on_errors) { closedir($dh); return false; } // if } else { $result = $result && $tmp_result; } // if } else { if (!recursive_mkdir($dest_src_path, 0777, WORK_PATH)) { $errors[] = 'Could not create directory: ' . $dest_src_path; return false; } // if $tmp_result = backup_module_copy_dir($full_src_path, $dest_src_path, $halt_on_errors, $errors); if (!$tmp_result && $halt_on_errors) { closedir($dh); return false; } // if $result = $result && $tmp_result; } // if } // if } // while closedir($dh); return $result; }
function getHTML ($attr) { if ($this->fname == '') return ''; $ext = strtolower(file_extension($this->fname)); $appletdir = $this->dir()."/".file_strip_extension($this->fname); $appleturl = dirname($this->url())."/".file_strip_extension($this->fname); recursive_mkdir($appletdir); if ($ext == 'jar' || $ext == 'zip') { $cwd = getcwd(); chdir($appletdir); if ($ext == 'zip') RunTool('unzip', "IN=".$this->path(), 'pipe'); else RunTool('unzip', "IN=".$this->path()." FILE=index.html", 'pipe'); $ok = $this->readHTMLFile('index.html'); chdir($cwd); if (!$ok) return ''; } if (!isset($this->attribs['archive'])) return ''; // generate html file containing the applet $ret = "<html><body>\n"; $ret.= '<div style="margin:0;padding:0"><applet'; foreach ($this->attribs as $k=>$v) $ret .= " $k=\"$v\""; $ret .= ">\n"; foreach ($this->params as $k=>$v) $ret .= "<param name=\"$k\" value=\"$v\"/>\n"; $ret .= "</applet></div>"; $ret .= "</body></html>"; $f = fopen("$appletdir/applet.html", "w"); fputs($f, $ret); fclose($f); // return iframe with above applet page $ret = "<iframe src='$appleturl/applet.html'"; $ret.= " scrolling='no' frameborder='0' marginwidth='0' marginheight='0'"; $ret.= " width='{$this->attribs['width']}' height='{$this->attribs['height']}'>\n"; $ret.= "<p>Your browser doesn't support embedded frames</p>\n"; $ret.= "</iframe>"; return $ret; }
function linkUploadedFile ($fname) { if ($this->isRemote()) return; global $FarmD, $UploadFileFmt; $fmt = preg_replace('/\$Group\b/', '@Group@', $UploadFileFmt); $group = $this->group; if (preg_match('#^//(.*?)/(.*)$#', $fname, $m)) { $group = $m[1]; $fname = $m[2]; } else $fname = preg_replace('#^/([^/].*)$#', '$1', $fname); // remove single leading slashes $uplfname = realpath(preg_replace('/@Group@/', $group, FmtPageName($fmt, $this->pagename))) . "/$fname"; if (!$this->exists() && file_exists($uplfname)) { recursive_mkdir($this->dir()); @unlink($this->path()); // remove previous link @@ kann weg? @symlink($uplfname, $this->path()); } }
$set = array("icon = '{$val_icon}'", "name = '{$val_name}'", "kindid = {$val_kindid}", "url = '{$val_url}'", "type = '{$val_type}'", "width = {$val_width}", "height = {$val_height}", "isresize = {$val_isresize}", "issetbar = {$issetbar}", "isflash = {$val_isflash}", "remark = '{$val_remark}'"); if ($id == '') { $set[] = "dt = now()"; $db->insert(0, 0, 'tb_app', $set); } else { $sqlwhere = "and tbid = {$id}"; $db->update(0, 0, 'tb_app', $set, $sqlwhere); } break; case 'uploadimg': //别人的http上传文件类 require_once 'libs/upload.class.php'; //文件目录 $uploadImagePath = 'dofiles/shortcut/'; if (!file_exists($uploadImagePath)) { recursive_mkdir($uploadImagePath, 0777); } $UploadFile = new HttpUpload(); $tmpname = $_FILES['jUploaderFile']['tmp_name']; $name = $_FILES['jUploaderFile']['name']; $size = $_FILES['jUploaderFile']['size']; $error = $_FILES['jUploaderFile']['error']; if (strlen(trim($tmpname)) > 0) { $UploadFile->getFile($tmpname, $name, $name, $error); if (!$UploadFile->upload(md5(uniqid(rand(), true)), $uploadImagePath)) { exit; } //图片路径 $returnImangeUrl = $uploadImagePath . $UploadFile->getFileName(); echo "{success:true,fileUrl:'" . $returnImangeUrl . "'}"; }
function getRemoteImg() { $url = $this->request('url'); $url = urldecode($url); $filename = md5($url . mktime(0, 0, 0, date("n"), date("j"), date("Y"))); $fileadr = SMARTYCACHEPATH . $filename; $root_path = rad_config::getParam('rootPath'); $theme_name = rad_config::getParam('theme.default'); if (empty($theme_name)) { $theme_name = 'default'; } $msg = ''; if ($url and strpos($url, "http") === 0) { $opts = array('http' => array('method' => "GET", 'max_redirects' => 5, 'timeout' => 5, 'ignore_errors' => false)); $context = stream_context_create($opts); $i = 3; $fileData = NULL; //try to recieve image file data 3 times with timeout 5 seconds do { $header = get_headers($url, 1); if (isset($header['Content-Length'])) { $contentLength = (int) $header['Content-Length']; $maxPost = (int) $this->configSys('max_post'); if ($contentLength <= $maxPost) { if (!file_exists($fileadr)) { $fileData = @file_get_contents($url, false, $context); if ($fileData) { $i = 0; } else { $i--; } } else { $fileExt = $this->_getImageExtension($fileadr); if ($fileExt) { die(json_encode(array('is_success' => true, 'theme' => $theme_name, 'origname' => $filename, 'filename' => $filename . '.' . $fileExt))); } else { unlink($fileadr); $i--; } } } else { $i = 0; $msg = $this->lang('imagesizetoobig.catalog.error'); } } } while ($i > 0); if ($fileData) { // if file data recieved, put it on the server into temp folder $hFile = fopen($fileadr, 'w'); if ($hFile) { fputs($hFile, $fileData); flush(); fclose($hFile); $fileExt = $this->_getImageExtension($fileadr); if ($fileExt) { $resizedFile = $root_path . 'cache' . DS . 'img' . DS . $theme_name . DS . 'corecatalog' . DS . 'product_thumb' . DS . $filename . '.' . $fileExt; $resizedPath = dirname($resizedFile); if (recursive_mkdir($resizedPath, 0777)) { $gdImg = new rad_gd_image(); if ($gdImg->set($fileadr, $resizedFile, 'product_thumb')) { $r = $gdImg->resize(); if ($r) { die(json_encode(array('is_success' => true, 'theme' => $theme_name, 'origname' => $filename, 'filename' => $filename . '.' . $fileExt))); } else { unlink($fileadr); $msg = $gdImg->getError(); } } else { unlink($fileadr); $msg = $gdImg->getError(); } } else { unlink($fileadr); $msg = "Can not create dir! Path: {$resizedPath}"; } } else { unlink($fileadr); $msg = $this->lang('wrongfiledata.catalog.error'); } } else { $msg = $this->lang('cannotcreatefile.catalog.error'); } } } else { $msg = $this->lang('wrongimageurl.catalog.error'); } die(json_encode(array('is_success' => false, 'msg' => $msg))); }
/** * Outputs selected style to output folder * * @param string $style_name * @return boolean */ function outputStyle($style_name = 'default') { $style_path = PROJECT_EXPORTER_MODULE_PATH . '/models/styles/' . $style_name; if (!is_dir($style_path)) { $this->execution_log->addWarning(lang('Style does not exists')); return false; } // if $output_style_folder = $this->getRootOutputFolder() . '/style'; if (!recursive_mkdir($output_style_folder, 0777, WORK_PATH)) { $this->execution_log->addWarning(lang('Could not create style directory')); return false; } // if return copy_dir($style_path, $output_style_folder); }
/** * Install this module * * @param void * @return boolean */ function install() { // invoices $this->createTable('invoices', array('id smallint(5) unsigned NOT NULL auto_increment', 'company_id smallint(5) unsigned NOT NULL default \'0\'', 'project_id smallint(5) unsigned default NULL', 'currency_id tinyint(4) NOT NULL default \'0\'', 'language_id tinyint(3) NOT NULL default \'0\'', 'number varchar(50) NOT NULL', 'company_name varchar(50) NOT NULL', 'company_address text', 'comment varchar(255) default NULL', 'note text', 'status tinyint(4) NOT NULL default \'0\'', 'issued_on date default NULL', 'issued_by_id int(11) default NULL', 'issued_by_name varchar(100) default NULL', 'issued_by_email varchar(150) default NULL', 'issued_to_id int(11) default NULL', 'due_on date default NULL', 'closed_on datetime default NULL', 'closed_by_id int(11) default NULL', 'closed_by_name varchar(100) default NULL', 'closed_by_email varchar(150) default NULL', 'created_on datetime default NULL', 'created_by_id int(10) unsigned default NULL', 'created_by_name varchar(100) default NULL', 'created_by_email varchar(150) default NULL'), 'PRIMARY KEY (id)'); // Invoice Items $this->createTable('invoice_items', array('id int(11) unsigned NOT NULL auto_increment', 'invoice_id smallint(5) unsigned NOT NULL default \'0\'', 'position int(11) NOT NULL', 'tax_rate_id tinyint(3) unsigned NOT NULL default \'0\'', 'description varchar(255) NOT NULL', 'quantity DECIMAL(13,3) unsigned NOT NULL default \'1\'', 'unit_cost DECIMAL(13,3) NOT NULL default \'0.00\''), array('PRIMARY KEY (id)', 'KEY invoice_id (invoice_id,position)')); $this->createTable('invoice_item_templates', array('id int(11) unsigned NOT NULL auto_increment', 'tax_rate_id tinyint(3) unsigned NOT NULL default \'0\'', 'description varchar(255) NOT NULL', 'quantity DECIMAL(13,3) unsigned NOT NULL default \'1\'', 'unit_cost DECIMAL(13,3) NOT NULL default \'0.00\'', "position int(11) NOT NULL default '0'"), array('PRIMARY KEY (id)')); // Invoice payments $this->createTable('invoice_payments', array('id int(10) unsigned NOT NULL auto_increment', 'invoice_id smallint(5) unsigned NOT NULL', 'amount DECIMAL(13,3) NOT NULL', 'paid_on date NOT NULL', 'comment text', 'created_on datetime default NULL', 'created_by_id int(10) unsigned default NULL', 'created_by_name varchar(100) default NULL', 'created_by_email varchar(150) default NULL'), array('PRIMARY KEY (id)', 'KEY invoice_id (invoice_id)')); // Invoice note templates $this->createTable('invoice_note_templates', array('id int(10) unsigned NOT NULL auto_increment', 'position int(11) NOT NULL', 'name varchar(150) default NULL', 'content text'), 'PRIMARY KEY (id)'); // Invoice time records $this->createTable('invoice_time_records', array('invoice_id smallint(5) unsigned NOT NULL', 'item_id int(10) unsigned NOT NULL', 'time_record_id int(10) unsigned NOT NULL'), 'PRIMARY KEY (invoice_id,time_record_id)'); // invoice_tax_rates $this->createTable('tax_rates', array('id tinyint(3) unsigned NOT NULL auto_increment', 'name varchar(50) NOT NULL', 'percentage DECIMAL(6,3) NOT NULL'), 'PRIMARY KEY (id)'); db_execute("INSERT INTO " . TABLE_PREFIX . "tax_rates (id, name, percentage) VALUES\n (1, 'VAT', 17.50);"); $this->createTable('currencies', array('id smallint(6) NOT NULL auto_increment', 'name varchar(50) NOT NULL', 'code varchar(3) NOT NULL', 'default_rate DECIMAL(13,3) unsigned NOT NULL', 'is_default tinyint(1) unsigned NOT NULL default \'0\''), array('PRIMARY KEY (id)')); db_execute("INSERT INTO " . TABLE_PREFIX . "currencies (id, name, code, default_rate, is_default) VALUES\n (1, 'Euro', 'EUR', 1, 0),\n (2, 'US Dollar', 'USD', 1, 1),\n (3, 'British Pound', 'GBP', 1, 0),\n (4, 'Japanese Yen', 'JPY', 1, 0)"); // config options $this->addConfigOption('prefered_currency', SYSTEM_CONFIG_OPTION, null); $this->addConfigOption('invoicing_number_pattern', SYSTEM_CONFIG_OPTION, ':invoice_in_year/:current_year'); $this->addConfigOption('invoicing_number_date_counters', SYSTEM_CONFIG_OPTION, null); // create and prepopulate company identity $owner_company = get_owner_company(); $owner_company_address = $owner_company->getConfigValue('office_address'); $this->addConfigOption('invoicing_company_name', SYSTEM_CONFIG_OPTION, $owner_company->getName()); $this->addConfigOption('invoicing_company_details', SYSTEM_CONFIG_OPTION, $owner_company_address); // default PDF settings $this->addConfigOption('invoicing_pdf_paper_format', SYSTEM_CONFIG_OPTION, 'A4'); $this->addConfigOption('invoicing_pdf_paper_orientation', SYSTEM_CONFIG_OPTION, 'Portrait'); $this->addConfigOption('invoicing_pdf_header_text_color', SYSTEM_CONFIG_OPTION, '000000'); $this->addConfigOption('invoicing_pdf_page_text_color', SYSTEM_CONFIG_OPTION, '000000'); $this->addConfigOption('invoicing_pdf_border_color', SYSTEM_CONFIG_OPTION, '000000'); $this->addConfigOption('invoicing_pdf_background_color', SYSTEM_CONFIG_OPTION, 'FFFFFF'); // email templates $this->addEmailTemplate('issue', "Invoice #:invoice_number has been issued", "<p>Hi,</p>\n<p><a href=\":issued_by_url\">:issued_by_name</a> just issued invoice <b>#:invoice_number</b> to you. Access <a href=\":invoice_url\">invoice details here</a> or <a href=\":pdf_url\">download PDF version here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('issued_by_name', 'issued_by_url', 'invoice_number', 'invoice_url', 'pdf_url')); $this->addEmailTemplate('billed', "Invoice #:invoice_number has been billed", "<p>Hi,</p>\n<p><a href=\":closed_by_url\">:closed_by_name</a> just marked invoice <b>#:invoice_number</b> as billed. Access <a href=\":invoice_url\">invoice details and payments here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('closed_by_name', 'closed_by_url', 'invoice_number', 'invoice_url')); $this->addEmailTemplate('cancel', "Invoice #:invoice_number has been canceled", "<p>Hi,</p>\n<p><a href=\":closed_by_url\">:closed_by_name</a> just canceled invoice <b>#:invoice_number</b>. Access <a href=\":invoice_url\">invoice details here</a>.</p>\n<p>Best,<br />:owner_company_name</p>", array('closed_by_name', 'closed_by_url', 'invoice_number', 'invoice_url')); recursive_mkdir(WORK_PATH . '/invoices', 0777, WORK_PATH); return parent::install(); }
if (empty($module)) { errorMsg('Module name is not set!'); } if (!preg_match('/^[a-zA-Z][a-zA-Z0-9]{2,31}$/', $module)) { errorMsg('Module name is incorrect!'); } if (empty($filename)) { errorMsg('File name is not set!'); } if (!preg_match('~^[a-zA-Z0-9][-_.a-zA-Z0-9]*(?:/[a-zA-Z0-9][-_.a-zA-Z0-9]*)*\\.(?:js|css)$~i', $filename)) { errorMsg('File name is incorrect!'); } $theme_name = rad_themer::getCurrentTheme(); $cachedFile = $config['rootPath'] . 'cache' . DS . $type . DS . $theme_name . DS . $module . DS . $filename; $cachedPath = dirname($cachedFile); if (!recursive_mkdir($cachedPath, 0777)) { errorMsg('Can not create dir! Path: {$cachedPath}'); } if (!file_exists($cachedFile) || time() - filemtime($cachedFile) >= (int) $config['cache.power.time']) { $originalFile = rad_themer::getFilePath($theme_name, 'jscss', $module, $filename); if (!$originalFile) { errorMsg('File does not exist!'); } try { rad_jscss::copyToCache($originalFile, $cachedFile); } catch (Exception $e) { errorMsg("Could not copy file {$originalFile} to {$cachedFile}"); } } if (!@readfile($cachedFile)) { errorMsg("Error reading {$cachedFile}");
} if (empty($filename)) { errorMsg("File name is not set!"); } if (!preg_match('~^[a-zA-Z0-9][-_.a-zA-Z0-9]*(?:/[a-zA-Z0-9][-_.a-zA-Z0-9]*)*\\.(?:jp(?:e?g|e|2)|gif|png|gd)$~i', $filename)) { //filename is a correct image file name errorMsg("File name is incorrect!"); } $theme_name = rad_themer::getCurrentTheme(); $originalFile = rad_themer::getFilePath($theme_name, 'img', $module, $filename); if (!$originalFile) { errorMsg("File does not exist!"); } $resizedFile = $config['rootPath'] . 'cache' . DS . 'img' . DS . $theme_name . DS . $module . DS . $preset . DS . $filename; $resizedPath = dirname($resizedFile); if (!recursive_mkdir($resizedPath, 0777)) { errorMsg("Can not create dir! Path: {$resizedPath}"); } if (!file_exists($resizedFile) || time() - filemtime($resizedFile) >= (int) $config['cache.power.time']) { $img = new rad_gd_image(); if ($img->set($originalFile, $resizedFile, $preset)) { $r = $img->resize(); if (!$r) { errorMsg($img->getError()); } } else { errorMsg($img->getError()); } } switch (rad_gd_image::getFileExtension($resizedFile)) { case 'jpg':
public function get3DBinFile($params) { if (empty($params['cat_id']) or !(int) $params['cat_id']) { throw new rad_exception('Cat id can\'t be empty when getting file!!! Some error!'); } set_time_limit($this->config('partners.3dbin.time')); $params['action'] = 'getfile'; $params['lang'] = $this->getCurrentLangID(); $params['email'] = $this->config('taberna.user'); $params['pass'] = $this->config('taberna.pass'); $params['url'] = SITE_URL; $file = $this->_getURL($this->_threeDBinService, $params); $destination = DOWNLOAD_FILES_DIR . '3dbin' . DS . $params['cat_id'] . '_' . md5(time() . '3dbin') . '.swf'; if (!is_dir(dirname($destination))) { recursive_mkdir(dirname($destination), 0777); } safe_put_contents($destination, $file); return $destination; }
/** * Import language from XML form * * @param void * @return null */ function import() { if (!extension_loaded('xml') || !function_exists('xml_parser_create')) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if $import_url = assemble_url('admin_languages_import'); $this->wireframe->addBreadCrumb(lang('Import Language'), $import_url); $step = $this->request->post('wizard_step') ? $this->request->post('wizard_step') : 'initial'; if ($step == 'initial') { $next_step = 'review'; } else { if ($step == 'review') { $next_step = 'finalize'; } } // if if (!folder_is_writable(LOCALIZATION_PATH)) { $this->wireframe->addPageMessage(lang('Localization folder: <strong>:folder</strong> is not writable', array('folder' => LOCALIZATION_PATH)), PAGE_MESSAGE_ERROR); $this->smarty->assign('import_enabled', false); } else { $this->smarty->assign(array('import_url' => $import_url, 'step' => $step, 'next_step' => $next_step, 'import_enabled' => true)); if ($this->request->isSubmitted()) { switch ($step) { case 'initial': break; case 'review': $xml_file = $_FILES['xml']['tmp_name']; if (!is_file($xml_file)) { flash_error('You need to upload XML file first'); $this->redirectToReferer($import_url); } // if require_once ANGIE_PATH . '/classes/xml/xml2array.php'; $language = xml2array(file_get_contents($xml_file)); if (!$language) { flash_error('Language XML file is corrupted'); $this->redirectToReferer($import_url); } // if $locale = $language['language']['info']['locale']['value']; $name = $language['language']['info']['name']['value']; $ac_version = $language['language']['info']['ac_version']['value']; $system_version = $this->application->version ? $this->application->version : '1.0'; if (!$locale || !$name) { flash_error('Language XML file is corrupted'); $this->redirectToReferer($import_url); } // if if (Languages::localeExists($locale)) { flash_error('Language with locale :locale is already installed on system', array('locale' => $locale)); $this->redirectToReferer($import_url); } // if if (Languages::nameExists($name)) { flash_error('Language with name :name is already installed on system', array('name' => $name)); $this->redirectToReferer($import_url); } // if $attachment = make_attachment($_FILES['xml']); if (!$attachment || is_error($attachment)) { flash_error($attachment->getMessage(), array('name' => $name)); $this->redirectToReferer($import_url); } // if if (version_compare($ac_version, $system_version, '=') != true) { $this->wireframe->addPageMessage(lang('Current activeCollab version is <strong>:system_version</strong> and this translation is made for <strong>:ac_version</strong> version. Importing can continue, but this translation may not work on your system', array('system_version' => $system_version, 'ac_version' => $ac_version)), 'warning'); } // if $this->smarty->assign(array('language_ac_version' => $ac_version, 'language_name' => $name, 'language_locale' => $locale, 'system_version' => $system_version, 'attachment_id' => $attachment->getId())); $this->setTemplate('import_review'); break; case 'finalize': $attachment_id = $this->request->post('attachment_id'); $attachment = Attachments::findById($attachment_id); if (!instance_of($attachment, 'Attachment')) { flash_error('There was some unknown error, please try again'); $this->redirectTo($import_url); } // if require_once ANGIE_PATH . '/classes/xml/xml2array.php'; $language_array = xml2array(file_get_contents(UPLOAD_PATH . '/' . $attachment->getLocation())); if (!$language_array) { flash_error('Uploaded file is not valid XML'); $this->redirectToReferer($import_url); } // if $language_locale = $language_array['language']['info']['locale']['value']; $language_name = $language_array['language']['info']['name']['value']; $language_version = $language_array['language']['info']['ac_version']['value']; $language = new Language(); $language->setLocale($language_locale); $language->setName($language_name); $result = recursive_mkdir($language->getLocalizationPath(), 0777, LOCALIZATION_PATH); if (!$result) { flash_error('Could not create localization folder'); $this->redirectToReferer($import_url); } // if $save = $language->save(); if (!$save || is_error($save)) { flash_error($save->getMessage()); $this->redirectToReferer($import_url); } // if $info = array('name' => $language_name, 'code' => $language_locale, 'version' => $language_version); $result = file_put_contents($language->getLocalizationPath() . '/info.php', "<?php return " . var_export($info, true) . " ?>"); if (is_foreachable($language_array['language']['translations']['module'])) { foreach ($language_array['language']['translations']['module'] as $module_translation) { if (is_foreachable($module_translation['translation'])) { $module_name = $module_translation['attr']['name']; $output = array(); foreach ($module_translation['translation'] as $translation) { if (is_array($translation)) { $phrase = $translation['attr']['phrase']; $translation_value = $translation['value']; $output[$phrase] = $translation_value; } // if } // foreach $filename = Languages::getTranslationPath($language, $module_name); file_put_contents($filename, "<?php return " . var_export($output, true) . " ?>"); } // if } // foreach } // if $attachment->delete(); flash_success('Language imported successfully'); $this->redirectTo('admin_languages'); break; default: break; } } // if } // if }
function chdir_mkdir ($dir) { recursive_mkdir($dir); $cwd = getcwd(); chdir($dir); return $cwd; }
public function add() { global $mysql, $langArray, $attributes; $user_id = $_SESSION['user']['user_id']; if (!$user_id) { return false; } //临时文件目录 $temporary_dir = DATA_SERVER_PATH . '/uploads/temporary/' . $user_id . '/'; if (!isset($_POST['name']) || trim($_POST['name']) == '') { $error['name'] = $langArray['error_not_set_name']; } if (!isset($_POST['description']) || trim($_POST['description']) == '') { $error['description'] = $langArray['error_not_set_description']; } //(缩略图) if (!isset($_POST['thumbnail']) || trim($_POST['thumbnail']) == '') { $error['thumbnail'] = $langArray['error_not_set_thumbnail']; } else { $file = pathinfo($_POST['thumbnail']); if (!in_array(strtolower($file['extension']), $this->support_format(1))) { $error['thumbnail'] = $langArray['error_thumbnail_jpg']; } elseif (!file_exists($temporary_dir . $_POST['thumbnail'])) { $error['thumbnail'] = $langArray['error_thumbnail_jpg']; } } // (预览图) $theme_preview_arr = explode(',', $_POST['theme_preview']); if (!isset($theme_preview_arr) || !is_array($theme_preview_arr)) { $error['theme_preview'] = $langArray['error_not_set_theme_preview']; } else { foreach ($theme_preview_arr as $theme_f) { $theme_file = pathinfo($theme_f); if (!in_array(strtolower($theme_file['extension']), $this->support_format(0))) { $error['theme_preview'] = $langArray['error_theme_preview_jpg']; } elseif (!file_exists($temporary_dir . $theme_f)) { $error['theme_preview'] = $langArray['error_not_file']; } } } // (封面) if (!isset($_POST['first_preview']) || trim($_POST['first_preview']) == '') { $error['first_preview'] = $langArray['error_not_set_first_preview']; } else { $file = pathinfo($_POST['first_preview']); if (!in_array(strtolower($file['extension']), $this->support_format(0))) { $error['first_preview'] = $langArray['error_theme_preview_jpg']; } elseif (!file_exists($temporary_dir . $_POST['first_preview'])) { $error['first_preview'] = $langArray['error_not_file']; } } // (主程序包) if (!isset($_POST['main_file']) || trim($_POST['main_file']) == '') { $error['main_file'] = $langArray['error_not_set_main_file']; } else { $file = pathinfo($_POST['main_file']); if (strtolower($file['extension']) != 'zip') { $error['main_file'] = $langArray['error_main_file_zip']; } elseif (!file_exists($temporary_dir . $_POST['main_file'])) { $error['main_file'] = $langArray['error_main_file_zip']; } } if (!isset($_POST['category'])) { $error['category'] = $langArray['error_not_set_category']; } elseif (!is_array($_POST['category'])) { $error['category'] = $langArray['error_not_set_category']; } elseif (!count($_POST['category'])) { $error['category'] = $langArray['error_not_set_category']; } if (is_array($attributes)) { $attributesError = false; foreach ($attributes as $a) { if (!isset($_POST['attributes'][$a['id']])) { $attributesError = true; break; } } if ($attributesError) { $error['attributes'] = $langArray['error_set_all_attributes']; } } //标签 if (!isset($_POST['tags']) || empty($_POST['tags'])) { $error['tags_features'] = $langArray['error_not_set_tags']; } else { $tags_data = explode(',', $_POST['tags']); if (count($tags_data) > 6) { $error['tags_features'] = $langArray['error_not_set_tags_tomore']; } } if (!isset($_POST['source_license'])) { $error['source_license'] = $langArray['error_not_set_source_license']; } if (isset($_POST['demo_url']) && trim($_POST['demo_url']) && filter_var($_POST['demo_url'], FILTER_VALIDATE_URL) === false) { $error['demo_url'] = $langArray['error_demo_url']; } if ($_POST['suggested_price'] && !preg_match('#^\\d+(?:\\.\\d{1,})?$#', $_POST['suggested_price'])) { $error['suggested_price'] = $langArray['error_suggested_price']; } if (isset($error)) { return $error; } if (!isset($_POST['demo_url'])) { $_POST['demo_url'] = ''; } if (!isset($_POST['comments_to_reviewer'])) { $_POST['comments_to_reviewer'] = ''; } if (!isset($_POST['free_request'])) { $_POST['free_request'] = 'true'; } require_once ROOT_PATH . '/apps/categories/models/categories.class.php'; $categoriesClass = new categories(); $mysql->query("\n\t\t\tINSERT INTO `items` (\n\t\t\t\t`user_id`,\n\t\t\t\t`name`,\n\t\t\t\t`description`,\n\t\t\t\t`main_file_name`,\n `thumbnail`,\n\t\t\t\t`theme_preview`,\n\t\t\t\t`main_file`,\n\t\t\t\t`demo_url`,\n\t\t\t\t`reviewer_comment`,\n\t\t\t\t`datetime`,\n\t\t\t\t`status`,\n\t\t\t\t`suggested_price`,\n\t\t\t\t`free_request`\n\t\t\t)\n\t\t\tVALUES (\n\t\t\t\t'" . intval($_SESSION['user']['user_id']) . "',\n\t\t\t\t'" . sql_quote($_POST['name']) . "',\n\t\t\t\t'" . sql_quote($_POST['description']) . "',\n\t\t\t\t'" . sql_quote($_SESSION['temp']['uploaded_files'][$_POST['main_file']]['name']) . "',\n '" . sql_quote($_POST['thumbnail']) . "',\n\t\t\t\t'" . sql_quote($_POST['first_preview']) . "',\n\t\t\t\t'" . sql_quote($_POST['main_file']) . "',\n\t\t\t\t'" . sql_quote($_POST['demo_url']) . "',\n\t\t\t\t'" . sql_quote($_POST['comments_to_reviewer']) . "',\n\t\t\t\tNOW(),\n 'queue',\n\t\t\t\t'" . (double) $_POST['suggested_price'] . "',\n\t\t\t\t'" . sql_quote($_POST['free_request']) . "'\n\t\t\t)\n\t\t"); $itemID = $mysql->insert_id(); $allCategories = $categoriesClass->getAll(); if (is_array($_POST['category'])) { foreach ($_POST['category'] as $category_id) { $categories = $categoriesClass->getCategoryParents($allCategories, $category_id); $categories = explode(',', $categories); array_pop($categories); $categories = array_reverse($categories); $categories = ',' . implode(',', $categories) . ','; $mysql->query("\n\t\t\t\t\tINSERT INTO `items_to_category` (\n\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t`categories`\n\t\t\t\t\t)\n\t\t\t\t\tVALUES (\n\t\t\t\t\t\t'" . sql_quote($itemID) . "',\n\t\t\t\t\t\t'" . sql_quote($categories) . "'\n\t\t\t\t\t)\n\t\t\t\t"); } } else { $categories = $categoriesClass->getCategoryParents($allCategories, $_POST['category']); $categories = explode(',', $categories); array_pop($categories); $categories = array_reverse($categories); $categories = ',' . implode(',', $categories) . ','; $mysql->query("\n INSERT INTO `items_to_category` (\n `item_id`,\n `categories`\n )\n VALUES (\n '" . sql_quote($itemID) . "',\n '" . sql_quote($categories) . "'\n )\n "); } #创建文件夹 recursive_mkdir(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/'); recursive_mkdir(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/preview/'); #剪裁缩略图并创建预览图 require_once ENGINE_PATH . '/classes/image.class.php'; $imageClass = new Image(); $imageClass->crop($temporary_dir . $_POST['thumbnail'], 90, 90); copy($temporary_dir . $_POST['thumbnail'], DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/' . $_POST['thumbnail']); @unlink($temporary_dir . $_POST['thumbnail']); $file_first = pathinfo($_POST['first_preview']); if (in_array(strtolower($file_first['extension']), $this->support_format(1))) { //第一张预览图地址 copy($temporary_dir . $_POST['first_preview'], DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/' . $_POST['first_preview']); @unlink($temporary_dir . $_POST['first_preview']); $imageClass->crop(DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/' . $_POST['first_preview'], 590, 300); } elseif (in_array(strtolower($file_first['extension']), $this->support_format(0))) { copy($temporary_dir . $_POST['first_preview'], DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/' . $_POST['first_preview']); @unlink($temporary_dir . $_POST['first_preview']); } //主程序包路径 copy($temporary_dir . $_POST['main_file'], DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/' . $_POST['main_file']); @unlink($temporary_dir . $_POST['main_file']); //预览包 foreach ($theme_preview_arr as $item_dir) { copy($temporary_dir . $item_dir, DATA_SERVER_PATH . '/uploads/' . $this->uploadFileDirectory . $itemID . '/preview/' . $item_dir); @unlink($temporary_dir . $item_dir); #插入预览图 $this->save_theme_preview($itemID, DATA_SERVER . '/uploads/' . $this->uploadFileDirectory . $itemID . '/preview/' . $item_dir); } unset($_SESSION['temp']['uploaded_files']); #插入标签 require_once ROOT_PATH . '/apps/tags/models/tags.class.php'; $tags = new tags(); //删除原绑定标签 $tags->del_by_item_id($itemID); //重写绑定标签 $tags_data = explode(',', $_POST['tags']); $tag_arr = array(); foreach ($tags_data as $val) { $tags->add_tags(array('item_id' => $itemID, 'tag_id' => $val)); } #插入属性 $_POST['attributes'] = (array) (isset($_POST['attributes']) ? $_POST['attributes'] : array()); foreach ($_POST['attributes'] as $cID => $a) { if (is_array($a)) { foreach ($a as $ai) { $mysql->query("\n\t\t\t\t\t\tINSERT INTO `items_attributes` (\n\t\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t\t`attribute_id`,\n\t\t\t\t\t\t\t`category_id`\n\t\t\t\t\t\t)\n\t\t\t\t\t\tVALUES (\n\t\t\t\t\t\t\t'" . intval($itemID) . "',\n\t\t\t\t\t\t\t'" . sql_quote($ai) . "',\n\t\t\t\t\t\t\t'" . sql_quote($cID) . "'\n\t\t\t\t\t\t)\n\t\t\t\t\t"); } } else { $mysql->query("\n\t\t\t\t\tINSERT INTO `items_attributes` (\n\t\t\t\t\t\t`item_id`,\n\t\t\t\t\t\t`attribute_id`,\n\t\t\t\t\t\t`category_id`\n\t\t\t\t\t)\n\t\t\t\t\tVALUES (\n\t\t\t\t\t\t'" . intval($itemID) . "',\n\t\t\t\t\t\t'" . sql_quote($a) . "',\n\t\t\t\t\t\t'" . sql_quote($cID) . "'\n\t\t\t\t\t)\n\t\t\t\t"); } } return true; }
if ($_FILES['xfile']['size'] > $uploadFileMaxSize * 1048576) { $r->error = "上传文件单个大小不能超过 {$uploadFileMaxSize} MB"; } else { $icon = ''; foreach ($uploadFileType as $uft) { if ($uft['ext'] == $extension) { $icon = $uft['icon']; break; } } if ($icon == '') { $icon = 'img/ui/file_unknow.png'; } //生成文件存放路径 $dir = 'uploads/member/' . session('member_id') . '/file/'; if (!is_dir($dir)) { //循环创建目录 recursive_mkdir($dir); } //上传 move_uploaded_file($_FILES['xfile']["tmp_name"], $dir . $file); $r->dir = $dir; $r->file = iconv('gb2312', 'UTF-8', $file); $r->name = iconv('gb2312', 'UTF-8', $name); $r->extension = iconv('gb2312', 'UTF-8', $extension); $r->icon = $icon; } } echo json_encode($r); break; }
function safe_put_contents($filename, $data, $flags = 0) { if (!recursive_mkdir(dirname($filename))) { return false; } return file_put_contents($filename, $data, $flags) !== false; }
function convertPagesToXML ($pageinfo) { $xml = "<!-- Frontmatter -->\n"; if ($pageinfo['preface'] != '') { // extract title and author information message("processing trail page ".$this->pagename, 'start'); while (preg_match('/(\(:(\w+)(\s+.+?)?:\).*?\(:end\2:\)\s*)/s', $pageinfo['preface'], $m)) { $xml .= preg_replace('#^\s*<p>(.*)</p>\s*$#s', '$1', MarkupToHTML($this->pagename, trim($m[1]))); $pageinfo['preface'] = str_replace($m[1], '', $pageinfo['preface']); } while (preg_match('/(\(:\w+(\s+.+?)?:\))\s*/s', $pageinfo['preface'], $m)) { $xml .= preg_replace('#^\s*<p>(.*)</p>\s*$#s', '$1', MarkupToHTML($this->pagename, trim($m[1]))); $pageinfo['preface'] = str_replace($m[1], '', $pageinfo['preface']); } message('', 'end'); } unset($pageinfo['preface']); foreach ($pageinfo as $pi) { global $WikiDir; $pagefile = $WikiDir->pagefile($pi['pagename']); $cachefile = $this->outputDir($pi['pagename'])."/cache.xml"; $msg = "processing page ".htmlentities($pi['pagename']); if (0) { // @@ message("$msg from cache", 'start'); $localxml = file_get_contents($cachefile); } else { global $ProcessedPages; $empty = file_exists($pagefile) ? '' : ' (page empty)'; message($msg.$empty, 'start'); $ProcessedPages[] = $pi['pagename']; list($group) = explode('.', $pi['pagename']); $page = ReadPage($pi['pagename']); $text = trim($page['text']); $text = preg_replace('/^!+.*?\\n/', '', $text); // remove title header from wiki page $text = html_entity_decode($text); $title = $pi['title'] ? $pi['title'] : $pi['pagename']; $sectcmd = "(:section level=$pi[depth] title=\"$pi[title]\" label=".Keep($pi[pagename]).":)"; $text = "{$sectcmd}\n$text"; // ...then add a title with name of wiki page $text = str_replace(chr(128), '¤', $text); // das "Windows" ¤-Zeichen liegt auf 128... $localxml = MarkupToHTML($pi['pagename'], $text); // generate XML of current wiki page if (file_exists($pagefile)) { // does wikipage exist? recursive_mkdir(dirname($cachefile)); $f = fopen($cachefile, 'w'); fputs($f, $localxml); fclose($f); } } $xml .= $localxml; message('', 'end'); } // close all open section elements $xml .= flush_section(0); $xml = "<article page-width='210mm' page-height='297mm' margin='2cm'>$xml</article>"; return $xml; }
} $rootdir = ''; if (strpos($namespace, '|') !== false) { $segments = explode('|', $namespace); $segments_tmp = array(); foreach ($segments as $segment) { if (trim($segment) != '') { array_push($segments_tmp, $segment); } } $segments = $segments_tmp; unset($segments_tmp); $segmentPath = implode('/', array_slice($segments, 0, -1)); $rootdir .= $segmentPath; //mkdir($rootdir, 0700, true); @recursive_mkdir($rootdir . '/'); //die($rootdir); $namespace = $segments[sizeof($segments) - 1]; } else { $rootdir = './'; } // TODO: // - full rewrite to disk using... // - post only to write, which makes sense // - get rid of all other parameters // load contents $datastore = $rootdir . '/' . $user . "." . $namespace . '.json'; $store->load($datastore); // return value helper $returnValue = null; // wrap data (refactor step1; refactor step2 will be scaffolding..)
/** * Saves the page into DB */ function saveArticle() { if ($this->request('hash') == $this->hash()) { $model = rad_instances::get('model_corearticles_articles'); if ($this->request('action_sub') == 'edit') { $art_id = (int) $this->request('art_id'); if ((int) $this->request('id') and !$art_id) { $art_id = (int) $this->request('id'); } if ($art_id) { $articles_item = $model->getItem($art_id); $articles_item->MergeArrayToStruct($this->getAllRequest()); } else { $this->securityHoleAlert(__FILE__, __LINE__, $this->getClassName()); return; } } else { $articles_item = new struct_corearticles_articles($this->getAllRequest()); } if ($this->request('del_img')) { $this->_deleteAllImg($articles_item->art_img); } if (isset($_FILES['articles_image']) && count($_FILES['articles_image'])) { if ((int) $_FILES['articles_image']['size']) { if ($articles_item->art_img) { $this->_deleteAllImg($articles_item->art_img); } $articles_item->art_img = $this->getCurrentUser()->u_id . md5(time() . $this->getCurrentUser()->u_id . $_FILES['articles_image']['name']) . '.' . strtolower(fileext($_FILES['articles_image']['name'])); if (!file_exists(COREARTICLES_IMG_PATH . 'articles')) { //create folder, if not exists recursive_mkdir(COREARTICLES_IMG_PATH . 'articles'); } move_uploaded_file($_FILES['articles_image']['tmp_name'], COREARTICLES_IMG_PATH . 'articles' . DS . $articles_item->art_img); } //size } $articles_item->art_shortdesc = stripslashes($this->request('FCKeditorShortDescription')); $articles_item->art_fulldesc = stripslashes($this->request('FCKeditorFullDescription')); $articles_item->art_showonmain = $this->request('art_showonmain') == 'on' ? '1' : '0'; $articles_item->art_isweek = $this->request('art_isweek') == 'on' ? '1' : '0'; $articles_item->art_active = $this->request('art_active') == 'on' ? '1' : '0'; $articles_item->art_langid = $this->getContentLangID(); $articles_item->art_dateupdated = now(); $articles_item->art_usercreated = $this->getCurrentUser()->u_id; //IS HAVE TAGS? if ($this->_have_tags) { if (strlen(trim($this->request('articletags')))) { $model_tags = rad_instances::get('model_coreresource_tags'); $tags_array = $model_tags->addItems(trim($this->request('articletags'))); if (count($tags_array)) { foreach ($tags_array as $id_tag => $tag_id) { $articles_item->tags[] = new struct_coreresource_tags_in_item(array('tii_item_id' => $articles_item->art_id, 'tii_tag_id' => $tag_id)); } } } } if ($this->request('action_sub') == 'add') { $articles_item->art_datecreated = now(); $this->_inserted_id = $model->insertItem($articles_item); } elseif ($this->request('action_sub') == 'edit') { $rows = $model->updateItem($articles_item); } $tree_id = $articles_item->art_treid; if ($this->request('returntorefferer') == '0') { $this->redirect($this->makeURL('alias=SITE_ALIAS') . '#nic/' . $tree_id); } elseif ($this->request('action_sub') == 'add') { $this->redirect($this->makeURL('action=' . $this->request('action') . '&nid=' . $tree_id . '&id=' . $this->_inserted_id)); } } else { $this->securityHoleAlert(__FILE__, __LINE__, $this->getClassName()); } }
private static function _renewCache($module, $file, $type) { $filename = fixPath($file); $cacheFile = CACHEPATH . $type . DS . self::$themeName . DS . $module . DS . $filename; $cachePath = dirname($cacheFile); if (!file_exists($cachePath)) { recursive_mkdir($cachePath); } if (file_exists($cacheFile) && time() - filemtime($cacheFile) < rad_config::getParam('cache.power.time')) { return true; } if ($fname = rad_themer::getFilePath(self::$themeName, 'jscss', $module, $filename)) { return self::copyToCache($fname, $cacheFile); } return false; }
<?php require_once '../../global.php'; //png1,png2,png3分别为3个尺寸头像的参数,经过base64解密后保存即可 $folder = 'uploads/member/' . session('member_id') . '/avatar/'; recursive_mkdir($folder); $filename120 = $folder . '120.jpg'; $filename48 = $folder . '48.jpg'; $filename24 = $folder . '24.jpg'; $somecontent1 = base64_decode($_POST['png1']); $somecontent2 = base64_decode($_POST['png2']); $somecontent3 = base64_decode($_POST['png3']); if ($handle = fopen($filename120, 'w+')) { if (!fwrite($handle, $somecontent1) == false) { fclose($handle); } } if ($handle = fopen($filename48, 'w+')) { if (!fwrite($handle, $somecontent2) == false) { fclose($handle); } } if ($handle = fopen($filename24, 'w+')) { if (!fwrite($handle, $somecontent3) == false) { fclose($handle); } } //更新cookie头像 if (cookie('userlist') != NULL) { $userlist = json_decode(stripslashes(cookie('userlist')), true); foreach ($userlist as &$v) {
/** * Processes the upload * */ function upload_process() { $this->_clean_paths(); //------------------------------------------------- // Check for getimagesize //------------------------------------------------- if (!function_exists('getimagesize')) { $this->image_check = 0; } //------------------------------------------------- // Set up some variables to stop carpals developing //------------------------------------------------- $FILE_NAME = isset($_FILES[$this->upload_form_field]['name']) ? $_FILES[$this->upload_form_field]['name'] : ''; $FILE_SIZE = isset($_FILES[$this->upload_form_field]['size']) ? $_FILES[$this->upload_form_field]['size'] : ''; $FILE_TYPE = isset($_FILES[$this->upload_form_field]['type']) ? $_FILES[$this->upload_form_field]['type'] : ''; //------------------------------------------------- // Naughty Opera adds the filename on the end of the // mime type - we don't want this. //------------------------------------------------- $FILE_TYPE = preg_replace("/^(.+?);.*\$/", "\\1", $FILE_TYPE); //------------------------------------------------- // Naughty Mozilla likes to use "none" to indicate an empty upload field. // I love universal languages that aren't universal. //------------------------------------------------- if (!isset($_FILES[$this->upload_form_field]['name']) or $_FILES[$this->upload_form_field]['name'] == "" or !$_FILES[$this->upload_form_field]['name'] or !$_FILES[$this->upload_form_field]['size'] or $_FILES[$this->upload_form_field]['name'] == "none") { $this->error_no = 1; return; } if (!is_uploaded_file($_FILES[$this->upload_form_field]['tmp_name'])) { $this->error_no = 1; return; } //------------------------------------------------- // De we have allowed file_extensions? //------------------------------------------------- if (!is_array($this->allowed_file_ext) or !count($this->allowed_file_ext)) { $this->error_no = 2; return; } //------------------------------------------------- // Get file extension //------------------------------------------------- $this->file_extension = $this->_get_file_extension($FILE_NAME); if (!$this->file_extension) { $this->error_no = 2; return; } $this->real_file_extension = $this->file_extension; //------------------------------------------------- // Valid extension? //------------------------------------------------- if (!in_array($this->file_extension, $this->allowed_file_ext)) { $this->error_no = 2; return; } //------------------------------------------------- // Check the file size //------------------------------------------------- if ($this->max_file_size and $FILE_SIZE > $this->max_file_size) { $this->error_no = 3; return; } //------------------------------------------------- // Make the uploaded file safe //------------------------------------------------- $FILE_NAME = preg_replace("/[^\\w\\.]/", "_", $FILE_NAME); $this->original_file_name = $FILE_NAME; //------------------------------------------------- // Convert file name? // In any case, file name is WITHOUT extension //------------------------------------------------- if ($this->out_file_name) { $this->parsed_file_name = $this->out_file_name; } else { $this->parsed_file_name = str_replace('.' . $this->file_extension, "", $FILE_NAME); } //------------------------------------------------- // Make safe? //------------------------------------------------- $renamed = 0; if ($this->make_script_safe) { if (preg_match("/\\.(cgi|pl|js|asp|php|html|htm|jsp|jar)(\\.|\$)/i", $FILE_NAME)) { $FILE_TYPE = 'text/plain'; $this->file_extension = 'txt'; $this->parsed_file_name = preg_replace("/\\.(cgi|pl|js|asp|php|html|htm|jsp|jar)(\\.|\$)/i", "\$2", $this->parsed_file_name); $renamed = 1; } } //------------------------------------------------- // Is it an image? //------------------------------------------------- if (is_array($this->image_ext) and count($this->image_ext)) { if (in_array($this->real_file_extension, $this->image_ext)) { $this->is_image = 1; } } //------------------------------------------------- // Add on the extension... //------------------------------------------------- if ($this->force_data_ext and !$this->is_image) { $this->file_extension = str_replace(".", "", $this->force_data_ext); } $this->parsed_file_name .= '.' . $this->file_extension; //------------------------------------------------- // Copy the upload to the uploads directory // ^^ We need to do this before checking the img // size for the openbasedir restriction peeps // We'll just unlink if it doesn't checkout //------------------------------------------------- /* * added by Venko007 */ recursive_mkdir($this->out_file_dir); $this->saved_upload_name = $this->out_file_dir . '/' . md5(time() . rand(100, 1000)) . "." . $this->file_extension; // . '_' .$this->parsed_file_name; ####################################################### //$this->saved_upload_name = $this->out_file_dir . '/' . $this->parsed_file_name; if (!@move_uploaded_file($_FILES[$this->upload_form_field]['tmp_name'], $this->saved_upload_name)) { $this->error_no = 4; return; } else { @chmod($this->saved_upload_name, 0774); } /* * scan for viruses... */ //scanFileClamAV ( $this->saved_upload_name ); ################################################ if (!$renamed) { $this->check_xss_infile(); if ($this->error_no) { return; } } //------------------------------------------------- // Is it an image? //------------------------------------------------- if ($this->is_image) { //------------------------------------------------- // Are we making sure its an image? //------------------------------------------------- if ($this->image_check) { $img_attributes = @getimagesize($this->saved_upload_name); if (!is_array($img_attributes) or !count($img_attributes)) { // Unlink the file first @unlink($this->saved_upload_name); $this->error_no = 5; return; } else { if (!$img_attributes[2]) { // Unlink the file first @unlink($this->saved_upload_name); $this->error_no = 5; return; } else { if ($img_attributes[2] == 1 and ($this->file_extension == 'jpg' or $this->file_extension == 'jpeg')) { // Potential XSS attack with a fake GIF header in a JPEG @unlink($this->saved_upload_name); $this->error_no = 5; return; } } } } } //------------------------------------------------- // If filesize and $_FILES['size'] don't match then // either file is corrupt, or there was funny // business between when it hit tmp and was moved //------------------------------------------------- if (filesize($this->saved_upload_name) != $_FILES[$this->upload_form_field]['size']) { @unlink($this->saved_upload_name); $this->error_no = 1; return; } }
function recursive_copy($src, $dest) { // Base case, is file so just copy if (is_file($src)) { $c = copy($src, $dest); return $c; } if (!is_dir($dest)) { recursive_mkdir($dest); } $dir = dir($src); while (false !== ($entry = $dir->read())) { if ($entry == '.' || $entry == '..' || preg_match('/^\\./', $entry)) { // Skips the index '.' and '..' along with hidden files continue; } if ($dest !== "{$src}/{$entry}") { recursive_copy("{$src}/{$entry}", "{$dest}/{$entry}"); } } }
/** * do daily backup * * @param null * @return null */ function backup_handle_on_daily() { set_time_limit(0); $start_time = time(); if (!ConfigOptions::getValue('backup_enabled')) { return true; } // if // check if backup path exists and if it's writable recursive_mkdir(BACKUP_PATH, 0777, WORK_PATH); if (!is_dir(BACKUP_PATH) || !folder_is_writable(BACKUP_PATH)) { backup_module_log_error('Backup path (' . BACKUP_PATH . ') does not exists or it is not writable', BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if $htaccess = BACKUP_PATH . '/.htaccess'; if (!is_file($htaccess)) { file_put_contents($htaccess, 'Deny from all'); } $folder_name = "backup " . date('Y-m-d H-i') . " GMT"; $backup_dir = BACKUP_PATH . '/' . $folder_name; // check if backup already exists if (is_dir($backup_dir)) { backup_module_log_error("Backup already exists ({$folder_name})", BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if // try to create backup directory if (!recursive_mkdir($backup_dir, 0777, WORK_PATH)) { backup_module_log_error("Could not create backup folder ({$backup_dir})", BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if chmod($backup_dir, 0777); // backup database (all tables that starts with TABLE_PREFIX) $tables = db_list_tables(TABLE_PREFIX); if (is_foreachable($tables)) { $result = db_dump_tables($tables, $backup_dir . '/database.sql'); if (is_error($result)) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error($result->getMessage(), BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if } else { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error("Database specified in config.php file does not have exportable tables. Check your config settings", BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // backup uploads $errors = array(); $result = backup_module_copy_dir(UPLOAD_PATH, $backup_dir . '/upload', true, $errors); if (!$result) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error($errors, BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if // backup project icons $errors = array(); $result = backup_module_copy_dir(PUBLIC_PATH . '/projects_icons', $backup_dir . '/projects_icons', true, $errors); if (!$result) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error($errors, BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if // backup avatars $errors = array(); $result = backup_module_copy_dir(PUBLIC_PATH . '/avatars', $backup_dir . '/avatars', true, $errors); if (!$result) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error($errors, BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if // backup logos $errors = array(); $result = backup_module_copy_dir(PUBLIC_PATH . '/logos', $backup_dir . '/logos', true, $errors); if (!$result) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error($errors, BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if $app =& application(); $checksum = backup_module_calculate_checksum($folder_name); $backup_note = "<?php \n/* \n"; $backup_note .= 'Backup is created with activeCollab v' . $app->version . ' on ' . date(DATETIME_MYSQL, $start_time) . "\n\n"; $backup_note .= "To restore system using this backup, visit this page: \n" . ROOT_URL . '/restore.php?backup=' . urlencode($folder_name) . '&checksum=' . $checksum; $backup_note .= "\n*/\n?>"; if (!file_put_contents($backup_dir . '/restore_instructions.php', $backup_note)) { safe_delete_dir($backup_dir, BACKUP_PATH); backup_module_log_error("Could not create restore instructions for backup.", BACKUP_MODULE_SEND_ERROR_EMAIL); return false; } // if // remove old backups $how_many_backups = ConfigOptions::getValue('backup_how_many_backups'); $how_many_backups = (int) $how_many_backups <= 0 ? 5 : $how_many_backups; $folders_in_backup_directory = backup_module_get_backups(BACKUP_PATH); if (count($folders_in_backup_directory) > $how_many_backups) { $old_backups = array_splice($folders_in_backup_directory, -(count($folders_in_backup_directory) - $how_many_backups)); foreach ($old_backups as $old_backup) { safe_delete_dir($old_backup['path'], BACKUP_PATH); } // foreach } // if log_message('Daily backup created', LOG_LEVEL_INFO, 'backup'); }
function writeElFiles($task, $elementsPath, $elementsPackage, $settings, $category_id = 0, $category_name = '') { global $modx; $dir = ''; if (!empty($elementsPath)) { $dir = $elementsPath; } else { if (!empty($elementsPackage)) { $dir = $modx->getOption('core_path') . 'components/' . $elementsPackage . '/elements/' . $task; } } if (!empty($dir)) { if (!recursive_mkdir($dir, 0755)) { return 'failure'; } $nameField = $modx->getOption('nameField', $settings, 'name'); $elementsSuffix = $modx->getOption('elementsSuffix', $settings, '.php'); $elementsClass = $modx->getOption('elementsClass', $settings, false); $contentField = $modx->getOption('contentField', $settings, ''); $memClass = str_replace('mod', 'mem', $elementClass); if ($elementsClass && ($collection = $modx->getIterator($elementsClass, array('category' => $category_id)))) { $elements = array(); foreach ($collection as $object) { $id = $object->get('id'); $exclude = false; if ($memObject = $modx->getObject($memClass, array('element_id' => $id))) { $exclude = $memObject->get('exclude'); } if ($exclude) { continue; } $element = $object->toArray(); if ($object instanceof modPlugin) { $plugin_events = array(); if ($events = $object->getMany('PluginEvents')) { foreach ($events as $event_o) { $event = $event_o->toArray(); if ($event_e = $event_o->getOne('Event')) { $systemevent = $event_e->toArray(); $event = array_merge($event, $systemevent); } $event['pluginid'] = $object->get('name'); $plugin_events[] = $event; } } $element['plugin_events'] = $plugin_events; } unset($element[$contentField]); unset($element['content']); $filename = strtolower($object->get($nameField)) . $elementsSuffix; $element['filename'] = $filename; $filename = $dir . '/' . $filename; $content = $object->getContent(); if (strstr($elementsSuffix, '.php')) { $content = '<?php' . "\n" . $content; } writeElFile($filename, $content); $element['category'] = 0; $element['category_name'] = $category_name; $elements[] = $element; } $content = $modx->toJson($elements); $content = $modx->migx->indent($content); $filename = $dir . '/' . $task . '.' . $category_id . '.json'; writeElFile($filename, $content); } } }
function resizeImages($file, $directoryExtend, $watermark = '', $watermarkOver = 0, $watermarkPosition = '') { if (trim($file) == '') { return false; } if (is_array($this->photoSizes)) { require_once ENGINE_PATH . 'classes/image.class.php'; $image = new Image(); if ($watermark != '') { require_once ENGINE_PATH . 'classes/watermark.class.php'; $wm = new watermark(DATA_SERVER_PATH . 'images/' . $watermark, $watermarkPosition); } recursive_mkdir(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend); foreach ($this->photoSizes as $key => $size) { $image->enlarge = true; $resize = false; if (substr($size, 0, 1) == '_') { $resize = true; $size = substr($size, 1); } $sizes = explode('x', $size); if ($sizes[0] > 0) { if ($sizes[1] == 0) { $image->resize(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], 1000, DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } else { if ($resize) { $image->enlarge = false; $image->resize(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], $sizes[1], DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } else { $image->crop(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $file, $sizes[0], $sizes[1], DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } } if ($watermark != '' && $watermarkOver <= $sizes[1]) { $wm->addWatermark(DATA_SERVER_PATH . "/uploads/" . $this->uploadFileDirectory . $directoryExtend . $key . '_' . $file); } } } } return true; }
function HandleM2MSaveOptions ($pagename, $auth='read') { global $M2MDir, $M2MDataDir; session_start(); $targetformat = $_SESSION['targetformat']; $options = new StylesheetOptions(); $options->readXML("$M2MDir/options/$targetformat.xml"); $options->setRequestValues($_REQUEST); $outdir = "$M2MDataDir/$pagename"; recursive_mkdir($outdir); $options->writeShortXML("$outdir/{$targetformat}opt.xml"); $options->writeStylesheet("$outdir/$targetformat.xsl", "$M2MDir/xsl/{$targetformat}.xsl"); HandleBrowse($pagename, $auth); }
/** * Copy folder tree and returns a true if all tree is copied and false if there was errors * * @param string $source_dir Source Directory * @param string $destination_dir Destination Directory * @return boolean */ function copy_dir($source_dir, $destination_dir) { if (!is_dir($source_dir) || !is_dir($destination_dir)) { return false; } // if $result = true; $dh = opendir($source_dir); while ($file = readdir($dh)) { if ($file != "." && $file != ".." && $file != '.svn') { $full_src_path = $source_dir . "/" . $file; $dest_src_path = $destination_dir . "/" . $file; if (!is_dir($full_src_path)) { $result = $result && copy($full_src_path, $dest_src_path); } else { recursive_mkdir($dest_src_path, 0777, WORK_PATH); $result = $result && copy_dir($full_src_path, $dest_src_path); } // if } // if } // while closedir($dh); return $result; }
public static function prepareImages(array $files) { $theme = rad_themer::getCurrentTheme(); foreach ($files as $file) { $fileOriginal = rad_themer::getFilePath($theme, 'img', $file['module'], $file['file']); $fileCached = CACHEPATH . 'img' . DS . $theme . DS . $file['module'] . DS . 'original' . DS . fixPath($file['file']); if (file_exists($fileCached)) { if (time() - filemtime($fileCached) < rad_config::getParam('cache.power.time')) { continue; //File is already cached } } else { $cachePath = dirname($fileCached); if (!is_dir($cachePath) && !recursive_mkdir($cachePath)) { throw new RuntimeException('Could not create cache folder for image'); } } copy($fileOriginal, $fileCached); } }
function WikiConverter ($pagename) { $this->pagename = $pagename; if (!recursive_mkdir($this->outputDir())) error_message("unable to create output directory ".$dir, true); }
/** * Create the xml file from array * Сдесь xml файл генерируется без помощи библиотек для лучшей совместимости. * * @param array $params - array of fieldnames and fieldvalues * @param string $module - module name * @return boolean */ function createParamsForTemplate($params, $module, $fn) { $file = $this->_getFN($module, $fn, false, false); if (!is_dir(dirname($file))) { if (!recursive_mkdir(dirname($file))) { return false; } } if (!is_writable(dirname($file))) { return false; } if (file_exists($file) and !is_writable($file)) { return false; } //CREATE THE DEFAULT STRUCTURE $s = '<?xml version="1.0" encoding="UTF-8"?>' . '<metadata>' . '<names>' . '<title>' . $this->_getLangValue($params['names.title']) . '</title>' . '<description>' . $this->_getLangValue($params['names.description']) . '</description>' . '<author>' . $this->_getLangValue($params['names.author']) . '</author>' . '<date>' . time() . '</date>' . '<url>' . $this->_getLangValue($params['names.url']) . '</url>' . '</names>' . '<system>' . '<ver>' . stripslashes($params['system.ver']) . '</ver>' . '<prelogic>' . $this->_getItems($params['system.prelogic']) . '</prelogic>' . '<themes>' . $this->_getItems($params['system.themes']) . '</themes>' . '<module>' . '<name>' . $this->_getLangValue($params['system.module.name']) . '</name>' . '<folder>' . stripslashes($params['system.module.folder']) . '</folder>' . '<ver>' . stripslashes($params['system.module.ver']) . '</ver>' . '<ident>' . $this->genereModuleIdent() . '</ident>' . '</module>' . '<name>' . stripslashes($params['system.name']) . '</name>' . '<ident>' . $this->genereTmplIdent($params['system.name'], $params['system.module.folder'], rad_config::getParam('loader_class')) . '</ident>' . '<template>' . '<lower>' . (!empty($params['system.ver']) ? $params['system.ver'] : '0.1') . '</lower>' . '<name>' . rad_config::getParam('loader_class') . '</name>' . '</template>' . '<access>' . stripslashes($params['system.access']) . '</access>' . '</system>' . '<params>' . $this->_getLangValue($params['params']) . '</params>' . '</metadata>'; return safe_put_contents($file, $s); }