Social Icons

суббота, 16 февраля 2013 г.

Drupal with Android integration: make posts and upload photos. Part I - Drupal.


Drupal is powerful and popular web CMS, with many useful features and hundreds of different modules that can extend core functionality. Android is powerful, popular and very fast growing mobile platform. It's leading smartphone and tablets platform. In this article i'll show you how to integrate Drupal with Android powered mobile devices, to authorize on site and to perform some actions. 

If you are interested in development mobile applications, that can backup or store files to a website, upload photos, make posts, administer site, or perform other remote actions - this article is for you. Here you can find guidelines and principles description of how mobile and web integration can be made. 

Example in this article will be a practical task: post pages and upload photos from Android device to Drupal website. In example, i show how to use it with Drupal 6, but all is also applicable to Drupal 7 (only minor modifications of Drupal module are required). This article show how to integrate Drupal with Android OS. If you need another platform, it can be useful for you too, as it describes principles and issues of communication. 

How it will be done?

Our task is to perform actions on Drupal website, and we need a method to communicate with it.
We will use XML-RPC protocol for communication between Android and Drupal. It's lightweight remote procedure call protocol, and you don't need any additional knowledge, as with SOAP. Also, it's not require  interface definitions, as with SOAP.

To use it, we need services module (http://drupal.org/project/services).

1. Services module

This module allows to create services within Drupal modules. A service exposes a set of methods, that can be called remotely by third party applications. Each method has defined name, parameters and return type. In our case they will be called from Android-powered mobile device.


Services module supports many communication protocols. REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF are supported. 


In this example we will use XMLRPC.

2. Configuring services module

Services module is not included in Drupal core. So, you need to download it from http://drupal.org/project/services. Unpack it into your Drupal website modules subdirectory (sites/all/modules), and enable it in modules administration page.

If all is fine, you will see it in modules admin page.




Next, you need to define the service endpoint. Open the services admin page of your site, and add "android" endpoint:



Then click "Add" link:


And then, enter endpoint's parameters:  machine-readable name, server type and endpoint path. 
Session authentication must be checked. If it's unchecked, all rpc calls will be executed as anonymous user.
Example is shown below:


Next, open resources tab. And select resouces, that will be available through this endpoint.
Resources are nodes, comments, files, users, etc. You need to enable user login and logout, and node create and delete. You can enable more resouces. For example: to allow users registration from mobile, to add/remove comments and etc. But, it's good practice to allow only that's really needed. (For example, if you use captcha for users registration to block bots, enabling user.register method through services will allow them to avoid captcha).

Now, services module is configured.

3. Drupal module

The purpose of our module is to get uploads from Android devices and attach them to pages. 
We call our module "photoupload". Create subdirectory photoupload in sites/all/modules directory of Drupal. Now we create photoupload.infoSet up mandatory fields:


name = Photo upload
description = Module that manages photo uploads from Android devices

core = 6.x
version = "6.x-1.0"
project = "photoupload"

Now, create module file photoupload.module

Begin with php opening tag.
 <?php 
First, our module will define "upload photos" permission. Only users with this permission are allowed to upload photos.


function photoupload_perm() 
{
 return array('upload photos');
}


Next, we need to define menu item for uploads. Call it "photoupload". Menu item is needed to handle urls, so it will be hidden (callback). Upload is made through form, so define page callback to be drupal_get_form, page arguments as array containing name of function to create form. Access arguments is array containing permission, required for access to menu item. In this case, it will an array with "upload photos" element.


function photoupload_menu() 

{
 $items = array();

 // mobile photo upload
 $items['photoupload'] = array(
  'title' => 'Mobile photo upload',
  'description' => 'Upload photo',
  // setup page callback to return form
  'page callback' => 'drupal_get_form',
  // form function
  'page arguments' => array('photoupload_upload_file'),
  // users with 'upload photos' permission is only allowed
  'access arguments' => array('upload photos'),
  // hide it from menus, available to users
  'type' => MENU_CALLBACK, 
 );
 return $items;
}


Now, we create form for upload. It will contain image file and page node identifier elements.

function photoupload_upload_file($form_state)

{
 // prepare the file upload form
 // set multipart/form-data encoding type
 $form = array('#attributes' => array('enctype' => 'multipart/form-data'));

 // image file selector
 $form['image'] = array(
     '#type' => 'file',
     '#title' => 'Upload photo',
     '#description' => t('Pick a image file to upload')
 );

 // page node identifier. The page to image be attached
 $form['nid'] = array(
  '#type' => 'textfield',
  '#title' => 'Page nid',
 );

 $form['#token'] = FALSE;
 
 // submit button
 $form['submit'] = array('#type' => 'submit', '#value' => 'Upload');
 return $form;
}


Create form submission handler.

function photoupload_upload_file_submit($form, &$form_state)
{
 $dir = file_directory_path();
 
 // unlike form submissions, multipart form submissions are not in
 // $form_state, but rather in $FILES, which requires more checking
 //

 if (!isset($_FILES) || empty($_FILES) || $_FILES['files']['size']['image'] == 0) {
      drupal_set_message("Your file doesn't appear to be here.");
  return ;
 }

 $name = $_FILES['files']['name']['image'];
 $size = $_FILES['files']['size']['image'];
 $type = $_FILES['files']['type']['image'];

 // get page nid
 $nid = $form_state['values']['nid'];

 // this is the actual place where we store the file
 $file = file_save_upload('image', array() , $dir);
 if ($file) {
  $filename = $dir."/".$file->filename;

  $import = _photoupload_attach_photo($filename, $nid);
  drupal_set_message($import); 
 }
 else {
     drupal_set_message("Something went wrong saving your file.");
 }
}


Add function to attach photo to page.

function _photoupload_attach_photo($file, $nid)
{
 global $user;

 // load node by nid
 $node = node_load($nid);

 // create file object
 $name = basename($file);

 $file_obj = new stdClass();
 $file_obj->filename = $name;
 $file_obj->filepath = $file;
 $file_obj->filemime = file_get_mimetype($name);
 $file_obj->filesize = $stats['size'];
 $file_obj->filesource = $file;
 $file_obj->status = FILE_STATUS_TEMPORARY;
 $file_obj->timestamp = time();
 $file_obj->list = 1;
 $file_obj->new = true;

 // write it
 drupal_write_record('files', $file_obj);

 file_set_status($file_obj, 1);
 // attach file to node

 $node->files[$file_obj->fid] = $file_obj;

 // and finally, save node
 node_save($node);
 return "OK";
}


And php closing tag.

?>

We finished with Drupal's module code.

Now, you need enable it in modules administration page.











It's all done with Drupal part. In the next part of article i'll describe how to implement Android application.
Drupal with Android integration: make posts and upload photos. Part II - Android.

46 комментариев:

  1. Этот комментарий был удален администратором блога.

    ОтветитьУдалить
  2. your blogs is awesome.
    Astrology
    WANT TO KNOW WHAT THE FUTURE HAS IN STORE FOR YOU ? VIDEOCON ASTROLOGY SERVICES CAN TELL YOU NOW ! · Talk to an expert astrologer , Dial 55315 at Rs 9/min · To subscribe to an astrology subscription pack , dial 5553150 at RS 30/30 days · For unlimited astrology pack , Dial 553155 at RS 5/day

    ОтветитьУдалить
  3. Drupal has become synonymous with increasingly usable and dynamic websites. Offering the users a greater flexibility to modify, share and distribute content.

    ОтветитьУдалить
  4. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    rpa Training in tambaram

    blueprism Training in tambaram

    automation anywhere training in tambaram

    iot Training in tambaram

    rpa training in sholinganallur

    blue prism training in sholinganallur

    automation anywhere training in sholinganallur

    iot training in sholinganallur

    ОтветитьУдалить
  5. From your discussion I have understood that which will be better for me and which is easy to use. Really, I have liked your brilliant discussion. I will comThis is great helping material for every one visitor. You have done a great responsible person. i want to say thanks owner of this blog.

    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data Science training in kalyan nagar
    Data Science training in OMR
    selenium training in chennai

    ОтветитьУдалить
  6. This is very good content you share on this blog. it's very informative and provide me future related information.
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ОтветитьУдалить
  7. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
    python online training
    python training in OMR
    python training in tambaram

    ОтветитьУдалить
  8. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.

    Devops training in sholinganallur

    ОтветитьУдалить
  9. This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring this topic to discussion.
    Blueprism training in tambaram

    Blueprism training in annanagar

    Blueprism training in velachery

    ОтветитьУдалить
  10. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ОтветитьУдалить
  11. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ОтветитьУдалить
  12. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page!data science course in dubai

    ОтветитьУдалить
  13. Great post about Android uploading information, Excellent Blog! Thanks for sharing.

    ExcelR Data Science Bangalore

    ОтветитьУдалить
  14. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    date analytics certification training courses
    data science courses training
    data analytics certification courses in Bangalore

    ОтветитьУдалить
  15. Actually I read it yesterday but I had some thoughts about it and today I wanted to read it again because it is very well written.

    Data Science Course

    ОтветитьУдалить
  16. Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks
    Data Science Course in Pune

    ОтветитьУдалить
  17. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    top 7 best washing machine

    ОтветитьУдалить
  18. Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
    www.technewworld.in
    How to Start A blog 2019
    Eid AL ADHA

    ОтветитьУдалить
  19. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    Data Science Courses

    ОтветитьУдалить
  20. tax return online

    Central Office Support is a company that was founded with 4 pillars of office work in mind. These are Accounting, Taxation, Financing, and Consulting. We believe that all of these fields are easily outsourced and that’s where we come in. Our team of professionals have years of experience in this field and are capable of helping out any company, be it the smallest or the largest.

    ОтветитьУдалить
  21. You will get an introduction to the Python programming language and understand the importance of it. How to download and work with Python along with all the basics of Anaconda will be taught. You will also get a clear idea of downloading the various Python libraries and how to use them.
    Topics
    About Excelr Solutions and Innodatatics
    Introduction to Python
    Installation of Anaconda Python
    Difference between Python2 and Python3
    Python Environment
    Operators
    Identifiers
    Exception Handling (Error Handling)

    [url=https://www.excelr.com/data-science-certification-course-training-in-singapore]Excelr Solutions[/url]

    ОтветитьУдалить
  22. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
    pmp certification malaysia

    ОтветитьУдалить
  23. PhenQ_Reviews 2019 – WHAT IS PhenQ ?


    How_to_use_PhenQ ?This is a powerful slimming formula made by combining the multiple weight loss
    benefits of variousPhenQ_ingredients. All these are conveniently contained in
    one pill. It helps you get the kind of body that you need. The ingredients of
    the pill are from natural sources so you don’t have to worry much about the side
    effects that come with other types of dieting pills.Is_PhenQ_safe ? yes this is completly safe.
    Where_to_buy_PhenQ ? you can order online.PhenQ Scam ? this medicine is not scam at all.


    Watch this PhenQ_Reviews to know more.
    Know about PhenQ Scam from here.
    know Is_PhenQ_safe for health.
    you don`t know How_to_use_PhenQ check this site

    wanna buy phenq check this site and know Where_to_buy_PhenQ and how to use.

    check the PhenQ_ingredients to know more.

    what is PhenQ check this site.

    ОтветитьУдалить
  24. its fashion mania item site with free SHIPPING all over the world.
    free SHIPPING women clothing, cosmetics bags sun glasses & health n beauty

    ОтветитьУдалить
  25. As many of the people are talking about the consumption and usage of weed is safe for health or not. Many of them have the opinion that using weed within a safe limit is not injurious to health.
    Get Weed online in USA/Canada

    ОтветитьУдалить
  26. Car Maintenance Tips That You Must Follow


    For everyone who owns it, Car Maintenance Tips need to know.
    Where the vehicle is currently needed by everyone in the world to
    facilitate work or to be stylish.
    You certainly want the vehicle you have always been in maximum
    performance. It would be very annoying if your vehicle isn’t even
    comfortable when driving.
    Therefore to avoid this you need to know Vehicle Maintenance Tips or Car Tips
    Buy New Car visit this site to know more.

    wanna Buy New Car visit this site.
    you dont know about Car Maintenance see in this site.
    wanna know about Car Tips click here.
    know more about Hot car news in here.

    ОтветитьУдалить
  27. Subsequent to the completion of our Data Science Training
    program, assignments, projects and placement assistance will kick start.
    Help will be rendered in terms of resume building, FAQs for the interviews, one-to-one discussion on job description during interview calls, etc.
    A couple of mock interviews (one on one / telephonic) will be conducted by the SME's to evaluate the grey areas and areas of strength.
    This helps the participant to retrospect and understand their interview readiness. Participants can attend and successfully crack the interviews with complete confidence.
    ExcelR offers the best Data Science training and the reviews from our past participant's vouch for our statement.



    Data Science Training

    ОтветитьУдалить
  28. Sehar News is a wide area that envelops pakistan news , kashmir news , International News, Sports News, Arts and
    Entertainment News, Science and Technology, Business News, latest news in urdu , Education News and today news Columns.
    The perusers can snatch most recent urdu news dependent on different political and get-together
    occurring in the nation. Sehar News covers the most recent and up and coming news features, Read today urdu news and top stories from different backgrounds and carries it to the viewers



    wanna know latest pakistan news ? click pakistan news and know more.

    Read latest news in urdu and know more .

    read all the latest urdu news in this site.

    you dont know ? about today news click here and know more.

    know the current news of kashmir news check here.

    read all about today urdu news and gain knowledge.

    ОтветитьУдалить
  29. LogoSkill,
    Logo Design Company
    is specifically a place where plain ideas converted into astonishing and amazing designs. You buy a logo design, we feel proud in envisioning
    our client’s vision to represent their business in the logo design, and this makes us unique among all. Based in USA we are the best logo design, website design and stationary
    design company along with the flayer for digital marketing expertise in social media, PPC, design consultancy for SMEs, Start-ups, and for individuals like youtubers, bloggers
    and influencers. We are the logo design company, developers, marketers and business consultants having enrich years of experience in their fields. With our award winning
    customer support we assure that, you are in the hands of expert designers and developers who carry the soul of an artist who deliver only the best.

    Logo Design Company

    ОтветитьУдалить
  30. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
    machine learning course malaysia

    ОтветитьУдалить
  31. Established in 2016 SSDWebHosting.net is providing top quality domain and hosting services worldwide to
    our valued customers and trying to play a little role in their success.We offer about 500 distinctive gTlds and ccTlds
    to look over which includes old master class gTlds like .com, .net and .org, in addition this we also offer newly launched Tlds
    like .xyz, .online, .master, .office, .on, .top and .club. We can assist you with choosing the best fitting name. Let's bring your
    thought or business on the web. visit this site https://SSDWebHosting.net/ to know more.


    Do you wanna buy SSD Web Hosting visit here.
    Find best Cheap Web Hosting here.

    ОтветитьУдалить
  32. punaise des lits sont l'un des problèmes les plus difficiles à éliminer rapidement.
    La meilleure solution, de loin, pour lutter contre punaise des lits est d'engager une société de lutte antiparasitaire.
    ayant de l'expérience dans la lutte contre punaise des lits . Malheureusement, cela peut être coûteux et coûteux.
    au-delà des moyens de beaucoup de gens. Si vous pensez que vous n'avez pas les moyens d'engager un professionnel
    et que vous voulez essayer de contrôler traitement des punaises de lit vous-même, il y a des choses que vous pouvez faire. Avec diligence
    et de patience et un peu de travail, vous avez une chance de vous débarrasser de punaises de lit paris dans votre maison.


    Vous voulez supprimer punaise des lits de votre maison ?
    se débarrasser de punaises de lit paris cocher ici
    nous faisons traitement des punaises de lit de façon très professionnelle.

    ОтветитьУдалить
  33. LogoSkill, Professional Logo Design Company Company is specifically a place where plain ideas converted into astonishing and amazing designs. You buy a logo design, we feel proud in envisioning
    our client’s vision to represent their business in the logo design, and this makes us unique among all. Based in USA we are the best logo design, website design and stationary
    design company along with the flayer for digital marketing expertise in social media, PPC, design consultancy for SMEs, Start-ups, and for individuals like youtubers, bloggers
    and influencers. We are the logo design company, developers, marketers and business consultants having enrich years of experience in their fields. With our award winning
    customer support we assure that, you are in the hands of expert designers and developers who carry the soul of an artist who deliver only the best.

    Professional Logo Design Company

    ОтветитьУдалить
  34. In our culture, the practice of treatment through various burn fat herbs and
    spices is widely prevalent. This is mainly due to the reason that different burn fat herbs grow in great abundance here. In addition to the
    treatment of various ailments these herbs prove beneficial in Healthy Ways To Lose Weight
    , especially for those who want to burn fat herbs

    we live in a world where diseases and their prevalence has gone off
    the charts. With the ever-growing incidences of illnesses and
    sufferings, one finds themselves caught up in a loop of medications
    and doctors’ visits. We, at https://goodbyedoctor.com/ , aim to find solutions for
    all your health-related problems in the most natural and harmless ways.
    We’re a website dedicated to providing you with the best of home
    remedies, organic solutions, and show you a path towards a healthy,
    happy life. visit https://goodbyedoctor.com/
    this site daily to know more about health tips and beauty tips.

    ОтветитьУдалить