function createFolder($path) { if (!file_exists($path)) { createFolder(dirname($path)); mkdir($path, 0777); } }
function createFolder($path) { if (!is_dir($path)) { createFolder(dirname($path)); @mkdir($path); @chmod($path, 0777); } }
function createFolder($path) { if (!file_exists($path)) { createFolder(dirname($path)); //递归创建 //取得最后一个文件夹的全路径返回开始的地方 mkdir($path, 0777); //创建并写文件 } }
function writetocache($script, $file, $dir, $folder, $prefix = 'cache_') { global $authkey; if (!is_dir(ROOT_PATH . $folder . "/" . $dir)) { createFolder(ROOT_PATH . $folder . "/" . $dir, 0777); } if ($fp = @fopen(ROOT_PATH . $folder . "/" . $dir . "/{$prefix}{$file}.php", 'wb')) { fwrite($fp, "<?php\n//cache file, DO NOT modify me!" . "\n//Created: " . date("M j, Y, G:i") . "\n//Identify: " . md5($prefix . $file . '.php' . $authkey) . "\n\n{$script}?>"); fclose($fp); } else { exit("Can not write to cache files, please check directory ./data/{$dir}."); } }
function createLink($target, $link) { if (!file_exists($target)) { throw new Exception("{$target} does not exists"); } $link = rtrim($link, '/'); if (file_exists($link)) { throw new Exception("{$link} exists but is not link"); } $target = rtrim($target, '/'); $folder = dirname($link); createFolder($folder); symlink($target, $link); }
/** * @Title: pJAccesslist * @Description: todo(任务节点权限生成) * @param $id int 任务节点id(以前用于生成数组key值,后改用控制器名称) * @param $actionname string 控制器名称 * @author 谢友志 * @date 2015-4-7 上午9:59:20 * @throws */ public function pJAccesslist2($actionname, $id = '') { //查找任务节点对应模板名称 $Action = $actionname; //查找该模板名称对应记录 $nodedetails = M("node")->where("name='" . $Action . "'")->find(); if (!$nodedetails) { logs($Action . "---------没有对应模板------------", "taskNodeAccess"); } //$nodeid = getFieldBy($action,"name","id","node"); //查找该模板的操作节点 $nodemodel = M("node"); $list = $nodemodel->where("pid=" . $nodedetails['id'])->select(); /** 索引文件以“paaccess_”+任务节点id为key值 已对应模板名称为value值组成数组 */ if ($list) { //组合一个索引文件的元素 这里直接做成一个数组,后面与索引文件取得的数组进行合并 $name = "pjaccess_" . $Action; //对操作节点数据进行重组$detailes $temp = array('GROUPID' => $nodedetails['group_id']); foreach ($list as $k => $v) { $optionname = strtoupper($v['name']); // if($optionname=="INDEX"){ $temp1 = array($optionname => $v['id'] . "-1"); // }else{ // $temp1 = array($optionname=>$v['id']."-4"); // } $temp = array_merge($temp, $temp1); } $detailes = array($Action => $temp); //套表 组合表情况下 添加权限详情元素 $isbinddetailes = $this->pjAccessisbind($Action); $detailes = array_merge($detailes, $isbinddetailes); //暂时生成文件 其操作节点权限全部为1 //任务节点权限文件夹 $pathconf = DConfig_PATH . '/PJAccessList'; if (!file_exists($pathconf)) { createFolder($pathconf); } //调用lookupobj模型的写入文件方法 $lookupmodel = D("LookupObj"); // 每个任务节点生成单独的文件 $detailesfile = $pathconf . '/' . $name . '.php'; $detailesnum = $lookupmodel->SetSongleRule($detailesfile, $detailes); } else { logs($Action . "=======没有对应下级操作========", "taskNodeAccess"); } }
function createFolders(&$drive_service, &$client, &$configObj, &$UsersAFSObj) { // Recreate the user's AFS directory structure inside Box $afsFilesFolder = createFolder($drive_service, "AFS Migration Files", "Home for migrated files", "root", $configObj); $UsersAFSObj->folderList[$UsersAFSObj->afsPath] = $afsFilesFolder->getID(); ++$UsersAFSObj->numFoldersUploaded; $logline = date('Y-m-d H:i:s') . " User's AFS Path: " . $UsersAFSObj->afsPath . "\n"; $logline = date('Y-m-d H:i:s') . " Our root folder ID: " . $UsersAFSObj->folderList[$UsersAFSObj->afsPath] . "\n"; fwrite($configObj->logFile, $logline); foreach ($UsersAFSObj->folderList as $key => $value) { // Avoid creating a folder for the root directory if (strcmp($key, $UsersAFSObj->afsPath) == 0) { continue; } // Make sure the folder still exists in AFS if (!file_exists($key)) { continue; } $parentFolderID = $UsersAFSObj->folderList[getParentFolder($key)]; $logline = date('Y-m-d H:i:s') . " Parent folder name: " . getParentFolder($key) . "\n"; $logline = $logline . date('Y-m-d H:i:s') . " Parent folder ID: " . $parentFolderID . "\n"; fwrite($configObj->logFile, $logline); // See if the access token is about to expire if ($client->isAccessTokenExpired()) { //Trade access token for refresh token if ($client->refreshToken($configObj->refreshToken) == null) { $logline = date('Y-m-d H:i:s') . ": Using refresh token, access token granted. \n"; fwrite($configObj->logFile, $logline); } else { $logline = date('Y-m-d H:i:s') . ": Unable to obtain access token. \n"; fwrite($configObj->logFile, $logline); } } //Create folder $logline = date('Y-m-d H:i:s') . " The folder name: " . getFileName($key) . "\n"; $folder = createFolder($drive_service, getFileName($key), "", $parentFolderID, $configObj); if ($folder) { //If creation worked, store folder ID for the file uploads ++$UsersAFSObj->numFoldersUploaded; $UsersAFSObj->folderList[$key] = $folder->getID(); $logline = $logline . date('Y-m-d H:i:s') . " Success! The ID of this new folder is: " . $folder->getID() . "\n"; fwrite($configObj->logFile, $logline); } else { $logline = $logline . date('Y-m-d H:i:s') . " The following folder could not be created: " . $folder->getID() . "\n"; fwrite($configObj->logFile, $logline); } } }
function createFolder($dir, $recursive = true) { global $REX; if (is_dir($dir)) { return true; } $parent = dirname($dir); if (!is_dir($parent) && (!$recursive || !createFolder($parent))) { return false; } if (mkdir($dir, $REX['DIRPERM'])) { @chmod($dir, $REX['DIRPERM']); return true; } return false; }
function copysubdir($srcdir, $destdir) { $dir = opendir($srcdir); while ($file = readdir($dir)) { if (!($file != ".") && !($file != "..")) { $dircontent = $srcdir . "/" . $file; if (is_dir($dircontent)) { if (!file_exists($destdir . "/" . $file)) { createFolder($destdir . "/" . $file); } copyfiles($dircontent, $destdir . "/" . $file); } } } closedir($_dirrun); }
static function saveBrowseList($authId = null) { if (null === $authId) { $authId = $_SESSION[C('USER_AUTH_KEY')]; } // 如果使用普通权限模式,保存当前用户的访问权限列表 // 管理员不生成浏览权限 if (C('USER_AUTH_TYPE') != 2 && !$_SESSION[C('ADMIN_AUTH_KEY')]) { // 把权限写入文件通过文件判断 //$file = DConfig_PATH . "/BrowsecList/borwse_" . $_SESSION [C ( 'USER_AUTH_KEY' )] . ".php"; ---xyz $file = DConfig_PATH . "/BrowsecList/borwse_" . $authId . ".php"; //---xyz if (!file_exists($file)) { $browselist = Browse::getBrowseList($authId); if (!file_exists(DConfig_PATH . "/BrowsecList")) { createFolder(dirname(DConfig_PATH . "/BrowsecList")); mkdir(DConfig_PATH . "/BrowsecList", 0777); } Browse::writeover($file, "return " . Browse::pw_var_export($browselist) . ";\n", true); } } return; }
/** * This function will get the the corresponding matrix id for a folder * If the matrix is equal to zero it will make sure create the folder * it will also make sure that all the parent folders are created in matrix * * @param string $folder_path folder's path * @param array &$matrix_ids array containing all the matrix ids * * @return int * @access private */ function getMatrixFolderId($folder_path, &$matrix_ids) { if (empty($matrix_ids[$folder_path])) { $folder_to_create = array(); array_push($folder_to_create, $folder_path); while (!empty($folder_to_create)) { // take current folder and get its parent // if the parent folder has a matrix id then create the folder // if the parent folder doesnt add the parent folder to the $folder_to_create list $current_folder = array_pop($folder_to_create); // if the current folder is empty means that we went too far if (empty($current_folder)) { trigger_error("We could not found the asset id for the folder {$folder_path}", E_USER_ERROR); } $parent_folder = dirname($current_folder); if (!empty($matrix_ids[$parent_folder])) { $matrix_ids[$current_folder] = createFolder($matrix_ids[$parent_folder], basename($current_folder)); } else { array_push($folder_to_create, $parent_folder); } } } return $matrix_ids[$folder_path]; }
public function insert() { global $CONFIG; $post = $_POST; $message = ''; $tbl_locn = 'locn'; $tbl_indiv = 'indiv'; $tbl_obs = 'obs'; $tbl_img = 'img'; $data[$tbl_locn] = array('locality' => $post['locality']); $data[$tbl_indiv] = array('personID' => $post['personID']); $data[$tbl_obs] = array('personID' => $post['personID'], 'localname' => $post['localname']); $data[$tbl_img] = array(); $insertLocn = $this->mspecimen->insertTransaction($tbl_locn, $data[$tbl_locn]); $locn_id = $insertLocn['lastid']; $data[$tbl_indiv]['locnID'] = $locn_id; $insertIndiv = $this->mspecimen->insertTransaction('indiv', $data[$tbl_indiv]); $indiv_id = $insertIndiv['lastid']; $data[$tbl_obs]['indivID'] = $indiv_id; $data[$tbl_img]['indivID'] = $indiv_id; $data[$tbl_img]['personID'] = $post['personID']; $insertObs = $this->mspecimen->insertTransaction('obs', $data[$tbl_obs]); $name = 'image'; $path = ''; $uploaded_file = uploadFile($name, $path, 'image'); //if uploaded if ($uploaded_file['status'] != '0') { logFile('Upload Success'); if (extension_loaded('gd') && function_exists('gd_info')) { logFile('GD2 is installed. Checking image data.'); $tmp_name = $uploaded_file['full_name']; $entry = str_replace(array('\'', '"'), '', $uploaded_file['real_name']); $image_name_encrypt = md5(str_shuffle($CONFIG['default']['salt'] . $entry)); //check filename //$dataExist = $this->mspecimen->imageExist($personID, $entry); $path_entry = $CONFIG['default']['upload_path']; $src_tmp = $path_entry . "/" . $tmp_name; logFile('Prepare to cropping image'); $path_data = 'public_assets/'; //$path_user = $path_data.$username; $path_img = $path_data . '/img'; $path_img_1000px = $path_img . '/1000px'; $path_img_500px = $path_img . '/500px'; $path_img_100px = $path_img . '/100px'; $fileinfo = getimagesize($path_entry . '/' . $tmp_name); $toCreate = array($path_img, $path_img_1000px, $path_img_500px, $path_img_100px); createFolder($toCreate, 0755); copy($path_entry . "/" . $tmp_name, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'); if (!@copy($path_entry . "/" . $tmp_name, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg')) { logFile('Copy file failed'); $status = "error"; $msg = error_get_last(); } else { logFile('Copy file success'); $dest_1000px = $CONFIG['default']['root_path'] . '/' . $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'; $dest_500px = $CONFIG['default']['root_path'] . '/' . $path_img_500px . '/' . $image_name_encrypt . '.500px.jpg'; $dest_100px = $CONFIG['default']['root_path'] . '/' . $path_img_100px . '/' . $image_name_encrypt . '.100px.jpg'; if ($fileinfo[0] >= 1000 || $fileinfo[1] >= 1000) { if ($fileinfo[0] > $fileinfo[1]) { $percentage = 1000 / $fileinfo[0]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } else { $percentage = 1000 / $fileinfo[1]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } $this->resize_pic($src_tmp, $dest_1000px, $config); unset($config); } logFile('Cropping to 1000px image'); //Set cropping for y or x axis, depending on image orientation if ($fileinfo[0] > $fileinfo[1]) { $config['width'] = $fileinfo[1]; $config['height'] = $fileinfo[1]; $config['x_axis'] = $fileinfo[0] / 2 - $config['width'] / 2; $config['y_axis'] = 0; } else { $config['width'] = $fileinfo[0]; $config['height'] = $fileinfo[0]; $config['x_axis'] = 0; $config['y_axis'] = $fileinfo[1] / 2 - $config['height'] / 2; } $this->cropToSquare($src_tmp, $dest_500px, $config); unset($config); logFile('Cropping to square image'); //set new config $config['width'] = 500; $config['height'] = 500; $this->resize_pic($dest_500px, $dest_500px, $config); unset($config); logFile('Cropping to 500px image'); $config['width'] = 100; $config['height'] = 100; $this->resize_pic($dest_500px, $dest_100px, $config); unset($config); logFile('Cropping to 100px image'); //add file information to array /*$fileToInsert = array('filename' => $entry,'md5sum' => $image_name_encrypt, 'directory' => '', 'mimetype' => $fileinfo['mime']); $insertImage = $this->imagezip->updateImage($personID, $fileToInsert);*/ $data[$tbl_img]['filename'] = $entry; $data[$tbl_img]['md5sum'] = $image_name_encrypt; $data[$tbl_img]['mimetype'] = $fileinfo['mime']; $insertImg = $this->mspecimen->insertTransaction('img', $data[$tbl_img]); if ($insertImg) { logFile('Insert Image Success'); } else { logFile('Insert Image Failed'); } $return['status'] = TRUE; $return['message'] = 'Data berhasil disimpan'; } // end if copy unlink($src_tmp); } else { logFile('GD2 is not installed'); $return['message'] = 'Error: Sistem Error. Harap menghubungi tim developer kami.'; } } else { logFile('Upload Image Failed'); $return['message'] = 'Error: ' . $uploaded_file['message']; } echo json_encode($return); exit; }
function makeDatabase() { // Creates a new database and populates it with triggers, constraints and core definitions global $newDBName, $isNewDB, $done, $isCreateNew, $isExtended,$errorCreatingTables; $error = false; $warning=false; if (isset($_POST['dbname'])) { // Check that there is a current administrative user who can be made the owner of the new database if(ADMIN_DBUSERNAME == "") { if(ADMIN_DBUSERPSWD == "") { echo "DB Admin username and password have not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } echo "DB Admin username has not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } if(ADMIN_DBUSERPSWD == "") { echo "DB Admin password has not been set in config.ini. Please do so before trying to create a new database.<br>"; return; } // checking for current administrative user // Create a new blank database $newDBName = trim($_POST['uname']).'_'; if ($newDBName == '_') {$newDBName='';}; // don't double up underscore if no user prefix $newDBName = $newDBName . trim($_POST['dbname']); $newname = HEURIST_DB_PREFIX . $newDBName; // all databases have common prefix then user prefix // Avoid illegal chars in db name $hasInvalid = isInValid($newname); if ($hasInvalid) { echo ("Only letters, numbers and underscores (_) are allowed in the database name"); return false; } // rejecting illegal characters in db name if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -e\"create database `$newname`\""; } else { $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -e'create database `$newname`'"; } $output1 = exec($cmdline . ' 2>&1', $output, $res1); if ($res1 != 0 ) { echo ("<p class='error'>Error code $res1 on MySQL exec: Unable to create database $newname<br> <br>"); echo("\n\n"); if(is_array($output)){ $isExists = (strpos($output[0],"1007")>0); }else{ $sqlErrorCode = split(" ", $output); $isExists = (count($sqlErrorCode) > 1 && $sqlErrorCode[1] == "1007"); } if($isExists){ echo "<strong>A database with that name already exists.</strong>"; } echo "</p>"; $isCreateNew = true; return false; } // At this point a database exists, so need cleanup if anythign goes wrong later // Create the Heurist structure for the newly created database, using the template SQL file // This file sets up teh table definitions and inserts a few critical values // it does not set referential integrity constraints or triggers $cmdline="mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < blankDBStructure.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load blankDBStructure.sql into database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); return false; } // Add referential constraints $cmdline="mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < addReferentialConstraints.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load addReferentialConstraints.sql into database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); return false; } // Add procedures and triggers $cmdline = "mysql -u".ADMIN_DBUSERNAME." -p".ADMIN_DBUSERPSWD." -D$newname < addProceduresTriggers.sql"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<p class='error'>Error $res2 on MySQL exec: Unable to load addProceduresTriggers.sql for database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed<br> <br></p>"); echo($output2); cleanupNewDB($newname); return false; } // Run buildCrosswalks to import minimal definitions from coreDefinitions.txt into the new DB // yes, this is badly structured, but it works - if it ain't broke ... $isNewDB = true; // flag of context for buildCrosswalks, tells it to use coreDefinitions.txt require_once('../structure/buildCrosswalks.php'); // errorCreatingTables is set to true by buildCrosswalks if an error occurred if($errorCreatingTables) { echo ("<p class='error'>Error importing core definitions from ".($isExtended?"coreDefinitionsExtended.txt":"coreDefinitions.txt")." for database $newname<br>"); echo ("Please check whether this file is valid; consult Heurist helpdesk if needed</p>"); cleanupNewDB($newname); return false; } // Get and clean information for the user creating the database if(!is_logged_in()) { $longName = ""; $firstName = $_REQUEST['ugr_FirstName']; $lastName = $_REQUEST['ugr_LastName']; $eMail = $_REQUEST['ugr_eMail']; $name = $_REQUEST['ugr_Name']; $password = $_REQUEST['ugr_Password']; $department = ''; $organisation = ''; $city = ''; $state = ''; $postcode = ''; $interests = ''; $s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./'; $salt = $s[rand(0, strlen($s)-1)] . $s[rand(0, strlen($s)-1)]; $password = crypt($password, $salt); }else{ mysql_connection_insert(DATABASE); $query = mysql_query("SELECT ugr_LongName, ugr_FirstName, ugr_LastName, ugr_eMail, ugr_Name, ugr_Password, ugr_Department, ugr_Organisation, ugr_City, ugr_State, ugr_Postcode, ugr_Interests FROM sysUGrps WHERE ugr_ID=".get_user_id()); $details = mysql_fetch_row($query); $longName = mysql_escape_string($details[0]); $firstName = mysql_escape_string($details[1]); $lastName = mysql_escape_string($details[2]); $eMail = mysql_escape_string($details[3]); $name = mysql_escape_string($details[4]); $password = mysql_escape_string($details[5]); $department = mysql_escape_string($details[6]); $organisation = mysql_escape_string($details[7]); $city = mysql_escape_string($details[8]); $state = mysql_escape_string($details[9]); $postcode = mysql_escape_string($details[10]); $interests = mysql_escape_string($details[11]); } // todo: code location of upload directory into sysIdentification, remove from edit form (should not be changed) // todo: might wish to control ownership rather than leaving it to the O/S, although this works well at present $warnings = 0; // Create a default upload directory for uploaded files eg multimedia, images etc. $uploadPath = HEURIST_UPLOAD_ROOT.$newDBName;//TODO: This locks us into upload path. This is teh place for DB override. $cmdline = "mkdir -p -m a=rwx ".$uploadPath; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { // TODO: need to properly trap the error and distiguish different versions. // Old uplaod directories hanging around could cause problems if upload file IDs are duplicated, // so should probably NOT allow their re-use echo ("<h3>Warning:</h3> Unable to create $uploadPath directory for database $newDBName<br> <br>"); echo ("This may be because the directory already exists or the parent folder is not writable<br>"); echo ("Please check/create directory by hand. Consult Heurist helpdesk if needed<br>"); echo($output2); $warnings = 1; } // copy icon and thumbnail directories from default set in the program code (sync. with H3CoreDefinitions) $cmdline = "cp -R rectype-icons $uploadPath"; // creates directories and copies icons and thumbnails $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy record type icons folder rectype-icons to $uploadPath<br>"); echo ("If upload directory was created OK, this is probably due to incorrect file permissions on new folders<br>"); echo($output2); $warnings = 1; } // copy smarty template directory from default set in the program code $cmdline = "cp -R smarty-templates $uploadPath"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy smarty-templates folder to $uploadPath<br>"); echo($output2); $warnings = 1; } if($isExtended){ // copy xsl template directories from default set in the program code $cmdline = "cp -R xsl-templates $uploadPath"; $output2 = exec($cmdline . ' 2>&1', $output, $res2); if ($res2 != 0 ) { echo ("<h3>Warning:</h3> Unable to create/copy xsl-templates folder to $uploadPath<br>"); echo($output2); $warnings = 1; } } $warnings =+ createFolder("settings","used to store import mappings and the like"); $warnings =+ createFolder("scratch","used to store temporary files"); $warnings =+ createFolder("hml-output","used to write published records as hml files"); $warnings =+ createFolder("html-output","used to write published records as generic html files"); $warnings =+ createFolder("generated-reports","used to write generated reports"); if ($warnings > 0) { echo "<h2>Please take note of warnings above</h2>"; echo "You must create the folders indicated or uploads, icons and templates will not work<br>"; echo "If upload folder is created but icons and template forlders are not, look at file permissions on new folder creation"; } // Prepare to write to the newly created database mysql_connection_insert($newname); // Update file locations $query='update sysIdentification set sys_hmlOutputDirectory = "'.$uploadPath.'/hml-output", sys_htmlOutputDirectory = "'.$uploadPath.'/html-output"'; mysql_query($query); if (mysql_error()) { echo "<h3>Warning: </h3> Unable to update sysIdentification table - please go to DBAdmin > Databases > Properties &". " Advanced Properties, and check the path to the upload, hml and html directories. (".mysql_error().")"; } // Make the current user the owner and admin of the new database mysql_query('UPDATE sysUGrps SET ugr_LongName="'.$longName.'", ugr_FirstName="'.$firstName.'", ugr_LastName="'.$lastName.'", ugr_eMail="'.$eMail.'", ugr_Name="'.$name.'", ugr_Password="******", ugr_Department="'.$department.'", ugr_Organisation="'.$organisation.'", ugr_City="'.$city.'", ugr_State="'.$state.'", ugr_Postcode="'.$postcode.'", ugr_interests="'.$interests.'" WHERE ugr_ID=2'); // TODO: error check, although this is unlikely to fail echo "<h2>New database '$newDBName' created successfully</h2>"; echo "<p><strong>Admin username:</strong> ".$name."<br />"; echo "<strong>Admin password:</strong> <<i>same as account currently logged in to</i>></p>"; echo "<p>You may wish to bookmark the database home page (search page): <a href=\"".HEURIST_BASE_URL."?db=".$newDBName."\" title=\"\" target=\"_new\">".HEURIST_BASE_URL."?db=".$newDBName."</a>.</p>"; echo "<p><a href='".HEURIST_BASE_URL."admin/adminMenu.php?db=".$newDBName."' title='' target=\"_new\" style='font-size:1.2em;font-weight:bold'>Go to Administration page</a>, to configure your new database</p>"; // TODO: automatically redirect to the new database, maybe, in a new window return false; } // isset } //makedatabase
} // 对象转换为JSON字符串 $sFilesInfo = strJSON($filesInfo); $jsonFile = json_decode($sFilesInfo); // 拼装接口消息体 $oMsg = new message(true, "OK", $jsonFile); echo $oMsg; } elseif ('mkdir_dir' === $act) { if ('' === $dir) { $oMsg = new message(false, "file_dir_name操作参数错误。"); echo $oMsg; exit; } $dir = ltrim($dir, HOME_FILE); $dir = HOME_PRO . HOME_FILE . DS . $dir; $msg = createFolder($dir); if ("文件夹创建成功" === $msg) { // 文件夹创建成功 $oMsg = new message(true, $msg); echo $oMsg; } else { // 文件夹创建出现异常 $oMsg = new message(false, $msg); echo $oMsg; } } elseif ('mkdir_file' === $act) { if ('' === $dir) { $oMsg = new message(false, "file_dir_name操作参数错误。"); echo $oMsg; exit; }
\t</form> EOF; echo $str; } elseif ($act == "doRename") { //实现重命名的操做 $newname = $_REQUEST['newname']; $mes = renameFile($filename, $newname); alertMes($mes, $redirect); } elseif ($act == "delFile") { $mes = delFile($filename); alertMes($mes, $redirect); } elseif ($act == "downFile") { //完成下载的操作 $mes = downFile($filename); } elseif ($act == "创建文件夹") { $mes = createFolder($path . "/" . $dirname); alertMes($mes, $redirect); } elseif ($act == "renameFolder") { $str = <<<EOF \t\t\t<form action="index.php?act=doRenameFolder" method="post"> \t请填写新文件夹名称:<input type="text" name="newname" placeholder="重命名"/> \t<input type="hidden" name="path" value="{$path}" /> \t<input type='hidden' name='dirname' value='{$dirname}' /> \t<input type="submit" value="重命名"/> \t</form> EOF; echo $str; } elseif ($act == "doRenameFolder") { $newname = $_REQUEST['newname']; //echo $newname,"-",$dirname,"-",$path; $mes = renameFolder($dirname, $path . "/" . $newname);
/** * @todo fetch folder function basedomain/zip/extract * * @see createFolder Function * @see getContents Function * @see resize & crop Function * @see validateUsername Function * @see imagezip class * * */ function fetch_folder($status = NULL, $msg = NULL, $data = NULL) { global $CONFIG; $name = $_POST['imagezip']; $path = ''; $path_folder = $CONFIG['default']['root_data']; //get data user from session $session = new Session(); $sess_data = $session->get_session(); $username = $sess_data['login']['username']; $personID = $sess_data['login']['id']; $password = $sess_data['login']['password']; if (empty($username) || empty($personID) || empty($password)) { $status = "error"; $msg = "Kesalahan terjadi saat validasi data pengguna, silakan logout kemudian login kembali"; echo json_encode(array('status' => $status, 'message' => $msg)); exit; } if (!empty($name)) { $file = $path_folder . $name; //check file zip exist if (!is_dir($file)) { $status = "error"; $msg = "Sistem tidak dapat menemukan folder yang ditentukan"; echo json_encode(array('status' => $status, 'message' => $msg)); exit; } $path_data = 'public_assets/'; //$path_user = $path_data.$username; $path_img = $path_data . '/img'; $path_img_ori = $path_img . '/ori'; $path_img_1000px = $path_img . '/1000px'; $path_img_500px = $path_img . '/500px'; $path_img_100px = $path_img . '/100px'; $toCreate = array($path_img, $path_img_ori, $path_img_1000px, $path_img_500px, $path_img_100px); $permissions = 0755; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { createFolder($toCreate, $permissions); } else { shell_createFolder($toCreate); } $images = $this->GetContents($file); $list = count($images); $dataNotExist = array(); foreach ($images as $image) { $entry = $image['filename']; $path_entry = $image['path']; $len = strlen($file); $folder = substr($path_entry, $len); if (preg_match('#\\.(jpg|jpeg|JPG|JPEG)$#i', $entry)) { $image_name_encrypt = md5(str_shuffle($CONFIG['default']['salt'] . $entry)); $fileinfo = getimagesize($path_entry . '/' . $entry); if (!$fileinfo) { $status = "error"; $msg = "Tidak ada informasi jenis berkas"; } else { $valid_types = array(IMAGETYPE_JPEG); $valid_mime = array('image/jpeg'); if (in_array($fileinfo[2], $valid_types) || in_array($fileinfo['mime'], $valid_mime)) { $mime = true; } else { $mime = false; } if ($mime) { //check file exist here //$dataExist = $this->imagezip->dataExist($entry); $dataExist = $this->imagezip->imageExist($entry); //add file information to array $fileToInsert = array('filename' => $entry, 'md5sum' => $image_name_encrypt, 'directory' => $folder, 'mimetype' => $fileinfo['mime']); if ($dataExist) { //get detail image $detail_image = $this->imagezip->get_image_by_name($entry); if ($detail_image['md5sum']) { $delete_image = array($path_img_ori . '/' . $detail_image['md5sum'] . '.ori.jpg', $path_img_1000px . '/' . $detail_image['md5sum'] . '.1000px.jpg', $path_img_500px . '/' . $detail_image['md5sum'] . '.500px.jpg', $path_img_100px . '/' . $detail_image['md5sum'] . '.100px.jpg'); //delete old image $this->delete_img($delete_image); } copy($path_entry . "/" . $entry, $path_img_ori . '/' . $image_name_encrypt . '.ori.jpg'); copy($path_entry . "/" . $entry, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'); if (!@copy($path_entry . "/" . $entry, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg')) { $status = "error"; $msg = error_get_last(); } else { $src_tmp = $path_entry . "/" . $entry; $dest_1000px = $CONFIG['default']['root_path'] . '/' . $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'; $dest_500px = $CONFIG['default']['root_path'] . '/' . $path_img_500px . '/' . $image_name_encrypt . '.500px.jpg'; $dest_100px = $CONFIG['default']['root_path'] . '/' . $path_img_100px . '/' . $image_name_encrypt . '.100px.jpg'; if ($fileinfo[0] >= 1000 || $fileinfo[1] >= 1000) { if ($fileinfo[0] > $fileinfo[1]) { $percentage = 1000 / $fileinfo[0]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } else { $percentage = 1000 / $fileinfo[1]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } $this->resize_pic($src_tmp, $dest_1000px, $config); unset($config); } //Set cropping for y or x axis, depending on image orientation if ($fileinfo[0] > $fileinfo[1]) { $config['width'] = $fileinfo[1]; $config['height'] = $fileinfo[1]; $config['x_axis'] = $fileinfo[0] / 2 - $config['width'] / 2; $config['y_axis'] = 0; } else { $config['width'] = $fileinfo[0]; $config['height'] = $fileinfo[0]; $config['x_axis'] = 0; $config['y_axis'] = $fileinfo[1] / 2 - $config['height'] / 2; } $this->cropToSquare($src_tmp, $dest_500px, $config); unset($config); //set new config $config['width'] = 500; $config['height'] = 500; $this->resize_pic($dest_500px, $dest_500px, $config); unset($config); $config['width'] = 100; $config['height'] = 100; $this->resize_pic($dest_500px, $dest_100px, $config); unset($config); //update data $insertImage = $this->imagezip->updateImage($personID, $fileToInsert); } // end if copy } else { //add data information to array array_push($dataNotExist, $fileToInsert); } } } } } $count_dataNotExist = count($dataNotExist); if ($list == $count_dataNotExist) { $status = 'warning'; $msg = 'File berhasil diekstrak. Tidak ada gambar yang sesuai dengan data.'; $data['dataNotExist'] = $dataNotExist; } else { //send dataNotExist information to user $status = 'success'; $msg = 'File berhasil diekstrak'; $data['dataNotExist'] = $dataNotExist; } } else { $status = "error"; $msg = 'Nama file tidak boleh kosong'; } echo json_encode(array('status' => $status, 'message' => $msg, 'data' => $data)); exit; }
} $LoopContent = $TempStr; break; /**/ } // echo "替换:i" . $i . '<br>'; $contents = str_replace($str_loop_begin . $LoopString . $str_loop_end, $LoopContent, $contents); //替换图片 $contents = str_replace($str_module_pic, $pic, $contents); //替换标题 $contents = str_replace($str_module_title, $title, $contents); //替换url $contents = str_replace($str_module_url, $url, $contents); $i++; } } // $contents=str_replace("{title}", $title, $contents); //生成文件夹 createFolder(SPECIALPATH, $html); $handle = fopen(SPECIALPATH . $html, "w"); fwrite($handle, $contents); fclose($handle); echo '[' . $special_title . '],生成成功:地址为:<a target="_blank" href="' . SPECIALURL . $html . '">' . SPECIALURL . $html . '</a><br />'; $refresh_msg = '专题[<font color=red>' . $special_title . '</font>]生成[<font color=red>成功</font>],返回专题列表显示页面。'; //管理员日志 $log_content = '专题[<font color=red>' . $special_title . '</font>] >> 生成 >> 成功'; } require $page_name . '.php'; //管理员日志 require '../../include/log.php'; require '../../include/debug.php';
log_message("Current Working directory {$current_working_directory}\n"); if (ALLOW_OVERWRITE === FALSE && file_exists($current_working_directory . "/" . $path_info['basename'])) { log_message("File exists. Skipping {$current_working_directory}/{$path_info['basename']}\n"); copy("{$each_file}", "{$current_working_directory}/{$path_info['basename']}"); } elseif (ALLOW_OVERWRITE === TRUE && file_exists($current_working_directory . "/" . $path_info['basename'])) { log_message("File Exists Overwriting. {$current_working_directory}/{$path_info['basename']}\n"); log_message("Command used 'copy(\"{$each_file}\", \"{$current_working_directory}/{$path_info['basename']}\");'\n"); copy("{$each_file}", "{$current_working_directory}/{$path_info['basename']}"); } else { log_message("Copying New file. {$current_working_directory}/{$path_info['basename']}\n"); log_message("Command used 'copy(\"{$each_file}\", \"{$current_working_directory}/{$path_info['basename']}\");'\n"); copy("{$each_file}", "{$current_working_directory}/{$path_info['basename']}"); } } else { log_message("{$path_info['extension']} for {$each_file} is not in the valid extensions list\n"); $date = date("Y:m:d 00:0000", filectime($each_file)); $current_working_directory = createFolder($date); copy("{$each_file}", "{$current_working_directory}/{$path_info['basename']}"); } if (ALLOW_DELETE === TRUE) { log_message("Deleting orginal file - {$each_file}"); unlink("{$each_file}"); } } else { echo "Failed: File does not exist\n"; } } } else { log_message("No files found in " . IMPORT_FOLDER . " or folder is missing"); } log_message("Finished");
/** * 远程抓取图片,保存到本地服务器 * @param $content 需要转换的内容 * @return 返回图片替换后的数据 */ function getContent($Content) { $Content = stripslashes($Content); // echo $Content; //获取图片路径 // preg_match_all( " <img[^>]*src=[\"|']?(^>+)[\"|']?[^>]*>", $Content, $temp ); // preg_match_all( "/src=(\"|')(.*?)(\"|')/i", DeCodeStr($Content), $temp ); preg_match_all("/src=(\"|')(.*?)(\"|')/i", $Content, $temp); $imageList = $temp[2]; // echo '<hr>'. print_r($imageList) . '<hr>'; //*/ $ImagePath = date("ym", time()) . '/' . date("d", time()); createFolder(IMAGEPATH, $ImagePath); //网页上面的路径 $ImageUrl = IMAGEURL . $ImagePath; for ($i = 0; $i < count($imageList); $i++) { $fName = saveFile($imageList[$i], $ImagePath, $ImageUrl); if (!empty($fName)) { $filename[$i] = $fName; } } for ($i = 0; $i < count($imageList); $i++) { $Content = str_replace($imageList[$i], $ImageUrl . $filename[$i], $Content); } /* echo '<hr>'; echo $Content; echo '<hr>'; exit(); //*/ /* //去掉无用的页面脚本 //去掉js $cp = preg_replace( "@\<script(.*?)\</script\>@is", "", $cp ); //去掉HTML //去Table $cp = preg_replace( "@\<table(.*?)\</table\>@is", "", $cp ); //去Tr $cp = preg_replace( "@\<tr(.*?)\</tr\>@is", "", $cp ); //去Td $cp = preg_replace( "@\<td(.*?)\</td\>@is", "", $cp ); //去div $cp = preg_replace( "@\<div(.*?)\</div\>@is", "", $cp ); //去iframe $cp = preg_replace( "@\<iframe(.*?)\</iframe\>@is", "", $cp ); //去掉css //$cp = preg_replace( "@\<style(.*?)\</style\>@is", "", $cp ); */ //去掉超连接 $Content = preg_replace(EnCodeStr("@\\<a(.*?)\\>@is"), "", $Content); //去<!-- --> $Content = preg_replace(EnCodeStr("@\\<!--(.*?)\\--\\>@is"), "", $Content); return $Content; }
public function initializeLookupObj() { $model = D($this->getActionName()); // 删除原有的文件夹 if (is_dir(Dynamicconf . "/LookupObj")) { import('@.ORG.xhprof.FileUtil'); $fileUtil = new FileUtil(); $fileUtil->unlinkDir(Dynamicconf . "/LookupObj"); } $lookupobjlist = $model->where('status=1')->select(); // print_r(count($lookupobjlist)); // echo 99; // exit; $conlist = array(); $path = $model->GetDetailsPath(); if (!file_exists($path)) { createFolder($path); } foreach ($lookupobjlist as $k => $v) { if ($v['viewtype'] == 1) { $viewmasid = getFieldBy($v['viewname'], "name", "id", "mis_system_dataview_mas"); $chinaarr = array(); if ($viewmasid) { $viewsub = M("mis_system_dataview_sub")->field("otherfield,title")->where("masid=" . $viewmasid)->select(); $fieldsarr = explode(',', $v['fields']); foreach ($fieldsarr as $key2 => $val2) { foreach ($viewsub as $key1 => $val1) { if ($val2 == $val1['otherfield']) { $chinaarr[$val1['otherfield']] = $val1['title'] ? $val1['title'] : $val1['otherfield']; } } } } $conlist[$v['id']] = array('title' => $v['title'], 'fields' => $v['fields'], 'fields_china' => $chinaarr, 'checkforfields' => $v['checkforfields'], 'fieldcom' => $v['fieldcom'], 'listshowfields' => $v['listshowfields'], 'listshowfields_china' => $this->getDeatilshowname($v['mode'], $v['listshowfields'], '', 'china'), 'funccheck' => $v['funccheck'], 'funccheck_china' => $this->getDeatilshowname($v['mode'], $v['funccheck'], '', 'china'), 'funcinfo' => unserialize(base64_decode($v['funcinfo'])), 'url' => $v['url'], 'mode' => $v['mode'], 'checkformodel' => $v['checkformodel'], 'filed' => $v['filed'], 'filed1' => $v['filed1'], 'val' => $v['val'], 'showrules' => $v['showrules'], 'rulesinfo' => $v['rulesinfo'], 'rules' => $v['rules'], 'viewname' => $v['viewname'], 'viewtype' => $v['viewtype'], 'condition' => $v['rules'], 'dialogwidth' => $v['dialogwidth'], 'dialogheight' => $v['dialogheight'], 'status' => $v['status'], 'level' => $v['level'], 'datasort' => $v['datasort'], 'conftype' => $v['conftype'] ? $v['conftype'] : 0); } else { $conlist[$v['id']] = array('title' => $v['title'], 'fields' => $v['fields'], 'fields_china' => $this->getDeatilshowname($v['mode'], $v['fields'], '', 'china'), 'checkforfields' => $v['checkforfields'], 'fieldcom' => $v['fieldcom'], 'listshowfields' => $v['listshowfields'], 'listshowfields_china' => $this->getDeatilshowname($v['mode'], $v['listshowfields'], '', 'china'), 'funccheck' => $v['funccheck'], 'funccheck_china' => $this->getDeatilshowname($v['mode'], $v['funccheck'], '', 'china'), 'funcinfo' => unserialize(base64_decode($v['funcinfo'])), 'url' => $v['url'], 'mode' => $v['mode'], 'checkformodel' => $v['checkformodel'], 'filed' => $v['filed'], 'filed1' => $v['filed1'], 'val' => $v['val'], 'showrules' => $v['showrules'], 'rulesinfo' => $v['rulesinfo'], 'rules' => $v['rules'], 'viewname' => $v['viewname'], 'viewtype' => $v['viewtype'], 'condition' => $v['rules'], 'dialogwidth' => $v['dialogwidth'], 'dialogheight' => $v['dialogheight'], 'status' => $v['status'], 'level' => $v['level'], 'datasort' => $v['datasort'], 'conftype' => $v['conftype'] ? $v['conftype'] : 0); } if ($v['dtinfo']) { $conlist[$v['id']]['dt'] = unserialize(base64_decode($v['dtinfo'])); $conlist['versions'] = '1.0'; } else { if ($v['datetable']) { $conlist[$v['id']]['proid'] = $v['proid']; $conlist[$v['id']]['fieldback'] = $v['fieldback']; if ($v['orderfield']) { $conlist[$v['id']]['orderfield'] = $v['orderfield']; $conlist[$v['id']]['ordersort'] = $v['ordersort']; } // $conlist[$v['id']]['fieldcom']=$v['fieldcom']; $conlist[$v['id']]['dt'] = unserialize(base64_decode($v['datetable'])); if ($v['dtfuncfields']) { $conlist['dtfuncfields'] = $v['dtfuncfields']; $conlist['dtfuncinfo'] = $v['dtfuncinfo']; } } } $filename = $path . "/" . $v['id'] . ".php"; $model->SetSongleRule($filename, $conlist[$v['id']]); $fileindex[$v['id']] = $v['title']; } $pathconf = DConfig_PATH . '/LookupObj/Index'; if (!file_exists($pathconf)) { createFolder($pathconf); } $num = $model->SetSongleRule($pathconf . '/list.inc.php', $fileindex); $model->commit(); if ($num) { $json = '{"status":1,"statusCode":1,"navTabId":null,"message":"\\u64cd\\u4f5c\\u6210\\u529f","forward":null,"forwardUrl":null,"callbackType":null,"data":"","checkfield":null,"refreshtabs":null,"rel":null,"redalert":0}'; echo '<script>reloadindexview(' . $json . ')</script>'; exit; } else { $this->error('转换失败'); } // $this->success('操作成功'); }
$response = array('error' => 'Execution time is less 15 seconds, configure this with ini_set/set_time_limit or "php.ini" (if safe_mode is enabled), recommended time is 30 seconds or more'); } else { if (MAX_EXEC <= TIMEOUT) { $response = array('error' => 'The execution time is not configured enough to TIMEOUT in SOCKET, configure this with ini_set/set_time_limit or "php.ini" (if safe_mode is enabled), recommended that the "max_execution_time =;" be a minimum of 5 seconds longer or reduce the TIMEOUT in "define(\'TIMEOUT\', ' . TIMEOUT . ');"'); } else { if (isset($_GET['url']) === false || strlen($_GET['url']) === 0) { $response = array('error' => 'No such parameter "url"'); } else { if (isHttpUrl($_GET['url']) === false) { $response = array('error' => 'Only http scheme and https scheme are allowed'); } else { if (preg_match('#[^A-Za-z0-9_[.]\\[\\]]#', $param_callback) !== 0) { $response = array('error' => 'Parameter "callback" contains invalid characters'); $param_callback = JSLOG; } else { if (createFolder() === false) { $err = get_error(); $response = array('error' => 'Can not create directory' . ($err !== null && isset($err['message']) && strlen($err['message']) > 0 ? ': ' . $err['message'] : '')); $err = null; } else { $http_port = (int) $_SERVER['SERVER_PORT']; $tmp = createTmpFile($_GET['url'], false); if ($tmp === false) { $err = get_error(); $response = array('error' => 'Can not create file' . ($err !== null && isset($err['message']) && strlen($err['message']) > 0 ? ': ' . $err['message'] : '')); $err = null; } else { $response = downloadSource($_GET['url'], $tmp['source'], 0); fclose($tmp['source']); } }
} function checkFileExist($folder_path, $file_name) { return file_exists($folder_path . $file_name); } // If folder not exist, create it function createFolder($bin_name, $base_imgpath) { $folder_path = $base_imgpath . '/' . $bin_name . '/'; if (file_exists($folder_path)) { echo 'The folder name: ' . $bin_name . ' already exist!' . PHP_EOL; } else { if (!mkdir($folder_path, 0777)) { die('Failed to create folder...' . PHP_EOL); } else { echo 'Create folder with bin_name: ' . $bin_name . PHP_EOL; } } } // Get bin name from command line argument if (isset($argv[1])) { $bin_name = $argv[1]; } else { die('The bin name is a required argument.' . PHP_EOL); } // Get save path from command line argument if (isset($argv[2])) { $base_imgpath = $argv[2]; } createFolder($bin_name, $base_imgpath); saveMedia($bin_name, $base_imgpath);
/** * Create a EmbedContent object. * * @return void */ public function create() { $this->auth->restrict($this->permissionCreate); if (isset($_POST['save'])) { if ($insert_id = $this->save_embedcontent()) { log_activity($this->auth->user_id(), lang('embedcontent_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'embedcontent'); Template::set_message(lang('embedcontent_create_success'), 'success'); //Copy the template into a new folder $templateData = $this->templates_model->getTemplateById($_POST["templateid"]); $templateFileName = $templateData->filename; createFolder($_POST["name"], $templateFileName); redirect(SITE_AREA . '/embeds/embedcontent'); } // Not validation error if (!empty($this->embedcontent_model->error)) { Template::set_message(lang('embedcontent_create_failure') . $this->embedcontent_model->error, 'error'); } } else { //run the query for the cities we specified earlier } $templateData = $this->templates_model->getTemplates(); Template::set('templatesDrop', $templateData); Template::set('toolbar_title', lang('embedcontent_action_create')); Template::render(); }
/** * @todo insert image from posted data * */ public function addImg() { global $CONFIG; $data = $_POST; $indivID = $_GET['id']; $name = 'filename'; $path = ''; $uploaded_file = uploadFile($name, $path, 'image'); //if uploaded if ($uploaded_file['status'] != '0') { logFile('Upload Success'); if (extension_loaded('gd') && function_exists('gd_info')) { logFile('GD2 is installed. Checking image data.'); //validate email and get short_namecode $ses_user = $this->isUserOnline(); $username = $ses_user['login']['username']; $personID = $ses_user['login']['id']; $tmp_name = $uploaded_file['full_name']; $entry = str_replace(array('\'', '"'), '', $uploaded_file['real_name']); $image_name_encrypt = md5($entry); //check filename $dataExist = $this->imagezip->dataExist($personID, $entry); $path_entry = $CONFIG['default']['upload_path']; $src_tmp = $path_entry . "/" . $tmp_name; if (!$dataExist) { logFile('Prepare to cropping image'); $path_data = 'public_assets/'; //$path_user = $path_data.$username; $path_img = $path_data . '/img'; $path_img_1000px = $path_img . '/1000px'; $path_img_500px = $path_img . '/500px'; $path_img_100px = $path_img . '/100px'; $fileinfo = getimagesize($path_entry . '/' . $tmp_name); $toCreate = array($path_img, $path_img_1000px, $path_img_500px, $path_img_100px); createFolder($toCreate, 0755); copy($path_entry . "/" . $tmp_name, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'); if (!@copy($path_entry . "/" . $tmp_name, $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg')) { logFile('Copy file failed'); $status = "error"; $msg = error_get_last(); } else { logFile('Copy file success'); $dest_1000px = $CONFIG['default']['root_path'] . '/' . $path_img_1000px . '/' . $image_name_encrypt . '.1000px.jpg'; $dest_500px = $CONFIG['default']['root_path'] . '/' . $path_img_500px . '/' . $image_name_encrypt . '.500px.jpg'; $dest_100px = $CONFIG['default']['root_path'] . '/' . $path_img_100px . '/' . $image_name_encrypt . '.100px.jpg'; if ($fileinfo[0] >= 1000 || $fileinfo[1] >= 1000) { if ($fileinfo[0] > $fileinfo[1]) { $percentage = 1000 / $fileinfo[0]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } else { $percentage = 1000 / $fileinfo[1]; $config['width'] = $percentage * $fileinfo[0]; $config['height'] = $percentage * $fileinfo[1]; } $this->resize_pic($src_tmp, $dest_1000px, $config); unset($config); } logFile('Cropping to 1000px image'); //Set cropping for y or x axis, depending on image orientation if ($fileinfo[0] > $fileinfo[1]) { $config['width'] = $fileinfo[1]; $config['height'] = $fileinfo[1]; $config['x_axis'] = $fileinfo[0] / 2 - $config['width'] / 2; $config['y_axis'] = 0; } else { $config['width'] = $fileinfo[0]; $config['height'] = $fileinfo[0]; $config['x_axis'] = 0; $config['y_axis'] = $fileinfo[1] / 2 - $config['height'] / 2; } $this->cropToSquare($src_tmp, $dest_500px, $config); unset($config); logFile('Cropping to square image'); //set new config $config['width'] = 500; $config['height'] = 500; $this->resize_pic($dest_500px, $dest_500px, $config); unset($config); logFile('Cropping to 500px image'); $config['width'] = 100; $config['height'] = 100; $this->resize_pic($dest_500px, $dest_100px, $config); unset($config); logFile('Cropping to 100px image'); //add file information to array $data['filename'] = $entry; $data['md5sum'] = $image_name_encrypt; $data['mimetype'] = $fileinfo['mime']; $data['indivID'] = $indivID; $data['personID'] = $personID; $insertData = $this->insertonebyone->insertTransaction('img', $data); if ($insertData) { logFile('Insert Data Success'); $this->msg->add('s', 'Sukses Memperbarui Gambar'); $session = new Session(); $dataSession = array(); $sess_image = $session->get_session(); if (isset($sess_image['image_sess'])) { logFile('Fetch image session'); foreach ($sess_image['image_sess'] as $data_before) { array_push($dataSession, $data_before); } } array_push($dataSession, $data); $session->set_session($dataSession, 'image_sess'); //$session->delete_session('onebyone'); } else { logFile('Insert Data Failed'); $this->msg->add('e', 'Gagal Memperbarui Gambar'); } } // end if copy } else { logFile('File Image exist'); $this->msg->add('e', 'Data Gambar Telah Ada'); } unlink($src_tmp); } else { logFile('GD2 is not installed'); $this->msg->add('e', 'Sistem Error. Harap menghubungi tim developer kami.'); } } else { logFile('Upload Image Failed'); $this->msg->add('e', $uploaded_file['message']); } //header('Location: ../../browse/editIndiv/?id='.$indivID); redirect($basedomain . '../editIndiv/?id=' . $indivID . '#img'); }
function run_create_module($task, $args) { ini_set("memory_limit", "2048M"); // get configuration // define constants define('SF_ROOT_DIR', sfConfig::get('sf_root_dir')); define('SF_APP', 'backend'); define('SF_ENVIRONMENT', 'prod'); define('SF_DEBUG', false); require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'; if (!class_exists("FileHelper")) { include sfConfig::get('sf_root_dir') . "/lib/helper/FileHelper.php"; } $createLib = true; if (isset($args[1])) { $createLib = $args[1] == "lib"; } if (isset($args[0])) { $moduleName = strtolower($args[0]); } else { echo_cms_sep(); echo_cms_title("\tUsage: symfony create-module <module_name> <lib>"); echo_cms_sep(); exit; } $formFile = sfConfig::get('sf_root_dir') . "/config/form.xml"; if (is_readable($formFile)) { $objects = XMLParser::getXMLdataValues($formFile); $objList = array(); foreach ($objects as $obj) { if ($obj['tag'] == 'OBJECT' && $obj['type'] == 'open') { $objName = $obj['attributes']['NAME']; $objModule = strtolower($obj['attributes']['MODULE']); if (!$objModule) { $objModule = strtolower(str_replace('I18n', '', $objName)); } if ($objModule == $moduleName) { $objList[] = $objName; } } } } if (empty($objList)) { echo_cms_error("\tError: No objects found for module " . $moduleName . " in form.xml file!"); exit; } if ($createLib) { $libActionsContent = getActionsContent($moduleName); // class mediaCoreActions extends sfActions $sf = $moduleName . "Core"; // Lib folders $libFolder = "lib/modules/"; createFolder($libFolder . $moduleName); createFolder($libFolder . $moduleName . "/actions"); createFolder($libFolder . $moduleName . "/config"); createFolder($libFolder . $moduleName . "/templates"); $libActionsFile = $libFolder . $moduleName . "/actions/actions.class.php"; writeContentToFile($libActionsFile, $libActionsContent); } else { $sf = ""; } // Creating apps/frontend, apps/backend files... $appBackActionsContent = getActionsContent($moduleName, "", "sf", $objList); // Example: class userActions extends sfActions $appFrontActionsContent = getActionsContent($moduleName, "", $sf); // Example: class newsActions extends newsCoreActions || sfActions // Backend folders $backFolder = "apps/backend/modules/"; createFolder($backFolder . $moduleName); createFolder($backFolder . $moduleName . "/actions"); createFolder($backFolder . $moduleName . "/config"); createFolder($backFolder . $moduleName . "/templates"); $backActionsFile = $backFolder . $moduleName . "/actions/actions.class.php"; writeContentToFile($backActionsFile, $appBackActionsContent); // Frontend folders $frontFolder = "apps/frontend/modules/"; createFolder($frontFolder . $moduleName); createFolder($frontFolder . $moduleName . "/actions"); createFolder($frontFolder . $moduleName . "/config"); createFolder($frontFolder . $moduleName . "/templates"); $ftontActionsFile = $frontFolder . $moduleName . "/actions/actions.class.php"; writeContentToFile($ftontActionsFile, $appFrontActionsContent); // ------------------------------------------------------------------------------------------ $configFolder = $backFolder . $moduleName . "/config/"; $leftFile = $configFolder . "leftTree.xml"; $leftContent = createXMLContent("left", $moduleName, $objList); writeContentToFile($leftFile, $leftContent); $mainFile = $configFolder . "mainList.xml"; $mainContent = createXMLContent("main", $moduleName, $objList); writeContentToFile($mainFile, $mainContent); $rightFile = $configFolder . "rightTree.xml"; $rightContent = createXMLContent("right", $moduleName, $objList); writeContentToFile($rightFile, $rightContent); $resourcesFile = $configFolder . "resources.xml"; $resourcesContent = createXMLContent("resources", $moduleName, $objList); writeContentToFile($resourcesFile, $resourcesContent); $blocksFile = $frontFolder . $moduleName . "/config/" . "blocks.xml"; $blocksContent = createXMLContent("blocks", $moduleName, $objList); writeContentToFile($blocksFile, $blocksContent); echo_cms("Done!"); echo_cms_sep(); }
/** * 生成缩略图 * @author yangzhiguo0903@163.com * @param string 源图绝对完整地址{带文件名及后缀名} * @param string 目标图绝对完整地址{带文件名及后缀名} * @param int 缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)} * @param int 缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)} * @param bool createimg true输出到浏览器 false输出到文件 * @param bool proportion 剪切true 缩放false补充白背景 * @return boolean */ function imgagethumb($src_img, $dst_img, $width = 75, $height = 75, $createimg = true, $proportion = false) { if (!is_file($src_img)) { return false; } $to = ''; if (!empty($dst_img)) { $ot = strtolower(pathinfo($dst_img, PATHINFO_EXTENSION)); $dirname = pathinfo($dst_img, PATHINFO_DIRNAME); if (!file_exists($dirname)) { createFolder($dirname); } } else { $ot = strtolower(pathinfo($src_img, PATHINFO_EXTENSION)); } $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot); $srcinfo = getimagesize($src_img); $src_w = $srcinfo[0]; $src_h = $srcinfo[1]; //if($src_h<intval(C('THUMB_HEIGHT')) || $src_w<intval(C('THUMB_WIDTH'))){return false;} $type = strtolower(substr(image_type_to_extension($srcinfo[2]), 1)); $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type); if (!$createimg) { header('content-type:image/' . ($type == 'jpg' ? 'jpeg' : $type)); } $dst_h = $height; $dst_w = $width; $x = $y = 0; $zfxbili = 0.0; //如果缩略图是正方形,算出源图的宽高比例如果接近正方形的话就生成正方形的图片 if ($width = $height) { $zfxbili = doubleval($src_w) / doubleval($src_h); } //源图和缩略图一样大小的情况直接复制 if ($src_w == $width && $src_h == $height) { return copy($src_img, $dst_img); } $src_image = $createfun($src_img); $cropped_image = imagecreatetruecolor($width, $height); if ($width == $height && 2 > $zfxbili && $zfxbili >= 0.5) { $white = imagecolorallocate($cropped_image, 255, 255, 255); imagefill($cropped_image, 0, 0, $white); } else { imagesavealpha($src_image, true); //这里很重要; $alpha = imagecolorallocatealpha($cropped_image, 255, 255, 255, 127); imagealphablending($cropped_image, false); //这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色; imagesavealpha($cropped_image, true); //这里很重要,意思是不要丢了$thumb图像的透明色 imagefill($cropped_image, 0, 0, $alpha); } //剪切图片(先从源图片中按缩略图的比例剪切出一个区域再缩放到缩略图中) if ($proportion) { //源图比缩略图大的情况 if ($src_w > $width && $src_h > $height) { //缩略图宽高一样的情况 if ($width == $height) { //源图类似正方形2:1 比例 宽大于高 if ($zfxbili > 1 && $zfxbili < 2) { //算出缩放的实际高度 $ah = $src_h * $width / $src_w; //算出实际的y轴 $ay = ($height - $ah) / 2; imagecopyresampled($cropped_image, $src_image, 0, $ay, 0, 0, $width, $ah, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图类似正方形1:2 比例 高大于宽 if ($zfxbili >= 0.5 && $zfxbili < 1) { //算出缩放的实际宽度 $aw = $src_w * $height / $src_h; //算出实际的x轴 $ax = ($width - $aw) / 2; imagecopyresampled($cropped_image, $src_image, $ax, 0, 0, 0, $aw, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽高一样 if ($src_h == $src_w) { imagecopyresampled($cropped_image, $src_image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽大于高 if ($src_w > $src_h) { $ww = $src_h; $_x = ($src_w - $src_h) / 2; imagecopyresampled($cropped_image, $src_image, 0, 0, $_x, 0, $width, $height, $ww, $ww); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } else { //源图宽小于等于高 $ww = $src_w; $_y = ($src_h - $src_w) / 2; imagecopyresampled($cropped_image, $src_image, 0, 0, 0, $_y, $width, $height, $ww, $ww); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } else { //缩略图宽高不一样的情况 //缩略图宽大于高 if ($width > $height) { $bili = $width / $height; $hh = $src_w / $bili; $_y = ($src_h - $hh) / 2; if ($src_w > $src_h) { //查找合适剪切的高 $tem_w = $src_w; $tem_h = 0; while (true) { $tem_h = $tem_w / $bili; if ($tem_h < $src_h) { break; } else { $tem_w--; } } $_x = ($src_w - $tem_w) / 2; $_y = ($src_h - $tem_h) / 2; imagecopyresampled($cropped_image, $src_image, 0, 0, $_x, $_y, $width, $height, $tem_w, $tem_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } else { imagecopyresampled($cropped_image, $src_image, 0, 0, 0, $_y, $width, $height, $src_w, $hh); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } else { //缩略图宽小于等于高 $bili = $height / $width; $ww = $src_h / $bili; $_x = ($src_w - $ww) / 2; if ($src_h > $src_w) { //查找合适剪切的高 $tem_h = $src_h; $tem_w = 0; while (true) { $tem_w = $tem_h / $bili; if ($tem_w < $src_w) { break; } else { $tem_h--; } } $_x = ($src_w - $tem_w) / 2; $_y = ($src_h - $tem_h) / 2; imagecopyresampled($cropped_image, $src_image, 0, 0, $_x, 0, $width, $height, $tem_w, $tem_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } else { imagecopyresampled($cropped_image, $src_image, 0, 0, $_x, 0, $width, $height, $ww, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } } } else { //源图任意一个长度比缩略图小的情况 if ($src_h <= $height && $src_w <= $width) { //源图宽高都比缩略图小 $_x = ($width - $src_w) / 2; $_y = ($height - $src_h) / 2; imagecopyresampled($cropped_image, $src_image, $_x, $_y, 0, 0, $src_w, $src_h, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } else { if ($src_h <= $height) { //源图高比缩略图小 $hh = $width / ($src_w / $src_h); $_y = ($height - $hh) / 2; imagecopyresampled($cropped_image, $src_image, 0, $_y, 0, 0, $width, $src_h, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } else { //源图宽比缩略图小 $ww = $height / ($src_h / $src_w); $_x = ($width - $ww) / 2; imagecopyresampled($cropped_image, $src_image, $_x, 0, 0, 0, $src_w, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } } } else { //缩放图片(把源图片完整的缩放到缩略图中) //缩略图宽高一样 if ($width == $height) { //源图宽大于高 if ($src_w > $src_h) { $ah = $src_h * $width / $src_w; $ay = ($height - $ah) / 2; imagecopyresampled($cropped_image, $src_image, 0, $ay, 0, 0, $width, $ah, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽小于高 if ($src_w < $src_h) { $aw = $src_w * $height / $src_h; $ax = ($width - $aw) / 2; imagecopyresampled($cropped_image, $src_image, $ax, 0, 0, 0, $aw, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽等于高 if ($src_w == $src_h) { imagecopyresampled($cropped_image, $src_image, 0, 0, 0, 0, $width, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } //缩略图宽大于高 if ($width > $height) { //源图宽大于高 if ($src_w > $src_h) { $ah = $src_h * $width / $src_w; $ay = ($height - $ah) / 2; imagecopyresampled($cropped_image, $src_image, 0, $ay, 0, 0, $width, $ah, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽小于高 if ($src_w <= $src_h) { $aw = $src_w * $height / $src_h; $ax = ($width - $aw) / 2; imagecopyresampled($cropped_image, $src_image, $ax, 0, 0, 0, $aw, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽等于高 //if($src_w==$src_h){ // imagecopyresampled($cropped_image, $src_image,0,0,0, 0, $width, $height,$src_w, $src_h); //} } //缩略图宽小于高 if ($width < $height) { //源图宽小于高 if ($src_w <= $src_h) { $aw = $src_w * $height / $src_h; $ax = ($width - $aw) / 2; imagecopyresampled($cropped_image, $src_image, $ax, 0, 0, 0, $aw, $height, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } //源图宽大于高 if ($src_w > $src_h) { $ah = $src_h * $width / $src_w; $ay = ($height - $ah) / 2; imagecopyresampled($cropped_image, $src_image, 0, $ay, 0, 0, $width, $ah, $src_w, $src_h); if ($createimg) { $otfunc($cropped_image, $dst_img); } else { $otfunc($cropped_image); } imagedestroy($cropped_image); imagedestroy($src_image); return true; } } } return true; }
$exts = $params["ftype"]; } $files = getdirfiles($dir, $exts); $result = array("error" => 0, "files" => $files); break; case "delfiles": if ($params["files"]) { $result = delfiles($params["files"]); } break; case "mkdir": if ($params["name"] && $params["pdir"]) { $path = $_SERVER['DOCUMENT_ROOT']; $path = trim($path, "/"); if (!file_exists($path . $params["pdir"] . "/" . $params["name"])) { $rev = createFolder($path . $params["pdir"] . "/" . $params["name"]); if ($rev) { $result = array("error" => 0); } } else { $result = array("error" => -9); } } else { $result = array("error" => -101); } break; case "deldir": if ($params["folder"]) { $bfdeldirfun = $config["beforedeldir"]; $afdeldirfun = $config["afterdeldir"]; $ballow = true;
if (in_array($attach_ext, array('gif', 'jpg', 'jpeg', 'png', 'bmp'))) { require_once R_P . 'require/imgfunc.php'; if (!($img_size = GetImgSize($srcfile, $attach_ext))) { Showmsg('upload_content_error'); } $img_size[0] = $img_size['width']; $img_size[1] = $img_size['height']; unset($img_size['width'], $img_size['height']); if ($db_watermark && $forumset['watermark'] && $img_size[2] < '4' && $img_size[0] > $db_waterwidth && $img_size[1] > $db_waterheight && function_exists('imagecreatefromgif') && function_exists('imagealphablending') && ($attach_ext != 'gif' || function_exists('imagegif') && ($db_ifgif == 2 || $db_ifgif == 1 && (PHP_VERSION > '4.4.2' && PHP_VERSION < '5' || PHP_VERSION > '5.1.4'))) && ($db_waterimg && function_exists('imagecopymerge') || !$db_waterimg && function_exists('imagettfbbox'))) { ImgWaterMark($srcfile, $db_waterpos, $db_waterimg, $db_watertext, $db_waterfont, $db_watercolor, $db_waterpct, $db_jpgquality); } if ($db_ifathumb) { $thumbdir = "thumb/{$fileuplodeurl}"; $thumburl = $db_ifftp ? D_P . "data/tmp/thumb_{$newattname}" : "{$attachdir}/{$thumbdir}"; list($db_thumbw, $db_thumbh) = explode("\t", $db_athumbsize); createFolder(dirname($thumburl)); if ($thumbsize = MakeThumb($srcfile, $thumburl, $db_thumbw, $db_thumbh)) { $img_size[0] = $thumbsize[0]; $img_size[1] = $thumbsize[1]; $ifthumb = 1; } } //Start elementupdate if ($db_ifpwcache & 512 && !$value['needrvrc'] && !$elementpic) { $elementpic = array('aid' => $rt['aid'], 'attachurl' => $fileuplodeurl, 'ifthumb' => $ifthumb); } //End elementupdate } if (pwFtpNew($ftp, $db_ifftp)) { if (!$ftp->upload($srcfile, $fileuplodeurl)) { continue;
/** * @param $url 远程地址 * @param $path 本地地址 * @param bool $copy 是否拷贝 * @return bool */ function saveImage($url, $path, $copy = false, $echo = true) { date_default_timezone_set('PRC'); $newfname = $path; if (file_exists($newfname)) { return false; } // echo "URL:$url,PATH:$path"; createFolder($newfname); if ($copy) { if (!copy($url, $path)) { if ($echo) { echo "copy_error"; } return false; } } else { // echo "Remote"; $i = 0; while (read_and_save_img($url, $newfname, false) === false) { $i++; if ($i > 5) { break; } } } @chmod($newfname, 0777); return true; }
function createFolder($path) { if (!is_dir($path)) { createFolder(dirname($path)); @mkdir($path); @chmod($path, 0777); @fclose(@fopen($path . '/index.html', 'w')); @chmod($path . '/index.html', 0777); } }