<?php

  // load viewer library
  $libraryPath = 'cmsAdmin/lib/viewer_functions.php';
  $dirsToCheck = array('','../','../../','../../../','../../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  //
  if (!$CURRENT_USER) { websiteLogin_redirectToLogin(); }

  // prepopulate form with current user values
  foreach ($CURRENT_USER as $name => $value) {
    if (array_key_exists($name, $_REQUEST)) { continue; }
    $_REQUEST[$name] = $value;
  }

  // process form
  if (@$_REQUEST['save']) {

    // error checking
    $errorsAndAlerts = "";
    if (!@$_REQUEST['firstname'])                { $errorsAndAlerts .= "You must enter your First name!<br/>\n"; }
    if (!@$_REQUEST['lastname'])                { $errorsAndAlerts .= "You must enter your Last name!<br/>\n"; }
    if (!@$_REQUEST['email'])                   { $errorsAndAlerts .= "You must enter your email!<br/>\n"; }
    else if(!isValidEmail(@$_REQUEST['email'])) { $errorsAndAlerts .= "Please enter a valid email (example: user@example.com)<br/>\n"; }
	if (!@$_REQUEST['state'])                { $errorsAndAlerts .= "You must select a state!<br/>\n"; }
	if (!@$_REQUEST['address'])                { $errorsAndAlerts .= "You must enter your address!<br/>\n"; }
	if (!@$_REQUEST['zip'])                { $errorsAndAlerts .= "You must enter your zip code!<br/>\n"; }
	if (!@$_REQUEST['phone'])                { $errorsAndAlerts .= "You must enter your phone number!<br/>\n"; }
	if (!@$_REQUEST['url'])                { $errorsAndAlerts .= "You must enter your Website URL!<br/>\n"; }
	if (!@$_REQUEST['status'])                { $errorsAndAlerts .= "You must select your status!<br/>\n"; }
	if (!@$_REQUEST['brand'])                { $errorsAndAlerts .= "You must select one or more camera brand!<br/>\n"; }
	if (!@$_REQUEST['category'])                { $errorsAndAlerts .= "You must select one or more category!<br/>\n"; }

    // new password checking
    if (@$_REQUEST['oldPassword'] || $_REQUEST['newPassword1'] || $_REQUEST['newPassword2']) {
      $oldPasswordHash = (@$SETTINGS['advanced']['encryptPasswords']) ? getPasswordDigest(@$_REQUEST['oldPassword']) : @$_REQUEST['oldPassword'];
      if (!@$_REQUEST['oldPassword'])                                 { $errorsAndAlerts .= "Please enter a value for: Current Password<br/>\n"; }
      elseif ($oldPasswordHash != $CURRENT_USER['password'])          { $errorsAndAlerts .= "Current password isn't correct!<br/>\n"; }
      elseif (!@$_REQUEST['newPassword1'])                            { $errorsAndAlerts .= "Please enter a value for: New Password<br/>\n"; }
      elseif (!@$_REQUEST['newPassword2'])                            { $errorsAndAlerts .= "Please enter a value for: Confirm New Password<br/>\n"; }
      elseif ($_REQUEST['newPassword1'] != $_REQUEST['newPassword2']) { $errorsAndAlerts .= "New passwords don't match!<br/>\n"; }
    }

    // check for duplicate usernames and emails
    if (@$_REQUEST['username'] != $CURRENT_USER['username']) {
      $count = mysql_count($GLOBALS['WSM_ACCOUNTS_TABLE'], "`username` = '".mysql_escape(@$_REQUEST['username'])."'");
      if ($count > 0 && @$_REQUEST['username']) { $errorsAndAlerts .= "That username is already in use, please choose another!<br/>\n"; }
    }
    if (@$_REQUEST['email'] != $CURRENT_USER['email']) {
      $count = mysql_count($GLOBALS['WSM_ACCOUNTS_TABLE'], "'".mysql_escape($_REQUEST['email'])."' IN (email, username)");
      if ($count > 0) { $errorsAndAlerts .= "That email is already in use, please choose another!<br/>\n"; }
    }
	
	// upload 'profile_image' if supplied 
    $uploadFieldName = 'main_image'; 
    $uploadInfo = @$_FILES[$uploadFieldName]; 
    if ($uploadInfo && !$errorsAndAlerts) { 
       
      /// attempt to save the upload 
      $errors = saveUpload('accounts', $uploadFieldName, $CURRENT_USER['num'], null, $uploadInfo, $newUploadNums); 
       
      /// check for errors 
      if ($errors) { 
        $errorsAndAlerts .= "There was a problem with your upload: $errors<br/>\n"; 
      } 
      else { 
       
        /// if the upload was successful, delete any other uploads associated with that record and field (so users only ever have 1 profile image) 
        global $TABLE_PREFIX; 
       
        // create query 
        $where  = mysql_escapef(" WHERE tableName = 'accounts' AND recordNum = ? AND num != ?", $CURRENT_USER['num'], $newUploadNums[0]); 
       
        // remove upload files 
        $query  = "SELECT * FROM `{$TABLE_PREFIX}uploads` $where"; 
        $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n"); 
        while ($row = mysql_fetch_assoc($result)) { 
          $files = array($row['filePath'], $row['thumbFilePath'], @$row['thumbFilePath2'], @$row['thumbFilePath3'], @$row['thumbFilePath4']); 
          foreach ($files as $filepath) { 
            if (!$filepath || !file_exists($filepath) || @unlink($filepath)) { continue; } 
       
            //$error  = "Unable to remove file '" .htmlspecialchars($filepath). "'\n\n"; 
            //$error .= "Please ask your server administrator to check permissions on that file and directory.\n\n"; 
            //$error .= "The PHP error message was: $php_errormsg\n"; 
            //die($error); 
          } 
        } 
        if (is_resource($result)) { mysql_free_result($result); } 
       
        // remove upload records 
        mysql_query("DELETE FROM `{$TABLE_PREFIX}uploads` $where") or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n"); 
      } 
     
    }
	
    // update user
    if (!$errorsAndAlerts) {
      mysqlStrictMode(false);   // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
      if (@$_REQUEST['newPassword2']) { $CURRENT_USER['password'] = $_REQUEST['newPassword2']; } // update password

      // update password if needed
      $password         = @$_REQUEST['newPassword2'] ? @$_REQUEST['newPassword2'] : $CURRENT_USER['password'];
      if (@$SETTINGS['advanced']['encryptPasswords']) { $passwordHash = getPasswordDigest($password); }
      else                                            { $passwordHash = $password; }

      //
      $query = "UPDATE `{$TABLE_PREFIX}" . @$GLOBALS['WSM_ACCOUNTS_TABLE'] . "` SET
                      firstname         = '".mysql_escape( $_REQUEST['firstname'] )."',
                      lastname         = '".mysql_escape( $_REQUEST['lastname'] )."',
                      email            = '".mysql_escape( $_REQUEST['email'] )."',
                      username         = '".mysql_escape( $_REQUEST['email'] )."',
                      password         = '".mysql_escape( $passwordHash )."',
					  state         = '".mysql_escape( $_REQUEST['state'] )."',
					  address         = '".mysql_escape( $_REQUEST['address'] )."',
					  zip         = '".mysql_escape( $_REQUEST['zip'] )."',
					  phone         = '".mysql_escape( $_REQUEST['phone'] )."',
					  website_title         = '".mysql_escape( $_REQUEST['website_title'] )."',
					  url         = '".mysql_escape( $_REQUEST['url'] )."',
					  status         = '".mysql_escape( $_REQUEST['status'] )."',
					  brand         = '".mysql_escape( $_REQUEST['brand'] )."',
					  degital_or_film        = '".mysql_escape( $_REQUEST['degital_or_film'] )."',
					  category         = '".mysql_escape( $_REQUEST['category'] )."',
					  bio         = '".mysql_escape( $_REQUEST['bio'] )."',
					  premium         = '".mysql_escape( $_REQUEST['premium'] )."',
					  mail_magazine = '".intval( @$_REQUEST['mail_magazine'] )."',
					  news_letter = '".intval( @$_REQUEST['news_letter'] )."',
					  

                      updatedByUserNum = '".mysql_escape( $CURRENT_USER['num'] )."',
                      updatedDate      = NOW()
                 WHERE num = '".mysql_escape( $CURRENT_USER['num'] )."'";
      mysql_query($query) or die("MySQL Error:<br/>\n". htmlspecialchars(mysql_error()) . "\n");
      $userNum = mysql_insert_id();

      // on success
      unset($_REQUEST['oldPassword'], $_REQUEST['newPassword1'], $_REQUEST['newPassword2']); // clear password fields
      $errorsAndAlerts = "Thanks, we've updated your profile!";
    }
  }

  // delete account
  if (@$_POST['deleteAccount']) {
    if ($CURRENT_USER['isAdmin']) { die("Error: Deleting admin accounts is not permitted!"); }

    // delete uploads
    $GLOBALS['tableName'] = $GLOBALS['WSM_ACCOUNTS_TABLE'];
    eraseRecordsUploads( $CURRENT_USER['num'] );

    // delete account
    $query = mysql_escapef("DELETE FROM `{$TABLE_PREFIX}accounts` WHERE num = ?", $CURRENT_USER['num']);
    mysql_query($query) or die("MySQL Error:<br/>\n". htmlspecialchars(mysql_error()) . "\n");

    // redirect to login
    websiteLogin_redirectToLogin();
  }




?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
  body, td { font-family: arial; font-size: 14px; }
</style>
</head>
<body>

<h1>Sample Edit Profile Page</h1>

<!-- EDIT PROFILE FORM -->
  <?php if (@$errorsAndAlerts): ?>
    <div style="color: #C00; font-weight: bold; font-size: 14px; font-family: arial;"><br/>
      <?php echo $errorsAndAlerts; ?><br/><br/>
    </div>
  <?php endif ?>
<p>(*)are required entry.<br />
You can always come back to edit or update your portfolio, but once the 'Update' button is pressed, the changes you've made will reflect your portfolio papge so be sure you have entered the right information.<br />
The only fields that will appear on your portfolio page is your<br />
-First Name<br />
-Last Name<br />
-State<br />
-Website Title<br />
-Website URL<br />
-Category<br />
-Biography<br />
and<br />
-Photograph Images
<br />
Here is a demo page of a portfolio page.<br />
Regular Member Page<br />
Premium Member Page<br />

  <form method="post" action="<?php echo $GLOBALS['WEBSITE_LOGIN_PROFILE_URL'];?>" enctype="multipart/form-data">
  <input type="hidden" name="save" value="1" />

  <table border="0" cellspacing="0" cellpadding="2">
   <tr>
    <td>*First Name</td>
    <td><input type="text" name="firstlname" value="<?php echo htmlspecialchars(@$_REQUEST['firstname']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>*Last Name</td>
    <td><input type="text" name="lastlname" value="<?php echo htmlspecialchars(@$_REQUEST['lastname']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>*Email</td>
    <td><input type="text" name="email" value="<?php echo htmlspecialchars(@$_REQUEST['email']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>*State</td>
    <td>
    <?php $fieldname = 'state'; ?>
	<?php $idCounter = 0; ?>
	<?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?>
	<?php $id = "$fieldname." . ++$idCounter; ?>
    <input type="radio" name="<?php echo $fieldname ?>" id="<?php echo $id ?>"
    value="<?php echo htmlspecialchars($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?> />
    <label for="<?php echo $id ?>"><?php echo htmlspecialchars($value) ?></label>
	<?php endforeach ?>
    </td>
   </tr>
   <tr>
    <td>*Address</td>
    <td><input type="text" name="address" value="<?php echo htmlspecialchars(@$_REQUEST['address']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>*Zip code</td>
    <td><input type="text" name="zip" value="<?php echo htmlspecialchars(@$_REQUEST['zip']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>Phone number</td>
    <td><input type="text" name="phone" value="<?php echo htmlspecialchars(@$_REQUEST['phone']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>Your Official Website Title</td>
    <td>(ex. My Works)<br />
<input type="text" name="website_title" value="<?php echo htmlspecialchars(@$_REQUEST['website_title']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>URL</td>
    <td>(ex. http://www.example.com)<br />
<input type="text" name="url" value="<?php echo htmlspecialchars(@$_REQUEST['url']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>Your Status as a photographer</td>
    <td>
    <?php $fieldname = 'status'; ?>
	<?php $idCounter = 0; ?>
	<?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?>
	<?php $id = "$fieldname." . ++$idCounter; ?>
    <input type="radio" name="<?php echo $fieldname ?>" id="<?php echo $id ?>"
    value="<?php echo htmlspecialchars($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?> />
    <label for="<?php echo $id ?>"><?php echo htmlspecialchars($value) ?></label>
	<?php endforeach ?>
</td>
   </tr>
   <tr>
    <td>Do you use degital or film camera?</td>
    <td>(Choose one or both)<br />
    <?php $fieldname = 'degital_or_film'; ?> 
     <?php 
    if(is_array(@$_REQUEST[$fieldname])){ 
      $fieldValues = $_REQUEST[$fieldname]; 
    } 
    else{ 
      $fieldValues = explode("\t",trim(@$_REQUEST[$fieldname],"\t")); 
    } 
  ?>
     <?php $idCounter = 0; ?> 
     <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?> 
       <?php $id = "$fieldname." . ++$idCounter; ?> 
       <input type="checkbox" name="<?php echo $fieldname ?>"[] id="<?php echo $id ?>" 
             value="<?php echo htmlspecialchars($value) ?>" <?php if(in_array($value,$fieldValues)):?> checked="checked" <?php endif ?>/> 
       <label for="<?php echo $id ?>"><?php echo htmlspecialchars($value) ?></label><br/> 
 
     <?php endforeach ?>
    </td>
   </tr>
   <tr>
    <td>Your camera brand</td>
    <td>(Choose one or more)<br />
    <?php $fieldname = 'brand'; ?> 
     <?php 
    if(is_array(@$_REQUEST[$fieldname])){ 
      $fieldValues = $_REQUEST[$fieldname]; 
    } 
    else{ 
      $fieldValues = explode("\t",trim(@$_REQUEST[$fieldname],"\t")); 
    } 
  ?>
     <?php $idCounter = 0; ?> 
     <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?> 
       <?php $id = "$fieldname." . ++$idCounter; ?> 
       <input type="checkbox" name="<?php echo $fieldname ?>"[] id="<?php echo $id ?>" 
             value="<?php echo htmlspecialchars($value) ?>" <?php if(in_array($value,$fieldValues)):?> checked="checked" <?php endif ?>/> 
       <label for="<?php echo $id ?>"><?php echo htmlspecialchars($value) ?></label><br/> 
 
     <?php endforeach ?>
    If you have chosen 'Others' and would like to add your camera brand to our list, please let us know. Contact
</td>
   </tr>
   <tr>
    <td>Category of your works</td>
    <td>(Choose one or more)<br />
    <?php $fieldname = 'category'; ?> 
     <?php 
    if(is_array(@$_REQUEST[$fieldname])){ 
      $fieldValues = $_REQUEST[$fieldname]; 
    } 
    else{ 
      $fieldValues = explode("\t",trim(@$_REQUEST[$fieldname],"\t")); 
    } 
  ?>
     <?php $idCounter = 0; ?> 
     <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?> 
       <?php $id = "$fieldname." . ++$idCounter; ?> 
       <input type="checkbox" name="<?php echo $fieldname ?>"[] id="<?php echo $id ?>" 
             value="<?php echo htmlspecialchars($value) ?>" <?php if(in_array($value,$fieldValues)):?> checked="checked" <?php endif ?>/> 
       <label for="<?php echo $id ?>"><?php echo htmlspecialchars($value) ?></label><br/> 
 
     <?php endforeach ?>
</td>
   </tr>
   <tr>
    <td>Enter your biography</td>
    <td><textarea name="bio" COLS=100 ROWS=30> <?php echo htmlspecialchars(@$_REQUEST['bio']); ?></textarea></td>
   </tr>
   <tr>
   <td>Premium Membership</td>
    <td><input type="checkbox" name="premium" value="1" <?php if(@$_REQUEST['premium']){echo "checked='checked'";}?> />Yes, I am a Premium Member<br /><br />
What is a <a href="premium_info.php">Premium Membership?</a><br />
<a href="premium-signup.php">Become a Premium Membership</a><br />
If you no longer want to be a Premium Membership, please contact the staff. Contact</td>
   </tr>
    <tr>
    <td>Subscribe Mail Magazine</td>
    <td><input type="checkbox" name="mail_magazinie" value = "1" <?php checkedIf("1", @$_REQUEST['mail_magazine']);?> />
    (News and information in general)</td>
   </tr>
   <td>Subscribe News Letter for members</td>
    <td><input type="checkbox" name="news_letter" value = "1" <?php checkedIf("1", @$_REQUEST['news_letter']);?> />(Information only for Photographers, such as recruiting group exhibition members at our gallery. )</td>
   </tr>
   
   <tr> 
    <td valign="top">Main Image</td> 
    <td> 
      <?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?> 
      <?php if (sizeof(@$current_user_with_uploads['main_image'])): 
        $upload = $current_user_with_uploads['main_image'][0] ?> 
        <a href="<?php echo $upload['urlPath'] ?>"> 
          <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br/> 
        </a> 
      <?php else: ?> 
        No image uploaded<br /> 
      <?php endif ?> 
      Upload: <input type="file" name="main_image"> 
    </td> 
   </tr>
   
    <tr> 
    <td valign="top">Sub Image<br />
1</td> 
    <td>You can upload 3 images as an option. The images will appear in these order.<br />
      <?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?> 
      <?php if (sizeof(@$current_user_with_uploads['sub1_image'])): 
        $upload = $current_user_with_uploads['sub1_image'][0] ?> 
        <a href="<?php echo $upload['urlPath'] ?>"> 
          <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br/> 
        </a> 
      <?php else: ?> 
        No image uploaded<br /> 
      <?php endif ?> 
      Upload: <input type="file" name="sub1_image"> 
    </td> 
   </tr>
   
   <tr> 
    <td valign="top">2</td> 
    <td>
      <?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?> 
      <?php if (sizeof(@$current_user_with_uploads['sub2_image'])): 
        $upload = $current_user_with_uploads['sub2_image'][0] ?> 
        <a href="<?php echo $upload['urlPath'] ?>"> 
          <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br/> 
        </a> 
      <?php else: ?> 
        No image uploaded<br /> 
      <?php endif ?> 
      Upload: <input type="file" name="sub2_image"> 
    </td> 
   </tr>
   
   <tr> 
    <td valign="top">3</td> 
    <td>
      <?php list(list($current_user_with_uploads),) = getRecords(array('tableName' => 'accounts', 'where' => mysql_escapef('num = ?', $CURRENT_USER['num']), 'allowSearch' => false)); ?> 
      <?php if (sizeof(@$current_user_with_uploads['sub3_image'])): 
        $upload = $current_user_with_uploads['sub3_image'][0] ?> 
        <a href="<?php echo $upload['urlPath'] ?>"> 
          <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br/> 
        </a> 
      <?php else: ?> 
        No image uploaded<br /> 
      <?php endif ?> 
      Upload: <input type="file" name="sub3_image"> 
    </td> 
   </tr>

   <tr><td colspan="2">&nbsp;</td></tr>

   <tr>
    <td>Current Password</td>
    <td><input type="password" name="oldPassword" value="<?php echo htmlspecialchars(@$_REQUEST['oldPassword']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>New Password</td>
    <td><input type="password" name="newPassword1" value="<?php echo htmlspecialchars(@$_REQUEST['newPassword1']); ?>" size="50" /></td>
   </tr>
   <tr>
    <td>New Password (again)</td>
    <td><input type="password" name="newPassword2" value="<?php echo htmlspecialchars(@$_REQUEST['newPassword2']); ?>" size="50" /></td>
   </tr>

   <tr>
    <td colspan="2" align="center">
      <br/><input class="button" type="submit" name="submit" value="Update profile &gt;&gt;" />
    </td>
   </tr>
  </table>
   <tr>
    <td colspan="2" align="center">
      <br/>Your Portfolio Page
    </td>
   </tr>
  </table>

  </form><br/>
<!-- /EDIT PROFILE FORM -->


<!-- REMOVE PROFILE FORM -->
<div style="border: 1px solid #000; background-color: #EEE; padding: 20px; width: 500px">
  <b>Delete Account</b>
  <p>If you want to delete your account you can do so here.<br/>
  Please note that all data will be lost and this is irreversible.</p>

  <form method="post" action="?" onsubmit="return confirm('Are you sure you want to delete your account?')">
  <input type="submit" name="deleteAccount" value="Delete Account" />
  </form>
</div>
<!-- /REMOVE PROFILE FORM -->

</body>
</html>
