From bd19ece4e6698362e5adde0da89f0e97fac9b479 Mon Sep 17 00:00:00 2001
From: Steve McKenzie <steve@stevemckenzie.ca>
Date: Mon, 28 Feb 2011 17:57:01 -0800
Subject: [PATCH] First crack at issue #1076802.

---
 drippic.api.inc |   66 +++++++++-------
 drippic.info    |    9 ++-
 drippic.install |   16 +----
 drippic.module  |  243 ++++++++++++++++++++++++++++++++++++++++++-------------
 4 files changed, 235 insertions(+), 99 deletions(-)

diff --git a/drippic.api.inc b/drippic.api.inc
index b2a5536..df00a8c 100644
--- a/drippic.api.inc
+++ b/drippic.api.inc
@@ -29,7 +29,7 @@
  * @return
  *   response of successful or failed upload.
  */
-function drippic_two_upload($function = null, $format = 'xml'){
+function drippic_two_upload($function = null, $format = 'xml') {
   // Verify user using oauth echo http://dev.twitter.com/pages/oauth_echo
   // Currently uses CURL although could/should be replaced by drupal_http_request
   $sp = $_SERVER['HTTP_X_AUTH_SERVICE_PROVIDER'];
@@ -46,11 +46,11 @@ function drippic_two_upload($function = null, $format = 'xml'){
   curl_setopt($curl, CURLOPT_FAILONERROR, false);
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
 
-  // Set our OAuth Echo headers
+  // Set our OAuth Echo headers.
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
-          'Authorization: ' . $vc_auth,
-          'X-Auth-Service-Provider: ' . $sp
-          ));
+    'Authorization: ' . $vc_auth,
+    'X-Auth-Service-Provider: ' . $sp
+  ));
 
   $response = curl_exec($curl);
   if (!$response) {
@@ -60,11 +60,11 @@ function drippic_two_upload($function = null, $format = 'xml'){
   $response_obj = json_decode($response);
   watchdog('drippic','Twitter response: </pre>'.print_r($response_obj,true).'</pre>');
   
-  if(isset($response_obj->error)){
+  // Handle twitter response.
+  if (isset($response_obj->error)) {
     header('HTTP/1.1 401 Unauthorized');
     return 'Twitter error: ' . $response_obj->error;
-  }
-  else{
+  } else {
   	$twitter_user = $response_obj;
   }
   
@@ -178,7 +178,7 @@ function drippic_two_upload($function = null, $format = 'xml'){
 			);
 		}
 	}
-	else{
+	else {
 	  // return an error if $twitter_user->screen_name and $media were not set
 		$response['attributes'] = array(
 			'stat' => 'fail',
@@ -189,20 +189,24 @@ function drippic_two_upload($function = null, $format = 'xml'){
 	}
 	$output .= format_xml_elements(array($response));
 	
-	// return as xml or json
-	if($format == 'xml'){
+  // XML return.
+	if ($format == 'xml') {
 	  header ("Content-Type:text/xml");  
 	  print $output;
   }
-  elseif($format =='json'){
+  
+  // JSON return.
+  elseif ($format =='json') {
     header('Content-type: application/json');
     $json = array();
     $json['url'] = $response['value']['mediaurl'];
     print json_encode($json);
   }
- 
+  
+  // TODO: SUPPORT DEFAULT.
 }
 
+
 /**
  * Page callback for drippic/show/%/%
  *
@@ -213,24 +217,29 @@ function drippic_two_upload($function = null, $format = 'xml'){
  *   the shorturl code for an image.
  *
  */
-function drippic_show($size,$code){
+function drippic_show($size,$code) {
   $indx = shorturl_decode_url($code);
   $orig_url = db_result(db_query('SELECT orig_url FROM {shorturl_link} WHERE lid=%d ', $indx));
 
-    $re1='.*?';	# Non-greedy match on filler
-    $re2='(\\d+)';	# Integer Number 1
-
-    if ($c=preg_match_all ("/".$re1.$re2."/is", $orig_url, $matches))
-    {
-        $int1=$matches[1][0];
-    }
+  $re1='.*?';	# Non-greedy match on filler
+  $re2='(\\d+)';	# Integer Number 1
 
+  if ($c = preg_match_all("/".$re1.$re2."/is", $orig_url, $matches)) {
+    $int1=$matches[1][0];
+  }
 
   $node = node_load($int1);
-  $image = imagecache_create_url($size, $node->field_pic[0]['filepath']);
-  drupal_goto($image);
+  $field_name = variable_get('drippic_imagefield', '');
+  
+  if ($field_name != nil) {
+    $image = imagecache_create_url($size, $node->{$field_name}[0]['filepath']);
+    drupal_goto($image);
+  }
+  
+  // TODO: SHOULD HANDLE ERROR WHEN NOT CONFIGURED PROPERLY.
 }
 
+
 /**
  * Page callback for photos/%/%
  *
@@ -245,17 +254,18 @@ function drippic_show($size,$code){
  *   list of user's nodes in json.
  *
  */
-function drippic_user_photos($username,$format){
-  
-  $account = user_load(array('name'=>$username));
+function drippic_user_photos($username, $format) {
+  $account = user_load(array('name'=> $username));
   $nodes = array();
-  $query = db_query('SELECT nid FROM {node} WHERE uid = %d',$account->uid);
+  $query = db_query('SELECT nid FROM {node} WHERE uid = %d', $account->uid);
   while ($node = db_fetch_object($query)) {
     $nodes[] = node_load($node->nid);
   }
   
-  if($format == 'json'){
+  if ($format == 'json') {
     header("Content-type: application/json; charset=utf-8");
     print json_encode($nodes);
   }
+  
+  // TODO: EXIT?
 }
diff --git a/drippic.info b/drippic.info
index 78fc710..76867f4 100644
--- a/drippic.info
+++ b/drippic.info
@@ -1,10 +1,17 @@
+; $Id: drippic.info,v 1.2 2010/11/06 21:33:52 timmillwood Exp $
 name = "Drippic"
 description = "A Drupal clone of Twitpic."
 core = 6.x
 dependencies[] = content
-dependencies[] = content_copy
 dependencies[] = filefield
 dependencies[] = imagefield
 dependencies[] = twitter
 dependencies[] = twitter_signin
 dependencies[] = oauth
+
+; Information added by drupal.org packaging script on 2010-11-18
+version = "6.x-1.x-dev"
+core = "6.x"
+project = "drippic"
+datestamp = "1290038987"
+
diff --git a/drippic.install b/drippic.install
index 9e2378e..054df29 100644
--- a/drippic.install
+++ b/drippic.install
@@ -4,20 +4,6 @@
  * Impementation of hook_install()
  */
 function drippic_install() {
-  drippic_create_content_type(drupal_get_path('module', 'drippic').'/drippic.cck.inc');
+  
 }
 
-/*
- * Helper function to import a content type
- */
-function drippic_create_content_type($cck_definition_file) {
-  include_once('./'. drupal_get_path('module', 'node') .'/content_types.inc');
-  include_once('./'. drupal_get_path('module', 'content') .'/includes/content.admin.inc');
-  $values = array();
-  $values['type_name'] = '<create>';
-  $values['macro'] = file_get_contents($cck_definition_file);
-  $form_state = array();
-  $form_state['values'] = $values;
-  drupal_execute("content_copy_import_form", $form_state);
-}
-?>
diff --git a/drippic.module b/drippic.module
index f2e4a2a..2068ddd 100644
--- a/drippic.module
+++ b/drippic.module
@@ -1,4 +1,5 @@
 <?php
+// $Id: drippic.module,v 1.5 2010/11/17 17:56:17 timmillwood Exp $
 
 /**
  * @file
@@ -7,11 +8,19 @@
  * This is the main module for the app containing all the main hooks and functions.
  */
 
+
 /**
- * Implementation if hook_init()
- *
+ *  Implementation of hook_perm().
+ */
+function drippic_perm() {
+  return array('administer drippic');
+}
+
+
+/**
+ * Implementation if hook_init().
  */
-function drippic_init(){
+function drippic_init() {
   // Adding Twitter hovercards using Twitter Anywhere.
 	drupal_set_html_head('<script src="http://platform.twitter.com/anywhere.js?id=N8c1DnM9nnJr22ZIEq6g&v=1" type="text/javascript"></script>');
 	$js = "twttr.anywhere(function(twitter) {";
@@ -25,14 +34,21 @@ function drippic_init(){
   drupal_add_js(drupal_get_path('module', 'drippic') .'/drippic.js');
 }
 
+
 /*
- * Implementiation of hook_menu()
- *
+ * Implementiation of hook_menu().
  */
-function drippic_menu(){	
+function drippic_menu() {	
   $items = array();
   
-  $items['drippic2/upload'] = array(
+  $items['admin/content/drippic'] = array(
+    'title' => 'Drippic',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('drippic_settings_form'),
+    'access arguments' => array('administer drippic'),
+  );
+  
+  $items['drippic/upload'] = array(
     'title' => 'Upload',
     'page callback' => 'drippic_two_upload',
     'access arguments' => array('access content'),
@@ -61,6 +77,46 @@ function drippic_menu(){
   return $items;
 }
 
+
+/*
+ * Implementation of hook_form_alter().
+ */
+function drippic_form_alter(&$form, &$form_state, $form_id) {
+	if ($form_id == 'comment_form') {
+    // Add a custom submit handler to the comments form.
+	  $form['#submit'][] = 'drippic_comment_form_submit';
+	}
+	
+	// Removes twitter.module submit handler and adds drippic submit handler.
+  // TODO: WHY?
+  if (_twitter_use_oauth() && $form_id == 'twitter_oauth_callback' && $_SESSION['twitter_oauth']['signin']) {
+    if ($form['#submit'][0] == 'twitter_signin_oauth_callback_submit') {
+      unset($form['#submit'][0]);
+    }
+    $form['#submit'] = array_merge(array('drippic_signin_oauth_callback_submit'), $form['#submit']);
+  }
+}
+
+
+/*
+ * Helper function to import a content type.
+ */
+function _drippic_create_sample_content_type() {
+  include_once('./'. drupal_get_path('module', 'node') .'/content_types.inc');
+  include_once('./'. drupal_get_path('module', 'content') .'/includes/content.admin.inc');
+  
+  $values = array();
+  $values['type_name'] = '<create>';
+  $values['macro'] = file_get_contents(drupal_get_path('module', 'drippic').'/drippic.cck.inc');
+  $form_state = array();
+  $form_state['values'] = $values;
+  
+  drupal_execute("content_copy_import_form", $form_state);
+  variable_set('drippic_content_type', 'pic');
+  variable_set('drippic_imagefield', 'field_pic');
+}
+
+
 /**
  * Custom Drippic function to create nodes.
  *
@@ -79,35 +135,41 @@ function drippic_menu(){
  */
 function drippic_create_node($tweet, $media, $account = null) {
   // make sure that the user object is pulled in
-  if(!isset($account)){
+  if (!isset($account)) {
 	  global $user;
 	  $account = $user;
   }
+  
   // Had an odd bug with images being posted as anonymous, here's a quick / hacky fix.
-  if($account->status == 0){
+  if ($account->status == 0) {
     return FALSE;
   }
-  watchdog('drippic','account: </pre>'.print_r($account,true).'</pre>');
+  
   // create the node
   $node = new stdClass;
   $node->status = 1;
-  $node->type = 'pic';
+  $node->type = variable_get('drippic_content_type', '');
+  // TODO: SHOULD HAVE VALIDATION ON CONFIGURATION.
+  
   $node->title = $tweet;
   
   // save the image
 	$target_path = file_directory_path();
 	$target_path = $target_path . '/' . basename($media['name']); 
-	if(move_uploaded_file($media['tmp_name'], $target_path)) {
+	if (move_uploaded_file($media['tmp_name'], $target_path)) {
 	    watchdog('drippic', "The file uploaded ok");
 	} else{
 	    watchdog('drippic',"There was an error uploading the file, please try again!");
 	}
 	
-	// Add the image to an imagefield
-  $file = drippic_imagefield_load('field_pic', 'pic', $target_path, $account);
-  $node->field_pic[0] = $file;
+	// Add the image to an imagefield.
+  $field_name = variable_get('drippic_imagefield', '');
+  // TODO: VALIDATION FOR CONFIGURATION.
+  
+  $file = drippic_imagefield_load($field_name, $node->type, $target_path, $account);
+  $node->{$field_name}[0] = $file;
 
-  // Save node
+  // Save the node.
   module_load_include('inc', 'node', 'node.pages');
   node_object_prepare($node);
   $node->form_id = $node->type . '_node_form';
@@ -117,13 +179,13 @@ function drippic_create_node($tweet, $media, $account = null) {
   $node->uid = $account->uid;
   $node->api_node = TRUE;
   // demote the node from the front page if the user has protected tweets 
-  if(isset($account->twitter)){
-    if($account->twitter->protected == 1){
+  if (isset($account->twitter)) {
+    if ($account->twitter->protected) {
       $node->promote = 0;
     }
   }
   node_save($node);
-  watchdog('drippic','<pre>'.print_r($node,true).'</pre>');
+  
 	return $node->nid;
 }
 
@@ -160,23 +222,6 @@ function drippic_imagefield_load($field_name, $ctype_name, $full_file_path, $acc
     }
 }
 
-/*
- * Implementation of hook_form_alter()
- */
-function drippic_form_alter(&$form, &$form_state, $form_id){
-  // Adding custom submit handler to comment forms
-	if($form_id == 'comment_form'){
-	  $form['#submit'][] = 'drippic_comment_form_submit';
-	}
-	
-	// Removes twitter.module submit handler and adds drippic submit handler.
-  if (_twitter_use_oauth() && $form_id == 'twitter_oauth_callback' && $_SESSION['twitter_oauth']['signin']) {
-    if($form['#submit'][0] == 'twitter_signin_oauth_callback_submit'){
-      unset($form['#submit'][0]);
-    }
-    $form['#submit'] = array_merge(array('drippic_signin_oauth_callback_submit'), $form['#submit']);
-  }
-}
 
 /*
  * Override of twitter_signin_oauth_callback_submit but allows existing users to login
@@ -284,12 +329,14 @@ function drippic_comment_form_submit($form, &$form_state) {
 function drippic_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
   // Tweet (via oauth) when node is inserted via node/add form.
   global $user;
-  if($op == 'insert' && !isset($node->api_node) && ($node->type == 'pic')){
+  $content_type = variable_get('drippic_content_type', '');
+  
+  if ($op == 'insert' && !isset($node->api_node) && ($node->type == $content_type)) {
 
 		$tweet = $node->title;
 		$url = drippic_shorten('node/'. $node->nid);
 		$post = $tweet . ' ' . $url;
-		while(strlen($post) > 140){
+		while (strlen($post) > 140) {
 			$tweet = substr($tweet, 0, -4);
 			$post = $tweet . '... ' . $url;
 		}
@@ -298,25 +345,108 @@ function drippic_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
 	  module_load_include('inc', 'twitter');
   	$values = db_fetch_array(db_query("SELECT twitter_uid FROM {twitter_account} WHERE uid = %d", $user->uid)); 
     $twitter_account = twitter_account_load($values[twitter_uid]);
-     try {
+    try {
      	$result = twitter_set_status($twitter_account, $post);
      	watchdog('drippic',t('Successfully posted to Twitter'));
-     	}
-     	catch (TwitterException $e) {
-     	watchdog('drippic',t('An error occurred when posting to twitter: %code %error',
-     	array('%code' => $result->code, '%error' => $result->error)), 'warning');
-     	}
+    }
+    catch (TwitterException $e) {
+      watchdog('drippic',t('An error occurred when posting to twitter: %code %error',
+      array('%code' => $result->code, '%error' => $result->error)), 'warning');
+    }
   }
   
   // Add Twitter hashtags as taxonomy terms
-  if($op == 'insert' && $node->type == 'pic'){
+  if ($op == 'insert' && $node->type == $content_type) {
     unset($node->taxonomy);
     preg_match_all('/(^|\s)#(\w+)/', $node->title, $matches);
-    $node->taxonomy['tags'][1] = implode(',',$matches[2]);
+    $node->taxonomy['tags'][1] = implode(',', $matches[2]);
     taxonomy_node_save($node, $node->taxonomy);
   }
 }
 
+
+function _drippic_sample_type_installed() {
+  return array_key_exists('pic', node_get_types('names'));
+}
+
+
+/**
+ *  Settings form.
+ */
+function drippic_settings_form() {
+  // Manually add our submit since this is a system settings form.
+  $form['#submit'][] = 'drippic_settings_form_submit';
+  
+  $form['content'] = array('#type' => 'fieldset', '#title' => 'Content settings', '#collapsible' => TRUE);
+  
+  $content_type = variable_get('drippic_content_type', '');
+  $form['content']['drippic_content_type'] = array(
+    '#type' => 'select',
+    '#title' => 'Content type',
+    '#description' => 'The content type to use when images are added through the Drippic API.',
+    '#options' => node_get_types('names'),
+    '#default_value' => $content_type,
+  );
+  
+  if ($content_type) {
+    $node_type = content_types($content_type);
+    
+    $fields = array();
+    if (!empty($node_type) && !empty($node_type['fields'])) {
+      foreach ($node_type['fields'] as $field => $item) {
+        $fields[$field] = $item['widget']['label'];
+      }
+    }
+    
+    $form['content']['drippic_imagefield'] = array(
+      '#type' => 'select',
+      '#title' => 'Image field',
+      '#description' => 'The image field to use when images are added through the Drippic API.',
+      '#options' => $fields,
+      '#default_value' => variable_get('drippic_imagefield', ''),
+    );
+  }
+  
+  $sample_type_installed = _drippic_sample_type_installed();
+  $form['content']['drippic_install_content_type'] = array(
+    '#type' => 'checkbox',
+    '#title' => 'Install a sample content type.',
+    '#description' => 'Only install this content type if you actually need it.',
+    '#default_value' => $sample_type_installed,
+    '#disabled' => $sample_type_installed,
+  );
+  
+  return system_settings_form($form);
+}
+
+
+/**
+ *  Settings form submit handler.
+ */
+function drippic_settings_form_submit($form, &$form_state) {
+  // Reset.
+  if ($form_state['clicked_button']['#id'] == 'edit-reset') {
+    
+  }
+  
+  // Save.
+  else {
+    if ($form_state['values']['drippic_install_content_type'] && !_drippic_sample_type_installed()) {
+      // Required module.
+      if (!module_exists('content_copy')) {
+        drupal_set_message(t('To install the sample content type, you need to !install the content_copy module.',
+                             array('!install' => l('install', 'admin/build/modules'))), 'error');
+      }
+      
+      // Install the sample content type.
+      else {
+        _drippic_create_sample_content_type();  
+      }
+    }
+  }
+}
+
+
 /**
  * Custom Drippic function to shorten URLs using the shorten module or TinyURL.
  *
@@ -327,14 +457,17 @@ function drippic_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  *   A short url.
  *
  */
-function drippic_shorten($url){
-		if(module_exists('shorten')){
-			$result = shorten_url(url($url, array('absolute' => TRUE)));
-		}
-		else{
-			$result = file_get_contents("http://tinyurl.com/api-create.php?url=" . url($url, array('absolute' => TRUE)));
-		}
-		return $result;
+function drippic_shorten($url) {
+  // Shorten module support.
+  if (module_exists('shorten')) {
+    $result = shorten_url(url($url, array('absolute' => TRUE)));
+  }
+  
+  // Default to tinyurl.
+  else {
+    $result = file_get_contents("http://tinyurl.com/api-create.php?url=" . url($url, array('absolute' => TRUE)));
+  }
+
+  return $result;
 }
 
-?>
-- 
1.7.0.3

