#include <stdio.h>
#include <string.h>
#include <sys/stat.h>		/* for stat() */
#include <unistd.h>		/* for unlink() */

#include "global.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"
#include "manhat-lib/shared_super_util.h"
#include "manhat-lib/shared_strtrm.h"
#include "manhat-lib/shared_file_util.h"
#include "manhat-lib/shared_bio.h"
#include "manhat-lib/shared_msg_line.h"

/** Course is an optional parameter.  If course is sent,
*** the the user is working within a Manhattan course.
*** Otherwise, they are working from the My Manhattan page.
***/

static void
read_parameters (char *course, char *key, char *username, int *is_admin)
{
  char tmp[10 + 1];


  cs_get_required_parameter ("id", key, MAX_KEY);
  cs_get_required_parameter ("user", username, MAX_USERNAME);


  cs_get_optional_parameter ("crs", course, MAX_PATH);

  cs_get_optional_parameter ("admin", tmp, 10);
  if(strlen(tmp))
    *is_admin = 1;
  else
     *is_admin =0; 
}






 
 
static 
void set_photo_data(const char *bio_dir, const char *target_username, const char *course, const char *key, GROUP_TYPE group)
{
  char url[MAX_PATH];

 if(group == ADMIN)
 {
   snprintf(url, MAX_PATH, "%s?id=%s&amp;crs=%s&amp;user=%s&amp;admin=1&amp;random=%d",
        "bio_send_photo",
        key,
        course,
        target_username,
        getpid());
   cs_set_value("photo_url", url);
 }  
 else
 {
   snprintf(url, MAX_PATH , "%s?id=%s&amp;crs=%s&amp;user=%s&amp;random=%d",
        "bio_send_photo",
        key,
        course,
        target_username,
        getpid());
   cs_set_value("photo_url", url);
 }
        
}

  
        
        


static 
void set_label_content_data(FILE *fp, const char *bio_dir,  char *target_username, 
							 char *target_realname,  char *course,  char *key, GROUP_TYPE group)
{
 #define MAX_TMP_NAME 30

 char email[200 + 1];
 char website[200 + 1];
 char custom_label[BIO_MAX_CUSTOM_LABEL + 10];
 char custom_content[BIO_MAX_CUSTOM_CONTENT + 10];
 char *new_label = 0;
 char *new_content= 0; 
 int i;
 char name[MAX_TMP_NAME];
 
 *email = '\0';
 *website = '\0';
 
 if(fp)
  {
   if(fgets(email,200,fp))   /* try to get email address from first line */
    {
      strtrm(email);
      if(fgets(website,200,fp))   /* try to read website from second line */
           strtrm(website);
    }
  }       
  
 cs_set_value("target_realname", target_realname); 
 
 /* set the email address **/  
 if(strlen(email))
    cs_set_value("email", email);

/* set the website */
 if(strlen(website))
    cs_set_value("website", website);
  
 if(fp)
  {
   for(i=0; i < BIO_MAX_CUSTOM_ELEMENTS; i++)
    {
     *custom_label = '\0';
     *custom_content = '\0';
     if(fgets(custom_label,BIO_MAX_CUSTOM_LABEL + 10,fp))  
      {
        strtrm(custom_label);
        cgi_html_escape_strfunc(custom_label,&new_label);   /* store html escaped version in newly allocated new_label 
                                                            ** part of ClearSilver library
                                                            */

        if(fgets(custom_content,BIO_MAX_CUSTOM_CONTENT + 10,fp))  
         {
           strtrm(custom_content);
           cgi_html_escape_strfunc(custom_content,&new_content);  /* store html escaped version in newly allocated new_content */
         }  
      }
      
     if(new_label && strlen(new_label))
      {
	snprintf(name, MAX_TMP_NAME, "custom.%d.label", i);
	cs_set_value(name, new_label);
      }	
       
      if(new_content && strlen(new_content))
       {
         snprintf(name, MAX_TMP_NAME, "custom.%d.content", i);
         cs_set_value(name, new_content);
       }  
      }

    if(new_label) 
      {
        free(new_label);
        new_label = 0;
      }  
    if(new_content)
      {
       free(new_content);
       new_content = 0;
      } 
      
  }
 
 set_photo_data (bio_dir, target_username, course, key, group);     
 
#undef MAX_TMP_NAME 
} 




static
FILE *open_bio(const char *bio_dir)
{

 char bio_path[MAX_PATH + 1];
 FILE *fp;
 
 snprintf(bio_path, MAX_PATH + 1, "%s/%s", bio_dir, BIO_FNAME);
 fp = fopen(bio_path,"r");
 return fp;
}



static
void set_bio_text(FILE *fp)
{
#define MAX_TMP_NAME 30
 char buffer[200];
 char *formatted_line;
 char *ptr;
 int initial_cap_printed = 0;
 char name[MAX_TMP_NAME];
 char temp[MAX_TMP_NAME];
 int i =0;
 
  if(fp)
   {
      while (fgets (buffer, 200, fp))
      {
          strtrm(buffer);   /*shared_strtrm.c */
          if(!*buffer)
              initial_cap_printed = 0;
          else
          {  
	      alloc_formatted_line(buffer, 1, 1, &formatted_line);   /* shared_msg_line.c */
              if(formatted_line)
	      {
                if(!initial_cap_printed)
	          {
                      ptr = strstr(formatted_line,"http://");
                      if(!ptr || ((ptr != formatted_line) && *formatted_line != '<') )
	               {
	                 snprintf(name, MAX_TMP_NAME, "line.%d.cap", i);
			 snprintf(temp, 3, "%c", *formatted_line);
	                 cs_set_value(name, temp); 
                         initial_cap_printed = 1;
			 ptr = formatted_line;
			 ptr++;
	                 snprintf(name, MAX_TMP_NAME, "line.%d.content", i);
	                 cs_set_value(name, ptr); 

	              }
	             else
	              {
	                snprintf(name, MAX_TMP_NAME, "line.%d.content", i);
	                cs_set_value(name, formatted_line); 
	              }
	         }
	       else
	         {
	            snprintf(name, MAX_TMP_NAME, "line.%d.content", i);
	            cs_set_value(name, formatted_line); 
	         }
	       free(formatted_line);
	    }
         }
         i++;
       }
     } 
#undef MAX_TMP_NAME 

}



static
void set_edit_button_data( char *course,  char *key, GROUP_TYPE group,  char *target_username)
{

   cs_set_value("id", key);
   cs_set_value("user", target_username);
   if(*course)
       cs_set_value("crs",course);
   if(group == ADMIN)
      cs_set_value("admin", "1");
    cs_set_int_value("edit_button", 1);   
}





static void
set_bio_values ( char *course,   /* this could be and empty string */
               char *key, 
               SESSION *user,         /* person running this program */
               CONFIG_STRUCT *conf,   /* contains junk if course is an empty string */
               char *target_username)   /* username whose profile we're displaying */
{

 char target_realname[MAX_NAME + 1];
 char bio_dir[MAX_PATH + 1];
 FILE *fp;

 
  /** The full (real) name of the person is not stored in the profile. **/
  get_bio_realname(course, conf, target_username, target_realname);   /* shared_bio.c */
       
  /* bio info is either stored in ../users/x/username/bio or, for standalone courses in
  ** course_dir/people/username/bio
  */     
  get_bio_dir(course, conf, target_username, bio_dir);       /* shared_bio.c */
  

  
  if(!bio_exists(bio_dir))   /* shared_bio.c */
     {
      cs_set_value("realname", target_realname);
      cs_set_int_value("no_bio", 1);
     } 
  else
   {     
     fp = open_bio(bio_dir);
     set_label_content_data(fp,bio_dir, target_username, target_realname, course,key, user->group);
     set_bio_text(fp);
     if(fp)
         fclose(fp);
    }

 if(bio_edit_allowed(user, target_username, course, conf))    /* shared_bio.c */
   {
     set_edit_button_data(course, key, user->group, target_username);
   }
     
}        
    
     
         

int
main ()
{
  char course[MAX_PATH + 1];	            /* from crs=? command line */
  char key[MAX_KEY + 1];	            /* from id=? command line */
  char target_username[MAX_USERNAME + 1];   /* from user=? command line */
  int is_admin;                             /* from admin=? command line */
  SESSION user;
  CONFIG_STRUCT conf;		            /* the configuration read from config file */

  cs_cgi_init();
  read_parameters (course, key, target_username,&is_admin);
  
  /** This program can be run by:
  ***   A teacher or student from their "My Manhattan Page":
  ***       - The 'course' string should be empty
  ***       - call validate_server_key()
  ***       - we know it's not a standalone course
  ***       - later, we'll check to make sure their username matches the target_username
  ***           since, users should only be allowed to see their own profile.
  ***
  ***   A teacher or student from within a particular Manhattan classroom's People module
  ***       - The course is contained within the 'course' string
  ***       - We read the course's config file to determine whether or not the course is a standalone course
  ***       - call validate_key()
  ***       - both this user and the target_username must be members of this course
  ***           (so people can't randomly view profiles of people in other courses)
  ***
  ***   An admin running the program from the administrative interface, or from within the Config menu of
  ***   a course:
  ***         - An admin=1 parameter is passed via the CGI, and sets is_admin to true
  ***         - there may or may not be a non-empty course string.  It can be empty if the admin is accessing
  ***             the program from View/Modify users.  It will be non-empty if the admin is accessing the
  ***             program from within a course's Config menu
  ***         - we validate_super_key()
  **/


  /* If a course was provided on the command line, read its configuration file.
  ** Set whether or not we're dealing with a standalone course
  **/

  if(*course)
     read_configuration_file(course, &conf);
     

 /* validate the appropriate key */
  if(is_admin)
    validate_super_key(key, &user);     /* shared_super_util.c */
  else if(!*course)
    validate_server_key(key, &user);       /* shared_util.c */
  else
    validate_key (key, &user, &conf);	/* shared_util.c */

  if(!bio_view_allowed(&user,target_username, course, &conf))  /* shared_bio.c */
      cs_critical_error (ERR_REQUEST_DENIED, "");
  

  set_bio_values (course, key, &user, &conf,  target_username);
  cs_cgi_display("bio_view", 1);
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}

