function checkSubmitSiteChallenge($log)
 {
     //echo 'log action:' . $log->action . '<br>';
     if (!(array_search($log->action, array_keys(self::$siteChallengeActions)) === false)) {
         //echo 'found action in siteChallengeActions<br>';
         require_once PATH_CORE . '/classes/challenges.class.php';
         $ct = new ChallengeCompletedTable($this->db);
         if (!$ct->submitAutomaticChallenge($log->userid1, $log->action, &$statuscode, self::$siteChallengeActions[$log->action], $log->id)) {
             //echo $statuscode; // TODO: take this out when done testing
             //$this->db->log($statuscode);
         }
         //echo $statuscode; // TODO: take this out when done testing
         //$this->db->log("checkSubmitSiteChallenge $log->action: $statuscode dontLog: ".self::$siteChallengeActions[$log->action]);
         //$this->db->log(print_r(self::$siteChallengeActions, true));
         // update cached user vars for select site actions
         require_once PATH_CORE . '/classes/user.class.php';
         $ut = new UserTable($this->db);
         $uit = new UserInfoTable($this->db);
         $user = $ut->getRowObject();
         $userinfo = $uit->getRowObject();
         switch ($log->action) {
             case 'invite':
                 if ($userinfo->load($log->userid1)) {
                     $userinfo->cachedFriendsInvited++;
                     $userinfo->update();
                 }
                 break;
             case 'comment':
                 if ($user->load($log->userid1)) {
                     $user->cachedCommentsPosted++;
                     $user->update();
                 }
                 break;
             case 'postStory':
             case 'postBlog':
                 if ($user->load($log->userid1)) {
                     $user->cachedStoriesPosted++;
                     $user->update();
                 }
                 break;
             default:
                 break;
         }
     }
 }
 function rewardBetaTesters()
 {
     $testers = array();
     require_once PATH_CORE . '/classes/user.class.php';
     require_once PATH_CORE . '/classes/challenges.class.php';
     $ct = new ChallengeCompletedTable($this->db);
     $cc = $ct->getRowObject();
     $challengeTable = new ChallengeTable($this->db);
     $betaTestChallenge = $challengeTable->getRowObject();
     if (!$betaTestChallenge->loadWhere("shortName='betaTest'")) {
         echo "Couldn't find betaTest challenge";
         return false;
     }
     $userTable = new UserTable($this->db);
     $user = $userTable->getRowObject();
     $backdate = "2009-02-28 00:00:00";
     foreach ($testers as $email) {
         if ($user->loadWhere("email='{$email}'")) {
             echo "User {$user->name}, {$email} found...";
             $statuscode = '';
             if (!$ct->submitAutomaticChallenge($user->userid, 'betaTest', &$statuscode, false)) {
                 echo "Challenge approval failure: {$statuscode}";
             } else {
                 echo $statuscode;
                 // TODO: take this out when done testing
                 //$this->db->log($statuscode);
                 // now backdate it!
                 if ($cc->loadWhere("userid={$user->userid} AND challengeid={$betaTestChallenge->id}")) {
                     //$cc->dateSubmitted = $backdate; // can leave this probably
                     $cc->dateAwarded = $backdate;
                     $cc->update();
                     echo "...backdated succesfully";
                 } else {
                     echo "Couldnt find CC to backdate!";
                 }
             }
         } else {
             echo "No user found with email {$email}.";
         }
         echo "<br />";
     }
 }
*/
///////////////////////////
// NEW
require_once PATH_CORE . '/classes/user.class.php';
$ut = new UserInfoTable();
$memberids = $ut->getFbIdsForUsers(array($completed_challenge['userid']));
$memberid = $memberids[0];
echo '<a href="' . URL_CANVAS . '?p=profile&memberid=' . $memberid . '&viewSubmitted">
	Click here to see profile with challenge submit records</a>';
//echo 'this is where the report goes';
////////////////////////////////////////////////////////////////
// figure out how many points would normally be credited
require_once PATH_CORE . '/classes/challenges.class.php';
$ct = new ChallengeTable();
//$this->db->setDebug(true);
$completedTable = new ChallengeCompletedTable();
$completed = $completedTable->getRowObject();
if ($completed->load($completed_challenge['id'])) {
    $challenge = $ct->getRowObject();
    if ($challenge->load($completed->challengeid)) {
        $points = $challenge->pointValue;
    } else {
        $points = '?';
        echo 'oops, couldnt load challenge ' . $completed->challengeid;
    }
}
echo '<hr>';
echo 'Challenge title: ' . $challenge->title . '<br>';
echo 'Challenge description: ' . $challenge->description . '<br>';
//echo 'Challenge title: '.$challenge->title .'<br>';
echo '<hr>';
    $prizeTable = new PrizeTable($manageObj->db);
}
if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'video.class.php')) {
    // create video table
    require_once PATH_CORE . '/classes/video.class.php';
    VideoTable::createTable($manageObj);
}
if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'photo.class.php')) {
    // create photo table
    require_once PATH_CORE . '/classes/photo.class.php';
    PhotoTable::createTable($manageObj);
}
if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'challenges.class.php')) {
    require_once PATH_CORE . '/classes/challenges.class.php';
    ChallengeTable::createTable($manageObj);
    ChallengeCompletedTable::createTable($manageObj);
    $challengeTable = new ChallengeTable($manageObj->db);
    $challengeTable->populateCommonChallenges();
}
if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'scores.class.php')) {
    require_once PATH_CORE . '/classes/scores.class.php';
    WeeklyScoresTable::createTable($manageObj);
}
if ($manageObj->modifyLibrary(PATH_CORE . '/classes/', 'contactEmails.class.php')) {
    // Create ContactEmail table for the contact us functions
    require_once PATH_CORE . '/classes/contactEmails.class.php';
    ContactEmailTable::createTable($manageObj);
    $contactemailTable = new ContactEmailTable($manageObj->db);
    //$contactemailTable->testPopulate();
}
// Create FeaturedTemplate table for the contact us functions
 static function processChallengeSubmit(&$code, &$passback)
 {
     //$debug = $_POST['debugSubmit']; // NEVER TURN ON FOR LIVE SITE
     echo '<h2>Processing, please wait...</h2>';
     if ($debug) {
         echo "POST<pre>" . print_r($_POST, true) . "</pre>";
     }
     // TODO: grab session keys from post, validate session
     $passback .= "&text={$_POST['text']}";
     $passback .= "&embedCode={$_POST['embedCode']}";
     if ($debug) {
         echo $passback;
     }
     if (isset($_POST['challengeid']) && $_POST['challengeid']) {
         $challengeid = $_POST['challengeid'];
     } else {
         $code = "There was no challenge id present in your submission";
         return false;
     }
     if (isset($_POST['text'])) {
         $evidence = $_POST['text'];
     } else {
         $evidence = '';
         /*$code = "Your text submission was empty."; return false;*/
     }
     if (isset($_POST['userid']) && $_POST['userid']) {
         $userid = $_POST['userid'];
     } else {
         $code = 'Either you aren\'t a registered user or your session is expired. Please return to the home page or sign in to facebook again.';
         return false;
     }
     require_once PATH_CORE . '/classes/db.class.php';
     $db = new cloudDatabase();
     // create a CompletedChallenges object
     //$userid = $this->page->session->userid;
     /*	if (!$userid)
     		{
     			echo "<pre>" . print_r($this->page->session, true) . "</pre>";	
     			
     			return "Could not get userid from session."; 
     		}*/
     require_once PATH_CORE . '/classes/user.class.php';
     require_once PATH_CORE . '/classes/challenges.class.php';
     $challengeTable = new ChallengeTable($db);
     $userTable = new UserTable($db);
     $userInfoTable = new UserInfoTable($db);
     $completedTable = new ChallengeCompletedTable($db);
     $user = $userTable->getRowObject();
     $userInfo = $userInfoTable->getRowObject();
     $challenge = $challengeTable->getRowObject();
     $completed = $completedTable->getRowObject();
     dbRowObject::$debug = $debug;
     $user->load($userid);
     $userInfo->load($userid);
     $challenge->load($challengeid);
     // validate challenge submission info
     // validate eligibility, date, membership
     if ($challenge->remainingCompletions <= 0 && $challenge->initialCompletions > 0) {
         $code = 'This challenge can no longer be completed for credit.';
         return false;
     }
     if (!ChallengeTable::userIsEligible($challenge->eligibility, $user->eligibility)) {
         $code = 'We\'re sorry, you are not eligible to receive credit for this challenge.';
         return false;
     }
     if (preg_match("/text/i", $challenge->requires) && !($evidence != '')) {
         $code = 'Sorry, you need to convince us you actually did this!';
         return false;
     }
     //if () //  TODO: now is between date start and end
     $now = time();
     $dateStart = strtotime($challenge->dateStart);
     $dateEnd = strtotime($challenge->dateEnd);
     if ($now > $dateEnd) {
         $code = 'Sorry, you are too late to receive credit for this challenge!';
         return false;
     }
     if ($now < $dateStart) {
         $code = 'Sorry, you can\'t receive credit for this challenge yet -- try again later!';
         return false;
     }
     // if () TODO: check user maximum by querying order histor
     // more...
     // everythings ok:
     $challenge->remainingCompletions--;
     $completed->userid = $user->userid;
     $completed->challengeid = $challenge->id;
     $phpnow = time();
     $completed->dateSubmitted = date('Y-m-d H:i:s', $phpnow);
     $completed->status = 'submitted';
     $completed->evidence = $evidence;
     $completed->comments = $evidence;
     // editors will review these later
     /*
      * The following code is a bit tricky. There are two things going on. The first is that photos
      * or videos are being checked for and their records are being created, but we have 
      * tentatively created a CompleteChallenge record first so they can back-reference it
      * 
      * If a required photo or video turns out not to have appeared, we have to then return an error 
      * and delete the CC record.
      * 
      * An extra wrinkle is that if both video and photo are in the requires field, we can accept 
      * one or the other.
      * 
      */
     // Create the completed to attach to the media records...
     if (!$completed->insert()) {
         $code = 'Internal error submitting your evidence, please try again.';
         return false;
     }
     if (preg_match("/photo/i", $challenge->requires) || preg_match("/optionalphoto/i", $challenge->requires)) {
         if ($photoFilename = self::processChallengeSubmitPhoto($userid, $completed->id)) {
             if (!preg_match("/\\.(jpg|png|gif|jpeg?)\$/i", $photoFilename)) {
                 $msg = 'Sorry, your photo did not appear to be of type jpg, png, or gif.';
                 $error = true;
             } else {
                 // create photo in our db
                 require_once PATH_CORE . '/classes/photo.class.php';
                 $photoTable = new PhotoTable($db);
                 $photoTable->createPhotoForCompletedChallenge($userid, $completed->id, $photoFilename, 'Photo submitted for ' . $challenge->title);
                 $photoSubmitted = true;
                 // indicate that a photo was found
             }
         } else {
             if (!preg_match("/optionalphoto/i", $challenge->requires)) {
                 $msg = 'No photo submitted';
                 $error = true;
             }
         }
     }
     //$passback .= "&photo1={$photoFilename}"; // wont be correct filename, actually quite complicated to make this work properly
     //echo $passback;
     if (preg_match("/video/i", $challenge->requires)) {
         if ($videoEmbedCode = self::processChallengeSubmitVideo($userid, $completed->id)) {
             // create photo in our db
             require_once PATH_CORE . '/classes/video.class.php';
             $videoTable = new VideoTable($db);
             $videoTable->createVideoForCompletedChallenge($userid, $completed->id, $videoEmbedCode, 'Video submitted for ' . $challenge->title);
             $videoSubmitted = true;
             // indicate video found
         } else {
             $msg = 'You must enter a YouTube video url.';
             $error = true;
         }
     }
     // HACK: now handle the case where both photo and video boxes appeared, and only one was entered
     if ($photoSubmitted or $videoSubmitted) {
         $error = false;
     }
     // set the $error flag set by the other one to false if one of them was sucessfully created
     if ($error) {
         $completed->delete();
         // delete the temporary CC record
         $code = $msg;
         return false;
     }
     $challenge->update();
     require_once PATH_CORE . '/classes/template.class.php';
     $code .= 'We have received your submission for the challenge <b>' . $challenge->title . '</b>  (reference number #' . $completed->id . ')';
     dbRowObject::$debug = 0;
     // NEVER TURN ON FOR LIVE SITE
     // for testing purposes -- approve free points right away
     if ($challenge->shortName == 'testPoints10k') {
         $code2 = '';
         if (!$completedTable->approveChallenge($completed->id, $challenge->pointValue, &$code2, false)) {
             $code = $code2;
             return false;
         } else {
             $code = 'Free points awarded!';
         }
     }
     return true;
 }
    function fetchChallengeCompletedFeedItem($action, $fbId, $returnerrors = false, $noFiltering = false)
    {
        $ago .= self::getElapsedString(strtotime($action->t));
        require_once PATH_CORE . '/classes/template.class.php';
        require_once PATH_CORE . '/classes/challenges.class.php';
        $ct = new ChallengeTable($this->db);
        // $this->db->setDebug(true); // NEVER TURN ON FOR LIVE SITE
        $completedTable = new ChallengeCompletedTable($this->db);
        $completed = $completedTable->getRowObject();
        if (!$action->itemid) {
            if ($returnerrors) {
                $code = 'completedChallenge itemid empty:' . print_r($action, true);
            }
            return;
        }
        if ($completed->load($action->itemid)) {
            $challenge = $ct->getRowObject();
            if ($challenge->load($completed->challengeid)) {
                // hack to cleanup actionFeed of CCs that should be hidden or now have custom feed items
                $filterPastChallenges = array('levelIncrease', 'addBookmarkTool', 'friendSignup');
                if (!$noFiltering && array_search($challenge->shortName, $filterPastChallenges) !== false) {
                    return '';
                }
                // filtered
                $photocode = $this->buildPhotos($completed->id, &$pcount);
                if ($pcount > 1) {
                    $submittedText .= 'photos ';
                    $submittedContent .= $photocode;
                } else {
                    if ($pcount > 0) {
                        $submittedText .= 'a photo ';
                        $submittedContent .= $photocode;
                    }
                }
                $videocode = $this->buildVideos($completed->id, &$vcount);
                if ($pcount > 0 and $vcount > 0) {
                    $submittedText .= ' and ';
                }
                if ($vcount > 1) {
                    $submittedText .= 'videos ';
                    $submittedContent .= $videocode;
                } else {
                    if ($vcount > 0) {
                        $submittedText .= 'a video ';
                        $submittedContent .= $videocode;
                    }
                }
                if ($completed->status == 'awarded') {
                    /*$code .= template::buildLinkedProfilePic($fbIds[0], 'size="square"') .' '. template::buildLinkedProfileName($fbId)
                    			.' completed the challenge '. template::buildChallengeLink($challenge->title, $challenge->id) . 
                    			' for ' . $completed->pointsAwarded 
                    			. ' points and submitted ' . $submittedText;
                    		*/
                    if (!$this->showOnlyChallengeBlog) {
                        $code .= '<div class="thumb">' . template::buildLinkedChallengePic($challenge->id, $challenge->thumbnail) . '</div>
					                <div class="storyBlockWrap">
					                	<div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbId, 'size="square"  with="30" height="30"') . '</div>
					                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbId) . ' completed a challenge					                   
					            			</span> ' . $ago . '</h3>
				            			</div>
					                    <p class="storyHead">' . template::buildChallengeLink($challenge->title, $challenge->id) . ' </p>
					                    <p class="storyCaption"> <span class="pointValue"> for ' . $completed->pointsAwarded . '<span class="pts"> points </span></span></p>
					                    ' . $submittedContent . ($completed->comments != '' ? ' <blockquote>
												<div class="quotes">' . $completed->comments . '
						               			</div>
						               		</blockquote>' : '') . '</div><!__end "storyBlockWrap"__>
					            	';
                    } else {
                        $code .= '<div class="profilePicLarger">' . template::buildLinkedProfilePic($fbId, 'size="square"') . '</div>
					                <div class="storyBlockWrap">
					                	<div class="feed_poster">
					                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbId) . ' 
					                    
					            			</span> ' . $ago . '</h3>
				            			</div>					              					                    
					                    ' . $submittedContent . ($completed->comments != '' ? ' <blockquote>
						                    	<div class="quotes">
						               				' . $completed->comments . '
						               			</div>
						               		</blockquote>' : '') . '</div><!__end "storyBlockWrap"__>
					            	';
                    }
                } else {
                    /*$code .= template::buildLinkedProfilePic($fbIds[0], 'size="square"') .' '. template::buildLinkedProfileName($fbId)
                    				.' submitted '. $submittedText 
                    				. 'for the challenge '. template::buildChallengeLink($challenge->title, $challenge->id); 
                    		*/
                    $code .= '<div class="thumb">' . template::buildLinkedChallengePic($challenge->id, $challenge->thumbnail) . '</div>
			                <div class="storyBlockWrap">
			                	<div class="feed_poster"><div class="avatar">' . template::buildLinkedProfilePic($fbId, 'size="square" with="30" height="30"') . '</div>
			                    	<h3><span class="bold">' . template::buildLinkedProfileName($fbId) . ' submitted ' . $submittedText . ' for the challenge ' . template::buildChallengeLink($challenge->title, $challenge->id) . '
			                    
			            			</span> ' . $ago . '</h3>
		            			</div>' . '<p class="storyCaption">' . $submittedContent . '</p>                
			                </div><!__end "storyBlockWrap"__>
			            	';
                }
                //$code .= self::getElapsedString(strtotime($action->t));
            } else {
                if ($returnerrors) {
                    $code = 'Couldnt load challengeid ' . $completed->id . '<br>';
                }
            }
            // debugging
        } else {
            if ($returnerrors) {
                $code = 'Couldnt load completedid ' . $action->itemid . '<br>';
            }
        }
        // debugging
        return $code;
    }
 public function approve_completed_challenge()
 {
     // slight hack, since this now handles rejection as well
     if (isset($_POST['completed_challenge']['id']) && preg_match('/^[0-9]+$/', $_POST['completed_challenge']['id'])) {
         $id = $_POST['completed_challenge']['id'];
     } else {
         set_flash(array('error' => "Invalid {$group} -- {$action} -- id: {$id}."));
         redirect(url_for('street_team', 'completed_challenges'));
     }
     if ($_POST['reject']) {
         /*
         					 * 
         					//$_POST['completed_challenge[status]']='rejected'; // set status to rejected
         					// update to set comment text
         					if (($result = $this->db->update($_POST['completed_challenge'])) == 1) 
         					{
         */
         // grrr russell
         require_once PATH_CORE . '/classes/challenges.class.php';
         $cct = new ChallengeCompletedTable();
         $cc = $cct->getRowObject();
         if ($cc->load($id)) {
             $cc->status = 'rejected';
             $cc->update();
             set_flash(array('notice' => "Challenge submission {$id} rejected."));
             redirect(url_for('street_team', 'view_completed_challenge', $id));
         } else {
             set_flash(array('error' => 'Could not update your completed_challenge! Please try again. ' . $result));
             redirect(url_for('street_team', 'modify_completed_challenge', $id));
         }
     } elseif (isset($_POST['pointsAwarded'])) {
         // update to set comment text
         if (($result = $this->db->update($_POST['completed_challenge'])) == 1) {
         } else {
             set_flash(array('error' => 'Could not update your completed_challenge! Please try again. ' . $result));
             redirect(url_for('street_team', 'modify_completed_challenge', $id));
         }
         // djm:
         require_once PATH_CORE . '/classes/challenges.class.php';
         $cct = new ChallengeCompletedTable();
         $cct->approveChallenge($id, $_POST['pointsAwarded'], &$code);
         /*
         					if (($result = $this->db->update($_POST['completed_challenge'])) == 1) 
         					{
         						set_flash(array('notice' => 'Successfully updated completed_challenge.'));
         						redirect(url_for('street_team', 'view_completed_challenge', $id));
         					} else 
         					{
         						set_flash(array('error' => 'Could not update your completed_challenge! Please try again. '.$result));
         						redirect(url_for('street_team', 'review_completed_challenge', $id));
         					}*/
         set_flash(array('notice' => $code));
         redirect(url_for('street_team', 'view_completed_challenge', $id));
     } else {
         set_flash(array('error' => 'Form data not submitted properly, please try again.'));
         redirect(url_for('street_team', 'view_completed_challenge', $id));
     }
 }