Introduction to the use of PHPCMS module development SWFUpload _php Instance

Source: Internet
Author: User
Formal contact with the development of the PHPCMS module. Several functional modules have been developed. The problem of uploading images in batches was encountered. So began to dig into the use of phpcms inside the swfupload.

In the phpcms inside the content type can be directly assigned to the picture group. But the picture Group feature is not what I want to use. I need to upload an entire static HTML file.

Be able to find a way to upload an entire folder. And can retain the original file name.

The purpose is summarized as follows:

1, does not change the system's file and directory structure.

2, realize the multi-attachment upload function.

3, can get the folder name after uploading.

The function of uploading attachments is included in Phpcms. I want to go with the SWFUpload function, and this feature is integrated into the PHPCMS attachment upload function. All I have to do is pull it out and change it.

In the first step, I'll study how this is called.

First, open the Firebug in the Firefox browser to open the Network panel. Find the button that swfupload in PHPCM. See what connection the system is requesting.
Copy the Code code as follows:
? m=attachment&c=attachments&a=swfupload&args=10,,1&module=&catid=&authkey= B756a93dea2e627293e88fa9d62af709&pc_hash=ixfbo1

We captured a bunch of such requests. The SWFUpload method inside the attachements controller of the attachment module was called.

Let's find this method inside the controller in this module.

Inside the phpcms/modoules/attachemet/attachemts.php.

open it and see the code below.
Copy CodeThe code is as follows:
Public Function swfupload () {
$grouplist = GetCache (' grouplist ', ' member ');
if (Isset ($_post[' Dosubmit ')) {
If the contents of the inside we do not look at the moment. Because this is the post-upload processing. We need to find out how to introduce swfupload first.
} else {
if ($this->isadmin==0 &&! $grouplist [$this->groupid][' allowattachment ']) showmessage (L (' Att_no_ Permission '));
$args = $_get[' args '];//get parameters
$authkey = $_get[' Authkey '];//get the key
if (Upload_key ($args)! = $authkey) showmessage (L (' attachment_parameter_error '));//Authentication key
Extract (Getswfinit ($_get[' args '));//Split parameter
$siteid = $this->get_siteid ();//Get Site ID
$site _setting = get_site_setting ($siteid);//Get Site Settings
$file _size_limit = sizecount ($site _setting[' upload_maxsize ']*1024);//Allow upload size
$att _not_used = Param::get_cookie (' Att_json ');//Get a list of files that have not been processed
if (Empty ($att _not_used) | |!isset ($att _not_used)) $tab _status = ' class= ' on ';//If there is an unhandled setting the label style is on
if (!empty ($att _not_used)) $div _status = ' hidden ';//Hide Tag otherwise
$att = $this->att_not_used ();//Get a list of temporarily unhandled files
Include $this->admin_tpl (' swfupload ');//This place is the key. The template was loaded.
}
}

Before we leave it, that is to deal with the upload of things. I started from else. First verify that attachments are allowed to be uploaded

Then from the $_get inside get swfupload parameter args, and then to verify the key, the key passed to parse args. Get the site's ID, get the site's settings, and get the size of the attachments that are allowed to upload. The list of unused attachments is obtained from the cookie.

Set the various displays inside the template. It is also the most critical. It uses the SWFUpload template. That means I'm going to find this template. See how swfupload is coming.

The template is here: phpcms/modules/attachment/templates/swfupload.tpl.php

Open the template file. A bunch of files are introduced on the template file:
Copy the Code code as follows:
Admin_tpl (' header ', ' attachment ');? >






The first is the introduction of the header file. I'll probably look inside. There's jquery or something. This is the necessary document. So we need to introduce this head when we need it.

After that is the SWFUpload style file and the necessary JS. Here is a system function called Initupload, which is what this function is all about.

Don't underestimate the line. The entire swfupload configuration is here.

Let's go look for this function.

Found its trail in phpcms/modules/attachment/functions/golable.func.php. The code below, the main function of this function is to configure swfupload this plugin.
Copy CodeThe code is as follows:
/* Flash upload initialization
* Initialize the required parameters in SWFUpload upload
* @param $module Module name
* @param $catid Column ID
* @param $args Pass Parameters
* @param $userid User ID
* @param $groupid user Group ID
* @param $isadmin is administrator mode
*/
function Initupload ($module, $catid, $args, $userid, $groupid = ' 8 ', $isadmin = ' 0 ') {
$grouplist = GetCache (' grouplist ', ' member ');
if ($isadmin ==0 &&! $grouplist [$groupid] [' allowattachment ']) return false;
Extract (Getswfinit ($args));
$siteid = Param::get_cookie (' SiteID ');
$site _setting = get_site_setting ($siteid);
$file _size_limit = $site _setting[' upload_maxsize ');
$sess _id = sys_time;
$swf _auth_key = MD5 (pc_base::load_config (' System ', ' Auth_key '). $sess _id);
$init = ' var swfu = ' \ ';
$ (document). Ready (function () {
SWFU = new SWFUpload ({
Flash_url: "'. Js_path. ' swfupload/swfupload.swf? ' +math.random (),
Upload_url: "'. App_path. ' Index.php?m=attachment&c=attachments&a=swfupload&dosubmit=1 ',
File_post_name: "Filedata",
post_params:{"Swfuploadsessid": "'. $sess _id. '", "module": "'. $module. '", "catid": "'. $_get[' catid ']. '", "userid": "'. $userid. ' "," SiteID ":" '. $siteid. ' "," Dosubmit ":" 1 "," Thumb_width ":" '. $thumb _width. ' "," thumb_height ":". $thumb _ Height. ' "," watermark_enable ":" '. $watermark _enable. ' "," filetype_post ":" '. $file _types_post. ' "," Swf_auth_key ":" '. $swf _auth_key. ' "," ISAdmin ":" '. $isadmin. ' "," GroupID ":" '. $groupid. ' "},
File_size_limit: "'. $file _size_limit. '",
File_Types: "'. $file _types. '",
File_types_description: "All Files",
File_upload_limit: "'. $file _upload_limit. '",
Custom_settings: {progresstarget: "fsuploadprogress", Cancelbuttonid: "Btncancel"},

Button_image_url: "",
Button_width:75,
Button_height:28,
button_placeholder_id: "Buttonplaceholder",
Button_text_style: "",
Button_text_top_padding:3,
Button_text_left_padding:12,
Button_window_mode:SWFUpload.WINDOW_MODE. TRANSPARENT,
Button_cursor:SWFUpload.CURSOR.HAND,

File_dialog_start_handler:filedialogstart,
File_queued_handler:filequeued,
File_queue_error_handler:filequeueerror,
File_dialog_complete_handler:filedialogcomplete,
Upload_progress_handler:uploadprogress,
Upload_error_handler:uploaderror,
Upload_success_handler:uploadsuccess,
Upload_complete_handler:uploadcomplete
});
})';
return $init;
}

Back to the point. Let's see the template swfupload.tpl.php

This template uses a JS to control

  • Displayed as a tab. We can use Firebug to find the ID of the tab with the SWFUpload button we want to find.

    That ID is tab_swf_1.

    This is a div code as follows.
    Copy the Code code as follows:
    ">





    ,

    Onclick= "Change_params ()" >









    Here we see that there is a span ID of buttonplaceholder and there is such a line in the config file button_placeholder_id: "Buttonplaceholder", it is obvious. When the page is loaded The element with ID Buttonplaceholder will be replaced by JS as the SWFUpload upload control.

    And then we're going to trigger the SWF upload method after we've selected the file.

    The following code is found in the code. This invokes the Swfu.startupload () method. This method defines the place within the swfupload.js. We don't have to bother.
    Copy the Code code as follows:


    So far. We've found the swfupload. How to use the upload control

    How do I call this stuff in my program?

    First of all, we need to introduce these necessary files into the template that appears in this control.
    Copy the Code code as follows:






    The code is as shown above.

    And then, in our template, where we want to place swfupload, write this tag.
    Copy the Code code as follows:


    This obviously reveals that we've uploaded the file to the SWFUpload method in the attachments controller in the attachment module to handle it.

    This place is what I had not noticed before.

    Take a look.
    Copy CodeThe code is as follows:
    if ($_post[' Swf_auth_key ')! = MD5 (pc_base::load_config (' System ', ' Auth_key '). $_post[' Swfuploadsessid ']) | | ($_post[' isadmin ']==0 &&! $grouplist [$_post[' GroupID ']][' allowattachment ']) Exit ();
    Pc_base::load_sys_class (' attachment ', ', 0);
    $attachment = new Attachment ($_post[' module '],$_post[' catid '],$_post[' SiteID ']);
    $attachment->set_userid ($_post[' userid ');
    $aids = $attachment->upload (' Filedata ', $_post[' filetype_post '], ",", Array ($_post[' thumb_width '],$_post[' Thumb_height ']), $_post[' watermark_enable ');
    if ($aids [0]) {
    $filename = (Strtolower (CHARSET)! = ' Utf-8 ')? Iconv (' GBK ', ' utf-8 ', $attachment->uploadedfiles[0][' filename '): $attachment->uploadedfiles[0][' filename '] ;
    if ($attachment->uploadedfiles[0][' isimage ') {
    echo $aids [0]. ', '. $this->upload_url. $attachment->uploadedfiles[0][' filepath ']. ', '. $attachment uploadedfiles[0][' isimage '. ', '. $filename;
    } else {
    $fileext = $attachment->uploadedfiles[0][' Fileext ');
    if ($fileext = = ' Zip ' | | $fileext = = ' rar ') $fileext = ' rar ';
    ElseIf ($fileext = = ' Doc ' | | $fileext = = ' docx ') $fileext = ' Doc ';
    ElseIf ($fileext = = ' xls ' | | $fileext = = ' xlsx ') $fileext = ' xls ';
    ElseIf ($fileext = = ' ppt ' | | $fileext = = ' pptx ') $fileext = ' ppt ';
    ElseIf ($fileext = = ' flv ' | | $fileext = = ' swf ' | | $fileext = = ' RM ' | | $fileext = = ' rmvb ') $fileext = ' flv ';
    else $fileext = ' do ';
    echo $aids [0]. ', '. $this->upload_url. $attachment->uploadedfiles[0][' filepath ']. ', '. $fileext. ', '. $filename;
    }
    Exit
    } else {
    Echo ' 0, '. $attachment->error ();
    Exit

    It's more important to have a few lines inside.

    First it loads the attachment class of the system and uses the method inside.

    The program has done the echo operation to upload successfully. The returned items are returned with the number, post-upload address, extension name, and file name.

    Who are these things for? We have to go back and look at the configuration file.

    There is a section in the configuration file that is the method that each event will trigger during the upload process. There are uploads that have been uploaded successfully and have failed to upload. And so on.

    We can see that there is a way to File_dialog_complete_handler:filedialogcomplete,

    In fact, these have been upgraded to the SWFUpload category. Interested in studying.

    Then we find this method in Phpcms/static/swfupload/handler.js.

    See the upload success after echo out of the data is parsed.

    The parsing method is as follows
    Copy the Code code as follows:
    function Att_show (serverdata,file)
    {
    var serverdata = Serverdata.replace (//g, ");
    var data = Serverdata.split (', ');
    var id = data[0];
    var src = data[1];
    var ext = data[2];
    var filename = data[3];
    if (id = = 0) {
    Alert (SRC)
    return false;
    }
    if (ext = = 1) {
    var img = ';
    } else {
    var img = ';
    }
    $.get (' index.php?m=attachment&c=attachments&a=swfupload_json&aid= ' +id+ ' &src= ' +src+ ' & Filename= ' +filename);
    $ (' #fsUploadProgress '). Append ('

  • ');
    $ (' #attachment_ ' +id). HTML (IMG);
    $ (' #att-status '). Append (' | ') +SRC);
    $ (' #att-name '). Append (' | ') +filename);
    }

    The purpose of this method is to add the attachment that we uploaded successfully to the element with ID fsuuploadprogress. But we still got the files.

    The key is here. Do we not have an instance of the attachment system class in the SWFUpload method?

    The actual upload attachment is implemented here. We call the attachment inside the upload method to implement the file upload.

    The upload method in this attachment file is inside the system class, inside the phpcms/libs/classes/attachment.class.php.

    In this class, we can find the upload method with a line in it.
    Copy the Code code as follows:
    $this->savepath = $this->upload_root. $this->upload_dir.date (' y/md/');

    This is a natural way to specify the directory to upload to. The file name is obtained by using the GetName method.

    Here we have a clear idea.

    That's how the system works.

    First, in the template reference swfupload (configuration file is generated by the function), upload the file->attachment module SWFUpload method Processing ( Use the Upload method inside the system's attachment class to loop through the attachments and return the results to the SWFUpload method), and the results are returned to the page by SWFUpload method (Filedialogcomplete).

    In the above we have implemented the introduction of swfupload in the template. But we use the configuration file and upload the attachment method, etc. is the system originally brought. I do not implement the directory structure and file naming methods that I want. What to do?

    Change.

    How to change, first of all to get rid of the configuration file. Create your own function inside the functions folder inside your module. We named global.func.php with our own function name file, so the system will load our function through Auto_load.

    Let's go in. We copy the Initupload function in the Attachment module functions folder underneath the system global.func.php. Modify only one of the rows
    Copy the Code code as follows:
    Upload_url: "'. App_path. ' Index.php?m= your module name &c= your controller name &a= your method name &dosubmit=1 ',

    The file is then submitted to our controller. and call our own method of writing

    Then we go to the attachment class of the system we create a myattachment.class.php under the Classes folder under our own module

    Write a class of our own. Attachment class to integrate the system. (Remember, the private method in the copy comes.) We need to change a few lines. The first thing is, the upload method inside the upload directory to get rid of. Then the name of the file to get rid of the method.
    Copy the Code code as follows:
    function upload ($field, $alowexts = ", $maxsize = 0, $overwrite = 0, $thumb _setting = Array (), $watermark _enable = 1) {
    if (!isset ($_files[$field])) {
    $this->error = UPLOAD_ERR_OK;
    return false;
    }
    if (Empty ($alowexts) | | $alowexts = = ") {
    $site _setting = $this->_get_site_setting ($this->siteid);
    $alowexts = $site _setting[' Upload_allowext ');
    }
    $FN = $_get[' Ckeditorfuncnum ')? $_get[' ckeditorfuncnum ': ' 1 ';

    $this->field = $field;
    $this->savepath = $this->upload_root. $this->upload_dir.date (' Ymd ');// Here we need to modify the next. You can also do this without modification. Specify the directory when we instantiate the class.
    $this->alowexts = $alowexts;
    $this->maxsize = $maxsize;
    $this->overwrite = $overwrite;
    $uploadfiles = Array ();
    $description = Isset ($GLOBALS [$field. ' _description '])? $GLOBALS [$field. ' _description ']: Array ();
    if (Is_array ($_files[$field [' Error '])) {
    $this->uploads = count ($_files[$field [' Error ']);
    foreach ($_files[$field] [' ERROR '] as $key = + $error) {
    if ($error = = = Upload_err_no_file) continue;
    if ($error!== upload_err_ok) {
    $this->error = $error;
    return false;
    }
    $uploadfiles [$key] = Array (' tmp_name ' = $_files[$field] [' tmp_name '] [$key], ' name ' = $_files[$field] [' Name '][$ Key], ' type ' = $_files[$field] [' type '] [$key], ' size ' = $_files[$field] [' size '] [$key], ' ERROR ' = $_files[$ field][' ERROR ' [$key], ' description ' = $description [$key], ' fn ' = $FN);
    }
    } else {
    $this->uploads = 1;
    if (! $description) $description = ';
    $uploadfiles [0] = array (' tmp_name ' = $_files[$field [' tmp_name '], ' name ' = $_files[$field [' name '], ' type ' = > $_files[$field] [' type '], ' size ' = $_files[$field [' Size '], ' error ' = $_files[$field [' Error '], ' Description ' = $description, ' fn ' and $FN);
    }

    if (!dir_create ($this->savepath)) {
    $this->error = ' 8 ';
    return false;
    }
    if (!is_dir ($this->savepath)) {
    $this->error = ' 8 ';
    return false;
    }
    @chmod ($this->savepath, 0777);

    if (!is_writeable ($this->savepath)) {
    $this->error = ' 9 ';
    return false;
    }
    if (! $this->is_allow_upload ()) {
    $this->error = ' 13 ';
    return false;
    }
    $aids = Array ();
    foreach ($uploadfiles as $k = = $file) {
    $fileext = Fileext ($file [' name ']);
    if ($file [' ERROR ']! = 0) {
    $this->error = $file [' ERROR '];
    return false;
    }
    if (!preg_match ("/^ (". $this->alowexts. ") $/", $fileext)) {
    $this->error = ' 10 ';
    return false;
    }
    if ($this->maxsize && $file [' size '] > $this->maxsize) {
    $this->error = ' 11 ';
    return false;
    }
    if (! $this->isuploadedfile ($file [' tmp_name '])) {
    $this->error = ' 12 ';
    return false;
    }
    $temp _filename = $this->getname ($fileext);//Name here. We need to change the
    $temp _filename = $file [' Tmp_name ']. $fileext; Modified to the original system file name.
           $savefile = $this->savepath. $temp _filename; $savefile = Preg_replace ("/(PHP|PHTML|PHP3|PHP4|JSP|EXE|DLL|ASP|CER|ASA|SHTML|SHTM|ASPX|ASAX|CGI|FCGI|PL) (\.| $)/I "," _\\1\\2 ", $savefile); $filepath = Preg_replace (new_addslashes ("|^". $this->upload_root. "|"), "", $savefile); if (! $this->overwrite && file_exists ($savefile)) continue; $upload _func = $this->upload_func; if (@ $upload _func ($file [' Tmp_name '], $savefile) {$this->uploadeds++; @chmod ($savefile, 0644), @unlink ($file [' tmp _name ']); $file [' name '] = Iconv ("Utf-8", CHARSET, $file [' name ']); $uploadedfile = Array (' filename ' = ' = ' $file [' name '], ' filepath ' + $filepath, ' filesize ' = ' = ' $file [' size '], ' Fileext ' = $fileext, ' fn ' = ' $file [' FN ']; $thumb _enable = Is_array ($thumb _setting) && ($thumb _setting[0] > 0 | | $thumb _setting[1] > 0)? 1:0; $image = new Image ($thumb _enable, $this->siteid); if ($thumb _enable) {$image->thumb ($savefile, ', $thumb _setting[0], $thumb _setting[1]);} if ($watermark _enaBLE) {$image->watermark ($savefile, $savefile);} $aids [] = $this->add ($uploadedfile); }} return $aids; }

    Note: Here we can re-establish the system under the Attachment module my_attachment.php but this will affect the system's attachment upload function.

    Inside our own controller. We need to load our own classes at this time.
    Copy the Code code as follows:
    Pc_base::load_app_class (' Your module name ', ' ', 0 ');

    The remaining operations can be modified by referring to the SWFUpload method inside the attachments controller under the attachment module of the system.

    At this point, I have finished my purpose. Do not change the system file directory based on. Complete the file upload function I want.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.